From a661017af4a9a40327576e2fb10f9ae0a143ee3b Mon Sep 17 00:00:00 2001 From: Hardik Date: Thu, 10 Aug 2023 15:40:49 +0530 Subject: [PATCH 01/81] Prevents auto-import in non-module files --- src/services/completions.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/services/completions.ts b/src/services/completions.ts index 764e64c32e104..88ede51f079f6 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1855,6 +1855,8 @@ namespace ts.Completions { function shouldOfferImportCompletions(): boolean { // If already typing an import statement, provide completions for it. if (importCompletionNode) return true; + // Prevents auto-import completions in non-module files. + if (program.getCompilerOptions().module === ModuleKind.None) return false; // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols if (isNonContextualObjectLiteral) return false; // If not already a module, must have modules enabled. From 28cd1fbd13b8d09259e7a7086aa258c0221c38ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Thu, 10 Aug 2023 21:50:21 +0200 Subject: [PATCH 02/81] Allow intersections to be used as valid types for template literal placeholders (#54188) --- src/compiler/checker.ts | 22 ++++++++++--- .../templateLiteralTypesPatterns.errors.txt | 16 +++++++-- .../reference/templateLiteralTypesPatterns.js | 19 ++++++++++- .../templateLiteralTypesPatterns.symbols | 25 ++++++++++++++ .../templateLiteralTypesPatterns.types | 33 +++++++++++++++++++ .../literal/templateLiteralTypesPatterns.ts | 10 ++++++ ...pletionsForOpenEndedTemplateLiteralType.ts | 6 ++++ 7 files changed, 123 insertions(+), 8 deletions(-) create mode 100644 tests/cases/fourslash/stringLiteralCompletionsForOpenEndedTemplateLiteralType.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 77afc6bf2083f..1865ecb9a7bb1 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16457,7 +16457,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function removeStringLiteralsMatchedByTemplateLiterals(types: Type[]) { - const templates = filter(types, t => !!(t.flags & TypeFlags.TemplateLiteral) && isPatternLiteralType(t)) as TemplateLiteralType[]; + const templates = filter(types, t => + !!(t.flags & TypeFlags.TemplateLiteral) && + isPatternLiteralType(t) && + (t as TemplateLiteralType).types.every(t => !(t.flags & TypeFlags.Intersection) || !areIntersectedTypesAvoidingPrimitiveReduction((t as IntersectionType).types)) + ) as TemplateLiteralType[]; if (templates.length) { let i = types.length; while (i > 0) { @@ -16966,8 +16970,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return reduceLeft(types, (n, t) => n + getConstituentCount(t), 0); } - function areIntersectedTypesAvoidingPrimitiveReduction(t1: Type, t2: Type) { - return !!(t1.flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt)) && t2 === emptyTypeLiteralType; + function areIntersectedTypesAvoidingPrimitiveReduction(types: Type[], primitiveFlags = TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt): boolean { + if (types.length !== 2) { + return false; + } + const [t1, t2] = types; + return !!(t1.flags & primitiveFlags) && t2 === emptyTypeLiteralType || !!(t2.flags & primitiveFlags) && t1 === emptyTypeLiteralType; } function getTypeFromIntersectionTypeNode(node: IntersectionTypeNode): Type { @@ -16975,7 +16983,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!links.resolvedType) { const aliasSymbol = getAliasSymbolForTypeNode(node); const types = map(node.types, getTypeFromTypeNode); - const noSupertypeReduction = types.length === 2 && (areIntersectedTypesAvoidingPrimitiveReduction(types[0], types[1]) || areIntersectedTypesAvoidingPrimitiveReduction(types[1], types[0])); + const noSupertypeReduction = areIntersectedTypesAvoidingPrimitiveReduction(types); links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); } return links.resolvedType; @@ -24362,12 +24370,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (source === target || target.flags & (TypeFlags.Any | TypeFlags.String)) { return true; } + if (target.flags & TypeFlags.Intersection) { + return every((target as IntersectionType).types, t => t === emptyTypeLiteralType || isValidTypeForTemplateLiteralPlaceholder(source, t)); + } if (source.flags & TypeFlags.StringLiteral) { const value = (source as StringLiteralType).value; return !!(target.flags & TypeFlags.Number && isValidNumberString(value, /*roundTripOnly*/ false) || target.flags & TypeFlags.BigInt && isValidBigIntString(value, /*roundTripOnly*/ false) || target.flags & (TypeFlags.BooleanLiteral | TypeFlags.Nullable) && value === (target as IntrinsicType).intrinsicName || - target.flags & TypeFlags.StringMapping && isMemberOfStringMapping(getStringLiteralType(value), target)); + target.flags & TypeFlags.StringMapping && isMemberOfStringMapping(getStringLiteralType(value), target) || + target.flags & TypeFlags.TemplateLiteral && isTypeMatchedByTemplateLiteralType(source, target as TemplateLiteralType)); } if (source.flags & TypeFlags.TemplateLiteral) { const texts = (source as TemplateLiteralType).texts; diff --git a/tests/baselines/reference/templateLiteralTypesPatterns.errors.txt b/tests/baselines/reference/templateLiteralTypesPatterns.errors.txt index e92c040be43ac..cd82afc83981b 100644 --- a/tests/baselines/reference/templateLiteralTypesPatterns.errors.txt +++ b/tests/baselines/reference/templateLiteralTypesPatterns.errors.txt @@ -55,9 +55,10 @@ templateLiteralTypesPatterns.ts(129,9): error TS2345: Argument of type '"1.1e-10 templateLiteralTypesPatterns.ts(140,1): error TS2322: Type '`a${string}`' is not assignable to type '`a${number}`'. templateLiteralTypesPatterns.ts(141,1): error TS2322: Type '"bno"' is not assignable to type '`a${any}`'. templateLiteralTypesPatterns.ts(160,7): error TS2322: Type '"anything"' is not assignable to type '`${number} ${number}`'. +templateLiteralTypesPatterns.ts(211,5): error TS2345: Argument of type '"abcTest"' is not assignable to parameter of type '`${`a${string}` & `${string}a`}Test`'. -==== templateLiteralTypesPatterns.ts (57 errors) ==== +==== templateLiteralTypesPatterns.ts (58 errors) ==== type RequiresLeadingSlash = `/${string}`; // ok @@ -373,4 +374,15 @@ templateLiteralTypesPatterns.ts(160,7): error TS2322: Type '"anything"' is not a this.get(id!); } } - \ No newline at end of file + + // repro from https://github.com/microsoft/TypeScript/issues/54177#issuecomment-1538436654 + function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {} + conversionTest("testDowncast"); + function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {} + conversionTest2("testDowncast"); + + function foo(str: `${`a${string}` & `${string}a`}Test`) {} + foo("abaTest"); // ok + foo("abcTest"); // error + ~~~~~~~~~ +!!! error TS2345: Argument of type '"abcTest"' is not assignable to parameter of type '`${`a${string}` & `${string}a`}Test`'. \ No newline at end of file diff --git a/tests/baselines/reference/templateLiteralTypesPatterns.js b/tests/baselines/reference/templateLiteralTypesPatterns.js index 7b3cb228da0da..d66c794e287a8 100644 --- a/tests/baselines/reference/templateLiteralTypesPatterns.js +++ b/tests/baselines/reference/templateLiteralTypesPatterns.js @@ -202,7 +202,16 @@ export abstract class BB { this.get(id!); } } - + +// repro from https://github.com/microsoft/TypeScript/issues/54177#issuecomment-1538436654 +function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {} +conversionTest("testDowncast"); +function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {} +conversionTest2("testDowncast"); + +function foo(str: `${`a${string}` & `${string}a`}Test`) {} +foo("abaTest"); // ok +foo("abcTest"); // error //// [templateLiteralTypesPatterns.js] "use strict"; @@ -353,3 +362,11 @@ var BB = /** @class */ (function () { return BB; }()); exports.BB = BB; +// repro from https://github.com/microsoft/TypeScript/issues/54177#issuecomment-1538436654 +function conversionTest(groupName) { } +conversionTest("testDowncast"); +function conversionTest2(groupName) { } +conversionTest2("testDowncast"); +function foo(str) { } +foo("abaTest"); // ok +foo("abcTest"); // error diff --git a/tests/baselines/reference/templateLiteralTypesPatterns.symbols b/tests/baselines/reference/templateLiteralTypesPatterns.symbols index 802d5ff263b72..cc508d2680959 100644 --- a/tests/baselines/reference/templateLiteralTypesPatterns.symbols +++ b/tests/baselines/reference/templateLiteralTypesPatterns.symbols @@ -487,3 +487,28 @@ export abstract class BB { } } +// repro from https://github.com/microsoft/TypeScript/issues/54177#issuecomment-1538436654 +function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {} +>conversionTest : Symbol(conversionTest, Decl(templateLiteralTypesPatterns.ts, 200, 1)) +>groupName : Symbol(groupName, Decl(templateLiteralTypesPatterns.ts, 203, 24)) + +conversionTest("testDowncast"); +>conversionTest : Symbol(conversionTest, Decl(templateLiteralTypesPatterns.ts, 200, 1)) + +function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {} +>conversionTest2 : Symbol(conversionTest2, Decl(templateLiteralTypesPatterns.ts, 204, 31)) +>groupName : Symbol(groupName, Decl(templateLiteralTypesPatterns.ts, 205, 25)) + +conversionTest2("testDowncast"); +>conversionTest2 : Symbol(conversionTest2, Decl(templateLiteralTypesPatterns.ts, 204, 31)) + +function foo(str: `${`a${string}` & `${string}a`}Test`) {} +>foo : Symbol(foo, Decl(templateLiteralTypesPatterns.ts, 206, 32)) +>str : Symbol(str, Decl(templateLiteralTypesPatterns.ts, 208, 13)) + +foo("abaTest"); // ok +>foo : Symbol(foo, Decl(templateLiteralTypesPatterns.ts, 206, 32)) + +foo("abcTest"); // error +>foo : Symbol(foo, Decl(templateLiteralTypesPatterns.ts, 206, 32)) + diff --git a/tests/baselines/reference/templateLiteralTypesPatterns.types b/tests/baselines/reference/templateLiteralTypesPatterns.types index d9176480bc7b0..d9fbfeec9d8b2 100644 --- a/tests/baselines/reference/templateLiteralTypesPatterns.types +++ b/tests/baselines/reference/templateLiteralTypesPatterns.types @@ -635,3 +635,36 @@ export abstract class BB { } } +// repro from https://github.com/microsoft/TypeScript/issues/54177#issuecomment-1538436654 +function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {} +>conversionTest : (groupName: "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) => void +>groupName : `${string & {}}Downcast` | "downcast" | "dataDowncast" | "editingDowncast" + +conversionTest("testDowncast"); +>conversionTest("testDowncast") : void +>conversionTest : (groupName: `${string & {}}Downcast` | "downcast" | "dataDowncast" | "editingDowncast") => void +>"testDowncast" : "testDowncast" + +function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {} +>conversionTest2 : (groupName: "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) => void +>groupName : "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast` + +conversionTest2("testDowncast"); +>conversionTest2("testDowncast") : void +>conversionTest2 : (groupName: "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) => void +>"testDowncast" : "testDowncast" + +function foo(str: `${`a${string}` & `${string}a`}Test`) {} +>foo : (str: `${`a${string}` & `${string}a`}Test`) => void +>str : `${`a${string}` & `${string}a`}Test` + +foo("abaTest"); // ok +>foo("abaTest") : void +>foo : (str: `${`a${string}` & `${string}a`}Test`) => void +>"abaTest" : "abaTest" + +foo("abcTest"); // error +>foo("abcTest") : void +>foo : (str: `${`a${string}` & `${string}a`}Test`) => void +>"abcTest" : "abcTest" + diff --git a/tests/cases/conformance/types/literal/templateLiteralTypesPatterns.ts b/tests/cases/conformance/types/literal/templateLiteralTypesPatterns.ts index a98facd4359a3..aeb05ead7ccca 100644 --- a/tests/cases/conformance/types/literal/templateLiteralTypesPatterns.ts +++ b/tests/cases/conformance/types/literal/templateLiteralTypesPatterns.ts @@ -200,3 +200,13 @@ export abstract class BB { this.get(id!); } } + +// repro from https://github.com/microsoft/TypeScript/issues/54177#issuecomment-1538436654 +function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {} +conversionTest("testDowncast"); +function conversionTest2(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${{} & string}Downcast`) {} +conversionTest2("testDowncast"); + +function foo(str: `${`a${string}` & `${string}a`}Test`) {} +foo("abaTest"); // ok +foo("abcTest"); // error \ No newline at end of file diff --git a/tests/cases/fourslash/stringLiteralCompletionsForOpenEndedTemplateLiteralType.ts b/tests/cases/fourslash/stringLiteralCompletionsForOpenEndedTemplateLiteralType.ts new file mode 100644 index 0000000000000..92c02a23a2854 --- /dev/null +++ b/tests/cases/fourslash/stringLiteralCompletionsForOpenEndedTemplateLiteralType.ts @@ -0,0 +1,6 @@ +/// + +//// function conversionTest(groupName: | "downcast" | "dataDowncast" | "editingDowncast" | `${string & {}}Downcast`) {} +//// conversionTest("/**/"); + +verify.completions({ marker: "", exact: ["downcast", "dataDowncast", "editingDowncast"] }); From 6b1f9bfcb7e59f5e1a97e5a2e5cbe2f67b07d220 Mon Sep 17 00:00:00 2001 From: Hardik Date: Fri, 11 Aug 2023 13:47:30 +0530 Subject: [PATCH 03/81] changing "compilerOptionsIndicateEs6Modules" --- src/services/completions.ts | 2 -- src/services/utilities.ts | 4 ++++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index 88ede51f079f6..764e64c32e104 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1855,8 +1855,6 @@ namespace ts.Completions { function shouldOfferImportCompletions(): boolean { // If already typing an import statement, provide completions for it. if (importCompletionNode) return true; - // Prevents auto-import completions in non-module files. - if (program.getCompilerOptions().module === ModuleKind.None) return false; // If current completion is for non-contextual Object literal shortahands, ignore auto-import symbols if (isNonContextualObjectLiteral) return false; // If not already a module, must have modules enabled. diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 533b816b8b380..1fa124282d9f0 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1840,6 +1840,10 @@ namespace ts { return program.getSourceFiles().some(s => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator); } export function compilerOptionsIndicateEs6Modules(compilerOptions: CompilerOptions): boolean { + // Prevent ES6 module indication for non-module files + if(compilerOptions.module === ModuleKind.None){ + return false; + } return !!compilerOptions.module || compilerOptions.target! >= ScriptTarget.ES2015 || !!compilerOptions.noEmit; } From b35fa04346b3888a7f0ddc580c3a79497f8edf1d Mon Sep 17 00:00:00 2001 From: lyonbot Date: Sat, 12 Aug 2023 00:51:05 +0800 Subject: [PATCH 04/81] Fix broken formatting rules around namespaced JSX attributes (#55294) --- src/services/formatting/rules.ts | 16 ++++++++++++++-- tests/cases/fourslash/formattingJsxTexts4.ts | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/formattingJsxTexts4.ts diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 9eb7635db8379..3d9c201a5050b 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -90,7 +90,7 @@ export function getAllRules(): RuleSpec[] { rule("IgnoreAfterLineComment", SyntaxKind.SingleLineCommentTrivia, anyToken, anyContext, RuleAction.StopProcessingSpaceActions), rule("NotSpaceBeforeColon", anyToken, SyntaxKind.ColonToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], RuleAction.DeleteSpace), - rule("SpaceAfterColon", SyntaxKind.ColonToken, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], RuleAction.InsertSpace), + rule("SpaceAfterColon", SyntaxKind.ColonToken, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNextTokenParentNotJsxNamespacedName], RuleAction.InsertSpace), rule("NoSpaceBeforeQuestionMark", anyToken, SyntaxKind.QuestionToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], RuleAction.DeleteSpace), // insert space after '?' only when it is used in conditional operator rule("SpaceAfterQuestionMarkInConditionalOperator", SyntaxKind.QuestionToken, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], RuleAction.InsertSpace), @@ -179,6 +179,8 @@ export function getAllRules(): RuleSpec[] { rule("NoSpaceBeforeGreaterThanTokenInJsxOpeningElement", SyntaxKind.SlashToken, SyntaxKind.GreaterThanToken, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), rule("NoSpaceBeforeEqualInJsxAttribute", anyToken, SyntaxKind.EqualsToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), rule("NoSpaceAfterEqualInJsxAttribute", SyntaxKind.EqualsToken, anyToken, [isJsxAttributeContext, isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), + rule("NoSpaceBeforeJsxNamespaceColon", SyntaxKind.Identifier, SyntaxKind.ColonToken, [isNextTokenParentJsxNamespacedName], RuleAction.DeleteSpace), + rule("NoSpaceAfterJsxNamespaceColon", SyntaxKind.ColonToken, SyntaxKind.Identifier, [isNextTokenParentJsxNamespacedName], RuleAction.DeleteSpace), // TypeScript-specific rules // Use of module as a function call. e.g.: import m2 = module("m2"); @@ -749,13 +751,23 @@ function isJsxExpressionContext(context: FormattingContext): boolean { } function isNextTokenParentJsxAttribute(context: FormattingContext): boolean { - return context.nextTokenParent.kind === SyntaxKind.JsxAttribute; + return context.nextTokenParent.kind === SyntaxKind.JsxAttribute || ( + context.nextTokenParent.kind === SyntaxKind.JsxNamespacedName && context.nextTokenParent.parent.kind === SyntaxKind.JsxAttribute + ); } function isJsxAttributeContext(context: FormattingContext): boolean { return context.contextNode.kind === SyntaxKind.JsxAttribute; } +function isNextTokenParentNotJsxNamespacedName(context: FormattingContext): boolean { + return context.nextTokenParent.kind !== SyntaxKind.JsxNamespacedName; +} + +function isNextTokenParentJsxNamespacedName(context: FormattingContext): boolean { + return context.nextTokenParent.kind === SyntaxKind.JsxNamespacedName; +} + function isJsxSelfClosingElementContext(context: FormattingContext): boolean { return context.contextNode.kind === SyntaxKind.JsxSelfClosingElement; } diff --git a/tests/cases/fourslash/formattingJsxTexts4.ts b/tests/cases/fourslash/formattingJsxTexts4.ts new file mode 100644 index 0000000000000..c9d238bf482d0 --- /dev/null +++ b/tests/cases/fourslash/formattingJsxTexts4.ts @@ -0,0 +1,19 @@ +/// + +// Github issue #55293 + +//@Filename: file.tsx +//// function foo() { +//// const a = ; +//// +//// return a; +//// } + +format.document(); + +verify.currentFileContentIs( +`function foo() { + const a = ; + + return a; +}`); From 3b43d841d15d4abe3a9b187dc4a3936cd416d408 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Fri, 11 Aug 2023 15:07:06 -0700 Subject: [PATCH 05/81] Enable eslint rules prefer-rest-params and prefer-spread (#55181) --- .eslintrc.json | 2 - src/compiler/checker.ts | 2 +- src/compiler/commandLineParser.ts | 6 +-- src/compiler/core.ts | 1 + src/compiler/moduleNameResolver.ts | 5 +-- src/compiler/utilities.ts | 44 ++++++++------------ src/deprecatedCompat/deprecate.ts | 3 +- src/executeCommandLine/executeCommandLine.ts | 8 ++-- src/harness/fourslashImpl.ts | 10 ++--- src/harness/harnessLanguageService.ts | 2 + src/services/services.ts | 6 +-- 11 files changed, 40 insertions(+), 49 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 1a81fa72497c6..0eb936e9be5c8 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -104,8 +104,6 @@ ], // Todo: For each of these, investigate whether we want to enable them ✨ - "prefer-rest-params": "off", - "prefer-spread": "off", "@typescript-eslint/no-unused-vars": "off", // Pending https://github.com/typescript-eslint/typescript-eslint/issues/4820 diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1865ecb9a7bb1..c43435bc001c5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19844,7 +19844,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const childrenPropName = childPropName === undefined ? "children" : unescapeLeadingUnderscores(childPropName); const childrenTargetType = getIndexedAccessType(target, getStringLiteralType(childrenPropName)); const diagnostic = Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; - invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", message: formatMessage(/*dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }; + invalidTextDiagnostic = { ...diagnostic, key: "!!ALREADY FORMATTED!!", message: formatMessage(diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }; } return invalidTextDiagnostic; } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 5fcd8525a9720..4004f0260ee8f 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -6,6 +6,7 @@ import { arrayToMap, assign, BuildOptions, + cast, changeExtension, CharacterCodes, combinePaths, @@ -2018,9 +2019,8 @@ export function parseBuildCommand(args: readonly string[]): ParsedBuildCommand { } /** @internal */ -export function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string { - const diagnostic = createCompilerDiagnostic.apply(undefined, arguments); - return diagnostic.messageText as string; +export function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string { + return cast(createCompilerDiagnostic(message, ...args).messageText, isString); } export type DiagnosticReporter = (diagnostic: Diagnostic) => void; diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 6f80f5f145d30..f5d60b0459141 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -2061,6 +2061,7 @@ export function compose(a: (t: T) => T, b: (t: T) => T, c: (t: T) => T, d: (t if (!!e) { const args: ((t: T) => T)[] = []; for (let i = 0; i < arguments.length; i++) { + // eslint-disable-next-line prefer-rest-params args[i] = arguments[i]; } diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 4538377dafd3d..3049f8b742d9d 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -115,9 +115,8 @@ import { } from "./_namespaces/ts"; /** @internal */ -export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; -export function trace(host: ModuleResolutionHost): void { - host.trace!(formatMessage.apply(undefined, arguments)); +export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void { + host.trace!(formatMessage(message, ...args)); } /** @internal */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 436fb32872c6e..638d76f79b53e 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -8121,8 +8121,8 @@ export function setObjectAllocator(alloc: ObjectAllocator) { } /** @internal */ -export function formatStringFromArgs(text: string, args: ArrayLike, baseIndex = 0): string { - return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.checkDefined(args[+index + baseIndex])); +export function formatStringFromArgs(text: string, args: DiagnosticArguments): string { + return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.checkDefined(args[+index])); } let localizedDiagnosticMessages: MapLike | undefined; @@ -8147,14 +8147,12 @@ export function getLocaleSpecificMessage(message: DiagnosticMessage) { } /** @internal */ -export function createDetachedDiagnostic(fileName: string, start: number, length: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithDetachedLocation; -/** @internal */ -export function createDetachedDiagnostic(fileName: string, start: number, length: number, message: DiagnosticMessage): DiagnosticWithDetachedLocation { +export function createDetachedDiagnostic(fileName: string, start: number, length: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithDetachedLocation { assertDiagnosticLocation(/*file*/ undefined, start, length); let text = getLocaleSpecificMessage(message); - if (arguments.length > 4) { - text = formatStringFromArgs(text, arguments, 4); + if (some(args)) { + text = formatStringFromArgs(text, args); } return { @@ -8218,15 +8216,13 @@ export function attachFileToDiagnostics(diagnostics: DiagnosticWithDetachedLocat } /** @internal */ -export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithLocation; -/** @internal */ -export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): DiagnosticWithLocation { +export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithLocation { assertDiagnosticLocation(file, start, length); let text = getLocaleSpecificMessage(message); - if (arguments.length > 4) { - text = formatStringFromArgs(text, arguments, 4); + if (some(args)) { + text = formatStringFromArgs(text, args); } return { @@ -8243,26 +8239,22 @@ export function createFileDiagnostic(file: SourceFile, start: number, length: nu } /** @internal */ -export function formatMessage(_dummy: any, message: DiagnosticMessage, ...args: DiagnosticArguments): string; -/** @internal */ -export function formatMessage(_dummy: any, message: DiagnosticMessage): string { +export function formatMessage(message: DiagnosticMessage, ...args: DiagnosticArguments): string { let text = getLocaleSpecificMessage(message); - if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); + if (some(args)) { + text = formatStringFromArgs(text, args); } return text; } /** @internal */ -export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: DiagnosticArguments): Diagnostic; -/** @internal */ -export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic { +export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: DiagnosticArguments): Diagnostic { let text = getLocaleSpecificMessage(message); - if (arguments.length > 1) { - text = formatStringFromArgs(text, arguments, 1); + if (some(args)) { + text = formatStringFromArgs(text, args); } return { @@ -8293,13 +8285,11 @@ export function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessag } /** @internal */ -export function chainDiagnosticMessages(details: DiagnosticMessageChain | DiagnosticMessageChain[] | undefined, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticMessageChain; -/** @internal */ -export function chainDiagnosticMessages(details: DiagnosticMessageChain | DiagnosticMessageChain[] | undefined, message: DiagnosticMessage): DiagnosticMessageChain { +export function chainDiagnosticMessages(details: DiagnosticMessageChain | DiagnosticMessageChain[] | undefined, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticMessageChain { let text = getLocaleSpecificMessage(message); - if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); + if (some(args)) { + text = formatStringFromArgs(text, args); } return { messageText: text, diff --git a/src/deprecatedCompat/deprecate.ts b/src/deprecatedCompat/deprecate.ts index 661da6980d437..cc6b2f31c31ed 100644 --- a/src/deprecatedCompat/deprecate.ts +++ b/src/deprecatedCompat/deprecate.ts @@ -24,7 +24,7 @@ function formatDeprecationMessage(name: string, error: boolean | undefined, erro deprecationMessage += `'${name}' `; deprecationMessage += since ? `has been deprecated since v${since}` : "is deprecated"; deprecationMessage += error ? " and can no longer be used." : errorAfter ? ` and will no longer be usable after v${errorAfter}.` : "."; - deprecationMessage += message ? ` ${formatStringFromArgs(message, [name], 0)}` : ""; + deprecationMessage += message ? ` ${formatStringFromArgs(message, [name])}` : ""; return deprecationMessage; } @@ -62,6 +62,7 @@ export function createDeprecation(name: string, options: DeprecationOptions = {} function wrapFunction any>(deprecation: () => void, func: F): F { return function (this: unknown) { deprecation(); + // eslint-disable-next-line prefer-rest-params return func.apply(this, arguments); } as F; } diff --git a/src/executeCommandLine/executeCommandLine.ts b/src/executeCommandLine/executeCommandLine.ts index b6f1d1ddedd7c..660effc571d48 100644 --- a/src/executeCommandLine/executeCommandLine.ts +++ b/src/executeCommandLine/executeCommandLine.ts @@ -486,7 +486,7 @@ function printEasyHelp(sys: System, simpleOptions: readonly CommandLineOption[]) output = [ ...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.COMMAND_LINE_FLAGS), cliCommands, /*subCategory*/ false, /*beforeOptionsDescription*/ undefined, /*afterOptionsDescription*/ undefined), - ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.COMMON_COMPILER_OPTIONS), configOpts, /*subCategory*/ false, /*beforeOptionsDescription*/ undefined, formatMessage(/*dummy*/ undefined, Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc")) + ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.COMMON_COMPILER_OPTIONS), configOpts, /*subCategory*/ false, /*beforeOptionsDescription*/ undefined, formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc")) ]; for (const line of output) { @@ -504,9 +504,9 @@ function printEasyHelp(sys: System, simpleOptions: readonly CommandLineOption[]) function printAllHelp(sys: System, compilerOptions: readonly CommandLineOption[], buildOptions: readonly CommandLineOption[], watchOptions: readonly CommandLineOption[]) { let output: string[] = [...getHeader(sys,`${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; - output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.ALL_COMPILER_OPTIONS), compilerOptions, /*subCategory*/ true, /*beforeOptionsDescription*/ undefined, formatMessage(/*dummy*/ undefined, Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc"))]; + output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.ALL_COMPILER_OPTIONS), compilerOptions, /*subCategory*/ true, /*beforeOptionsDescription*/ undefined, formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc"))]; output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.WATCH_OPTIONS), watchOptions, /*subCategory*/ false, getDiagnosticText(Diagnostics.Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_config_watch_mode_with_Colon))]; - output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.BUILD_OPTIONS), buildOptions, /*subCategory*/ false, formatMessage(/*dummy*/ undefined, Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds"))]; + output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.BUILD_OPTIONS), buildOptions, /*subCategory*/ false, formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds"))]; for (const line of output) { sys.write(line); } @@ -514,7 +514,7 @@ function printAllHelp(sys: System, compilerOptions: readonly CommandLineOption[] function printBuildHelp(sys: System, buildOptions: readonly CommandLineOption[]) { let output: string[] = [...getHeader(sys,`${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; - output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.BUILD_OPTIONS), buildOptions, /*subCategory*/ false, formatMessage(/*dummy*/ undefined, Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds"))]; + output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.BUILD_OPTIONS), buildOptions, /*subCategory*/ false, formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds"))]; for (const line of output) { sys.write(line); } diff --git a/src/harness/fourslashImpl.ts b/src/harness/fourslashImpl.ts index c34050f8f8bc1..634a80bdf0871 100644 --- a/src/harness/fourslashImpl.ts +++ b/src/harness/fourslashImpl.ts @@ -3279,7 +3279,7 @@ export class TestState { assert.equal(action.description, options.description); } else if (Array.isArray(options.description)) { - const description = ts.formatStringFromArgs(options.description[0], options.description, 1); + const description = ts.formatStringFromArgs(options.description[0], options.description.slice(1)); assert.equal(action.description, description); } else { @@ -4333,7 +4333,7 @@ export class TestState { public toggleLineComment(newFileContent: string): void { const changes: ts.TextChange[] = []; for (const range of this.getRanges()) { - changes.push.apply(changes, this.languageService.toggleLineComment(this.activeFile.fileName, range)); + changes.push(...this.languageService.toggleLineComment(this.activeFile.fileName, range)); } this.applyEdits(this.activeFile.fileName, changes); @@ -4344,7 +4344,7 @@ export class TestState { public toggleMultilineComment(newFileContent: string): void { const changes: ts.TextChange[] = []; for (const range of this.getRanges()) { - changes.push.apply(changes, this.languageService.toggleMultilineComment(this.activeFile.fileName, range)); + changes.push(...this.languageService.toggleMultilineComment(this.activeFile.fileName, range)); } this.applyEdits(this.activeFile.fileName, changes); @@ -4355,7 +4355,7 @@ export class TestState { public commentSelection(newFileContent: string): void { const changes: ts.TextChange[] = []; for (const range of this.getRanges()) { - changes.push.apply(changes, this.languageService.commentSelection(this.activeFile.fileName, range)); + changes.push(...this.languageService.commentSelection(this.activeFile.fileName, range)); } this.applyEdits(this.activeFile.fileName, changes); @@ -4366,7 +4366,7 @@ export class TestState { public uncommentSelection(newFileContent: string): void { const changes: ts.TextChange[] = []; for (const range of this.getRanges()) { - changes.push.apply(changes, this.languageService.uncommentSelection(this.activeFile.fileName, range)); + changes.push(...this.languageService.uncommentSelection(this.activeFile.fileName, range)); } this.applyEdits(this.activeFile.fileName, changes); diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 26682df5cdf1e..e059aad96f1f5 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -17,6 +17,7 @@ export function makeDefaultProxy(info: ts.server.PluginCreateInfo): ts.LanguageS for (const k of Object.keys(langSvc)) { // eslint-disable-next-line local/only-arrow-functions proxy[k] = function () { + // eslint-disable-next-line prefer-spread, prefer-rest-params return langSvc[k].apply(langSvc, arguments); }; } @@ -901,6 +902,7 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger { const langSvc: any = info.languageService; // eslint-disable-next-line local/only-arrow-functions proxy.getQuickInfoAtPosition = function () { + // eslint-disable-next-line prefer-spread, prefer-rest-params const parts = langSvc.getQuickInfoAtPosition.apply(langSvc, arguments); if (parts.displayParts.length > 0) { parts.displayParts[0].text = "Proxied"; diff --git a/src/services/services.ts b/src/services/services.ts index 51dcb93f7dd58..b0e56cc06453f 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -2614,7 +2614,7 @@ export function createLanguageService( // If the line is not an empty line; otherwise no-op. if (lineTextStart !== undefined) { if (isJsx) { - textChanges.push.apply(textChanges, toggleMultilineComment(fileName, { pos: lineStarts[i] + leftMostPosition, end: sourceFile.getLineEndOfPosition(lineStarts[i]) }, isCommenting, isJsx)); + textChanges.push(...toggleMultilineComment(fileName, { pos: lineStarts[i] + leftMostPosition, end: sourceFile.getLineEndOfPosition(lineStarts[i]) }, isCommenting, isJsx)); } else if (isCommenting) { textChanges.push({ @@ -2788,10 +2788,10 @@ export function createLanguageService( if (commentRange) { switch (commentRange.kind) { case SyntaxKind.SingleLineCommentTrivia: - textChanges.push.apply(textChanges, toggleLineComment(fileName, { end: commentRange.end, pos: commentRange.pos + 1 }, /*insertComment*/ false)); + textChanges.push(...toggleLineComment(fileName, { end: commentRange.end, pos: commentRange.pos + 1 }, /*insertComment*/ false)); break; case SyntaxKind.MultiLineCommentTrivia: - textChanges.push.apply(textChanges, toggleMultilineComment(fileName, { end: commentRange.end, pos: commentRange.pos + 1 }, /*insertComment*/ false)); + textChanges.push(...toggleMultilineComment(fileName, { end: commentRange.end, pos: commentRange.pos + 1 }, /*insertComment*/ false)); } i = commentRange.end + 1; From 634d3a1db5c69c1425119a74045790a4d1dc3046 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Sat, 12 Aug 2023 06:20:54 +0000 Subject: [PATCH 06/81] Update package-lock.json --- package-lock.json | 448 +++++++++++++++++++++++----------------------- 1 file changed, 224 insertions(+), 224 deletions(-) diff --git a/package-lock.json b/package-lock.json index de3c6fd1e757b..997774523cbb8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -76,9 +76,9 @@ "dev": true }, "node_modules/@esbuild/android-arm": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.0.tgz", - "integrity": "sha512-GAkjUyHgWTYuex3evPd5V7uV/XS4LMKr1PWHRPW1xNyy/Jx08x3uTrDFRefBYLKT/KpaWM8/YMQcwbp5a3yIDA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.1.tgz", + "integrity": "sha512-yjTucwcOua52z14RL30JMwmCdylsQ5WrErGkAb6VL0MWPbnwJyLejydaRcUqkPO6g0MowlzavdxrR7AcfCW+yA==", "cpu": [ "arm" ], @@ -92,9 +92,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.0.tgz", - "integrity": "sha512-AzsozJnB+RNaDncBCs3Ys5g3kqhPFUueItfEaCpp89JH2naFNX2mYDIvUgPYMqqjm8hiFoo+jklb3QHZyR3ubw==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.1.tgz", + "integrity": "sha512-CqhrKvDSt76I0so/5afqgKrMv41FjbfUKFrcZddMnrZKqJU70I1MWLVJrImJuYMaY4Yb9rn4UKfF7oZ0BOleVw==", "cpu": [ "arm64" ], @@ -108,9 +108,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.0.tgz", - "integrity": "sha512-SUG8/qiVhljBDpdkHQ9DvOWbp7hFFIP0OzxOTptbmVsgBgzY6JWowmMd6yJuOhapfxmj/DrvwKmjRLvVSIAKZg==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.1.tgz", + "integrity": "sha512-VA29h01MrPkymIL1bFtvL2L4WPogiMGW2N/M+vXZHHOv6LgA9vjzVskTt0v5LjeCjx1PFDcR0ASKy8Y7Gm+iIA==", "cpu": [ "x64" ], @@ -124,9 +124,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.0.tgz", - "integrity": "sha512-HkxZ8k3Jvcw0FORPNTavA8BMgQjLOB6AajT+iXmil7BwY3gU1hWvJJAyWyEogCmA4LdbGvKF8vEykdmJ4xNJJQ==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.1.tgz", + "integrity": "sha512-Be4Cf6WDH7QkLHEpfzQOlBOFdqmqYTSqw2yG3SVmzB3++wy3K7wiNGedezL+q6Jb4weqT9tchO5kkLDC08Jnzg==", "cpu": [ "arm64" ], @@ -140,9 +140,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.0.tgz", - "integrity": "sha512-9IRWJjqpWFHM9a5Qs3r3bK834NCFuDY5ZaLrmTjqE+10B6w65UMQzeZjh794JcxpHolsAHqwsN/33crUXNCM2Q==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.1.tgz", + "integrity": "sha512-SewtenJi6zCEfZRSUchb+LgJ/IQw8QvnKECPu/qHII1fLQKnVPUVR+VH2IuS03DD9WWnAi3yfOvBNwtrp3WXtg==", "cpu": [ "x64" ], @@ -156,9 +156,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.0.tgz", - "integrity": "sha512-s7i2WcXcK0V1PJHVBe7NsGddsL62a9Vhpz2U7zapPrwKoFuxPP9jybwX8SXnropR/AOj3ppt2ern4ItblU6UQQ==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.1.tgz", + "integrity": "sha512-TadKO0AaTDAPV2RyGZQ0AaiDTVYg7RsgNaA6OJjXXmoLbTs++NwHtzAmVFBq8Q/P9A11wgkv36HeyAYhWHbW1w==", "cpu": [ "arm64" ], @@ -172,9 +172,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.0.tgz", - "integrity": "sha512-NMdBSSdgwHCqCsucU5k1xflIIRU0qi1QZnM6+vdGy5fvxm1c8rKh50VzsWsIVTFUG3l91AtRxVwoz3Lcvy3I5w==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.1.tgz", + "integrity": "sha512-DrFMGLF0/aAcZgwhtZr1cby7aHlalpFjLCe5CiI8mm0Kqhhc8gyNZKreaZzvir8CQe0H17p9xx6M9ben5R3r0g==", "cpu": [ "x64" ], @@ -188,9 +188,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.0.tgz", - "integrity": "sha512-2F1+lH7ZBcCcgxiSs8EXQV0PPJJdTNiNcXxDb61vzxTRJJkXX1I/ye9mAhfHyScXzHaEibEXg1Jq9SW586zz7w==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.1.tgz", + "integrity": "sha512-lCWDVPpQO/Dt5MEqctKujgtUVmwQx7J2Q83EqX/9BejN7BIX4fGJ0QKMiIyy21PFh+/64ArN+Ovh1tzYkTt2wg==", "cpu": [ "arm" ], @@ -204,9 +204,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.0.tgz", - "integrity": "sha512-I4zvE2srSZxRPapFnNqj+NL3sDJ1wkvEZqt903OZUlBBgigrQMvzUowvP/TTTu2OGYe1oweg5MFilfyrElIFag==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.1.tgz", + "integrity": "sha512-6ku/R2EzsdjyBaqQn+xGOPbv+BBYBXQYzlA04/46YQLmXkdApi0GYyUwiCXYBxm578iyywzGmM0rep1/q8tuFQ==", "cpu": [ "arm64" ], @@ -220,9 +220,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.0.tgz", - "integrity": "sha512-dz2Q7+P92r1Evc8kEN+cQnB3qqPjmCrOZ+EdBTn8lEc1yN8WDgaDORQQiX+mxaijbH8npXBT9GxUqE52Gt6Y+g==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.1.tgz", + "integrity": "sha512-8AKFBk9v/zBDsADvK/0BWZUxkjEc0QDwO8rvbHJKqAZx6DF/VSeBxTRmqWeecrJmx+n3kemEwML9z0eD9IHweQ==", "cpu": [ "ia32" ], @@ -236,9 +236,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.0.tgz", - "integrity": "sha512-IcVJovJVflih4oFahhUw+N7YgNbuMSVFNr38awb0LNzfaiIfdqIh518nOfYaNQU3aVfiJnOIRVJDSAP4k35WxA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.1.tgz", + "integrity": "sha512-6mOS5CxTGD8qOymp2y4KoM4ir+/REgjdJQFYpwP+WqjrWBo+PUevDGeHHjzCdw/R19PkFqS1bRzv8cTCmB/5kA==", "cpu": [ "loong64" ], @@ -252,9 +252,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.0.tgz", - "integrity": "sha512-bZGRAGySMquWsKw0gIdsClwfvgbsSq/7oq5KVu1H1r9Il+WzOcfkV1hguntIuBjRVL8agI95i4AukjdAV2YpUw==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.1.tgz", + "integrity": "sha512-Bzmv6rRMzR4ErG2k/jwfj5jKNzVMVEI1tThuirFdAoE+duUv+jlDnlwxsN3s1eqMzADTOV2sSIcUUOfgv++Dgg==", "cpu": [ "mips64el" ], @@ -268,9 +268,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.0.tgz", - "integrity": "sha512-3LC6H5/gCDorxoRBUdpLV/m7UthYSdar0XcCu+ypycQxMS08MabZ06y1D1yZlDzL/BvOYliRNRWVG/YJJvQdbg==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.1.tgz", + "integrity": "sha512-mPOxA7bd3nmx8TkuO/9M/tE0fnvmuX0wlpwnTL6DPLgkb/Z/KkupexSIw4cLfznn/fPzD89y17VWBjlVNyrpCQ==", "cpu": [ "ppc64" ], @@ -284,9 +284,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.0.tgz", - "integrity": "sha512-jfvdKjWk+Cp2sgLtEEdSHXO7qckrw2B2eFBaoRdmfhThqZs29GMMg7q/LsQpybA7BxCLLEs4di5ucsWzZC5XPA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.1.tgz", + "integrity": "sha512-znYb2Mhe9xKIDeIYuTD6vCcUltvYzRT5Yq6sVcdhPrGu8DRdsNZS04B2tSeM+j7T03jL4yY+7/G/jxSJJ9LX2A==", "cpu": [ "riscv64" ], @@ -300,9 +300,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.0.tgz", - "integrity": "sha512-ofcucfNLkoXmcnJaw9ugdEOf40AWKGt09WBFCkpor+vFJVvmk/8OPjl/qRtks2Z7BuZbG3ztJuK1zS9z5Cgx9A==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.1.tgz", + "integrity": "sha512-BBIE32cyqAYhMOQ42/jnecoF5P/S5lMob2vXSUiFpD3xCFbXOFkjP1OjfFKnalSO9+B5emvPTQFfNQXuLeVGEw==", "cpu": [ "s390x" ], @@ -316,9 +316,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.0.tgz", - "integrity": "sha512-Fpf7zNDBti3xrQKQKLdXT0hTyOxgFdRJIMtNy8x1az9ATR9/GJ1brYbB/GLWoXhKiHsoWs+2DLkFVNNMTCLEwA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.1.tgz", + "integrity": "sha512-PoCvKdHTIbnHmVJ5OEdewGMSw40HDFRTrC/imwh8vrp695RbSUpOqBqNBT45neK0FQleGFbSE/A9X6HlXPDhqA==", "cpu": [ "x64" ], @@ -332,9 +332,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.0.tgz", - "integrity": "sha512-AMQAp/5oENgDOvVhvOlbhVe1pWii7oFAMRHlmTjSEMcpjTpIHtFXhv9uAFgUERHm3eYtNvS9Vf+gT55cwuI6Aw==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.1.tgz", + "integrity": "sha512-4OrGMPorHCq9h52VLtyyyAmPjC2ZlANx54VDYyCrqXUOi+k0qxnPKXKKprVES67w2mE7TZJx9qZmT+jHeiZbHQ==", "cpu": [ "x64" ], @@ -348,9 +348,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.0.tgz", - "integrity": "sha512-fDztEve1QUs3h/Dw2AUmBlWGkNQbhDoD05ppm5jKvzQv+HVuV13so7m5RYeiSMIC2XQy7PAjZh+afkxAnCRZxA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.1.tgz", + "integrity": "sha512-3a7ZYMjBC4P3FKdTmUZHJw7Mhzp71m+iSFFhX1PnLZ03qmyaB2K+vJZCk4PjRjAvm5lSupJQQtM/AFMyLgKlxQ==", "cpu": [ "x64" ], @@ -364,9 +364,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.0.tgz", - "integrity": "sha512-bKZzJ2/rvUjDzA5Ddyva2tMk89WzNJEibZEaq+wY6SiqPlwgFbqyQLimouxLHiHh1itb5P3SNCIF1bc2bw5H9w==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.1.tgz", + "integrity": "sha512-29yWBN5XfEjXT8yoeVb8cXfN1jAQLB+uskog1vBMhFR+YWOYvsrwPnh4hspETC/JnF95J+iETrvxgOUlICTWIw==", "cpu": [ "x64" ], @@ -380,9 +380,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.0.tgz", - "integrity": "sha512-NQJ+4jmnA79saI+sE+QzcEls19uZkoEmdxo7r//PDOjIpX8pmoWtTnWg6XcbnO7o4fieyAwb5U2LvgWynF4diA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.1.tgz", + "integrity": "sha512-9Hb/WUXgyXlL55w3iNVyLkN9gq9x+agv3kk80foWbfpOwe7Qw4Vx6JGB+XQdsIfvvP1kShVQPIvBgVj0TxLlVw==", "cpu": [ "arm64" ], @@ -396,9 +396,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.0.tgz", - "integrity": "sha512-uyxiZAnsfu9diHm9/rIH2soecF/HWLXYUhJKW4q1+/LLmNQ+55lRjvSUDhUmsgJtSUscRJB/3S4RNiTb9o9mCg==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.1.tgz", + "integrity": "sha512-VGdtEcXX/f01NgoM8emDnpdOyrZCQ7VTwLv89MOl3mvJ5fbCOBMNCa8t7RZS4lf12RS87qOuJFX7Bh9aLTbSxg==", "cpu": [ "ia32" ], @@ -412,9 +412,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.0.tgz", - "integrity": "sha512-jl+NXUjK2StMgqnZnqgNjZuerFG8zQqWXMBZdMMv4W/aO1ZKQaYWZBxTrtWKphkCBVEMh0wMVfGgOd2BjOZqUQ==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.1.tgz", + "integrity": "sha512-H6u8OHmJkKJubLbukVOyi9yA5lzK8VE4TFEkZj2vgusTUPvFeMQ8YnWviVc9F6PuKS6ZIpOvi2/sfiW8tQZQ2g==", "cpu": [ "x64" ], @@ -478,9 +478,9 @@ } }, "node_modules/@eslint/eslintrc": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.1.tgz", - "integrity": "sha512-9t7ZA7NGGK8ckelF0PQCfcxIUzs1Md5rrO6U/c+FIQNanea5UZC0wqKXH4vHBccmu4ZJgZ2idtPeW7+Q2npOEA==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.2.tgz", + "integrity": "sha512-+wvgpDsrB1YqAMdEUCcnTlpfVBH7Vqn6A/NT3D8WVXFIaKMlErPIZT3oCIAVCOtarRpMtelZLqJeU3t7WY6X6g==", "dev": true, "dependencies": { "ajv": "^6.12.4", @@ -501,9 +501,9 @@ } }, "node_modules/@eslint/js": { - "version": "8.46.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.46.0.tgz", - "integrity": "sha512-a8TLtmPi8xzPkCbp/OGFUo5yhRkHM2Ko9kOWP4znJr0WAhWyThaw3PnwX4vOTWOAMsV2uRt32PPDcEz63esSaA==", + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.47.0.tgz", + "integrity": "sha512-P6omY1zv5MItm93kLM8s2vr1HICJH8v0dvddDhysbIuZ+vcjOHg5Zbkf1mTkcmi2JA9oBG2anOkRnW8WJTS8Og==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -870,9 +870,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.4.9", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.9.tgz", - "integrity": "sha512-8e2HYcg7ohnTUbHk8focoklEQYvemQmu9M/f43DZVx43kHn0tE3BY/6gSDxS7k0SprtS0NHvj+L80cGLnoOUcQ==", + "version": "20.4.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.10.tgz", + "integrity": "sha512-vwzFiiy8Rn6E0MtA13/Cxxgpan/N6UeNYR9oUu6kuJWxu6zCk98trcDp8CBhbtaeuq9SykCmXkFr2lWLoPcvLg==", "dev": true }, "node_modules/@types/semver": { @@ -1708,9 +1708,9 @@ "dev": true }, "node_modules/esbuild": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.0.tgz", - "integrity": "sha512-i7i8TP4vuG55bKeLyqqk5sTPu1ZjPH3wkcLvAj/0X/222iWFo3AJUYRKjbOoY6BWFMH3teizxHEdV9Su5ESl0w==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.1.tgz", + "integrity": "sha512-IknHHwV4B/H4imOAu+416fuCvPfRjdncoyGi7eunhSvHuHkdNs50sLWan2LEG2Mym07TuW6gJUIyRS9G1miHEg==", "dev": true, "hasInstallScript": true, "bin": { @@ -1720,28 +1720,28 @@ "node": ">=12" }, "optionalDependencies": { - "@esbuild/android-arm": "0.19.0", - "@esbuild/android-arm64": "0.19.0", - "@esbuild/android-x64": "0.19.0", - "@esbuild/darwin-arm64": "0.19.0", - "@esbuild/darwin-x64": "0.19.0", - "@esbuild/freebsd-arm64": "0.19.0", - "@esbuild/freebsd-x64": "0.19.0", - "@esbuild/linux-arm": "0.19.0", - "@esbuild/linux-arm64": "0.19.0", - "@esbuild/linux-ia32": "0.19.0", - "@esbuild/linux-loong64": "0.19.0", - "@esbuild/linux-mips64el": "0.19.0", - "@esbuild/linux-ppc64": "0.19.0", - "@esbuild/linux-riscv64": "0.19.0", - "@esbuild/linux-s390x": "0.19.0", - "@esbuild/linux-x64": "0.19.0", - "@esbuild/netbsd-x64": "0.19.0", - "@esbuild/openbsd-x64": "0.19.0", - "@esbuild/sunos-x64": "0.19.0", - "@esbuild/win32-arm64": "0.19.0", - "@esbuild/win32-ia32": "0.19.0", - "@esbuild/win32-x64": "0.19.0" + "@esbuild/android-arm": "0.19.1", + "@esbuild/android-arm64": "0.19.1", + "@esbuild/android-x64": "0.19.1", + "@esbuild/darwin-arm64": "0.19.1", + "@esbuild/darwin-x64": "0.19.1", + "@esbuild/freebsd-arm64": "0.19.1", + "@esbuild/freebsd-x64": "0.19.1", + "@esbuild/linux-arm": "0.19.1", + "@esbuild/linux-arm64": "0.19.1", + "@esbuild/linux-ia32": "0.19.1", + "@esbuild/linux-loong64": "0.19.1", + "@esbuild/linux-mips64el": "0.19.1", + "@esbuild/linux-ppc64": "0.19.1", + "@esbuild/linux-riscv64": "0.19.1", + "@esbuild/linux-s390x": "0.19.1", + "@esbuild/linux-x64": "0.19.1", + "@esbuild/netbsd-x64": "0.19.1", + "@esbuild/openbsd-x64": "0.19.1", + "@esbuild/sunos-x64": "0.19.1", + "@esbuild/win32-arm64": "0.19.1", + "@esbuild/win32-ia32": "0.19.1", + "@esbuild/win32-x64": "0.19.1" } }, "node_modules/escalade": { @@ -1766,15 +1766,15 @@ } }, "node_modules/eslint": { - "version": "8.46.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.46.0.tgz", - "integrity": "sha512-cIO74PvbW0qU8e0mIvk5IV3ToWdCq5FYG6gWPHHkx6gNdjlbAYvtfHmlCMXxjcoVaIdwy/IAt3+mDkZkfvb2Dg==", + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.47.0.tgz", + "integrity": "sha512-spUQWrdPt+pRVP1TTJLmfRNJJHHZryFmptzcafwSvHsceV81djHOdnEeDmkdotZyLNjDhrOasNK8nikkoG1O8Q==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.1", - "@eslint/js": "^8.46.0", + "@eslint/eslintrc": "^2.1.2", + "@eslint/js": "^8.47.0", "@humanwhocodes/config-array": "^0.11.10", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", @@ -1785,7 +1785,7 @@ "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.2", + "eslint-visitor-keys": "^3.4.3", "espree": "^9.6.1", "esquery": "^1.4.2", "esutils": "^2.0.2", @@ -1879,9 +1879,9 @@ } }, "node_modules/eslint-visitor-keys": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.2.tgz", - "integrity": "sha512-8drBzUEyZ2llkpCA67iYrgEssKDUu68V8ChqqOfFupIaG/LCVPUT+CoGJpT77zJprs4T/W7p07LP7zAIMuweVw==", + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -2278,9 +2278,9 @@ } }, "node_modules/globals": { - "version": "13.20.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.20.0.tgz", - "integrity": "sha512-Qg5QtVkCy/kv3FUSlu4ukeZDVf9ee0iXLAUYX13gbR17bnejFTzr4iS9bY7kwCf1NztRNm1t91fjOiyx4CSwPQ==", + "version": "13.21.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.21.0.tgz", + "integrity": "sha512-ybyme3s4yy/t/3s35bewwXKOf7cvzfreG2lH0lZl0JB7I4GxRP2ghxOK/Nb9EkRXdbBXZLfq/p/0W2JUONB/Gg==", "dev": true, "dependencies": { "type-fest": "^0.20.2" @@ -3913,156 +3913,156 @@ "dev": true }, "@esbuild/android-arm": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.0.tgz", - "integrity": "sha512-GAkjUyHgWTYuex3evPd5V7uV/XS4LMKr1PWHRPW1xNyy/Jx08x3uTrDFRefBYLKT/KpaWM8/YMQcwbp5a3yIDA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.1.tgz", + "integrity": "sha512-yjTucwcOua52z14RL30JMwmCdylsQ5WrErGkAb6VL0MWPbnwJyLejydaRcUqkPO6g0MowlzavdxrR7AcfCW+yA==", "dev": true, "optional": true }, "@esbuild/android-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.0.tgz", - "integrity": "sha512-AzsozJnB+RNaDncBCs3Ys5g3kqhPFUueItfEaCpp89JH2naFNX2mYDIvUgPYMqqjm8hiFoo+jklb3QHZyR3ubw==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.1.tgz", + "integrity": "sha512-CqhrKvDSt76I0so/5afqgKrMv41FjbfUKFrcZddMnrZKqJU70I1MWLVJrImJuYMaY4Yb9rn4UKfF7oZ0BOleVw==", "dev": true, "optional": true }, "@esbuild/android-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.0.tgz", - "integrity": "sha512-SUG8/qiVhljBDpdkHQ9DvOWbp7hFFIP0OzxOTptbmVsgBgzY6JWowmMd6yJuOhapfxmj/DrvwKmjRLvVSIAKZg==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.1.tgz", + "integrity": "sha512-VA29h01MrPkymIL1bFtvL2L4WPogiMGW2N/M+vXZHHOv6LgA9vjzVskTt0v5LjeCjx1PFDcR0ASKy8Y7Gm+iIA==", "dev": true, "optional": true }, "@esbuild/darwin-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.0.tgz", - "integrity": "sha512-HkxZ8k3Jvcw0FORPNTavA8BMgQjLOB6AajT+iXmil7BwY3gU1hWvJJAyWyEogCmA4LdbGvKF8vEykdmJ4xNJJQ==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.1.tgz", + "integrity": "sha512-Be4Cf6WDH7QkLHEpfzQOlBOFdqmqYTSqw2yG3SVmzB3++wy3K7wiNGedezL+q6Jb4weqT9tchO5kkLDC08Jnzg==", "dev": true, "optional": true }, "@esbuild/darwin-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.0.tgz", - "integrity": "sha512-9IRWJjqpWFHM9a5Qs3r3bK834NCFuDY5ZaLrmTjqE+10B6w65UMQzeZjh794JcxpHolsAHqwsN/33crUXNCM2Q==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.1.tgz", + "integrity": "sha512-SewtenJi6zCEfZRSUchb+LgJ/IQw8QvnKECPu/qHII1fLQKnVPUVR+VH2IuS03DD9WWnAi3yfOvBNwtrp3WXtg==", "dev": true, "optional": true }, "@esbuild/freebsd-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.0.tgz", - "integrity": "sha512-s7i2WcXcK0V1PJHVBe7NsGddsL62a9Vhpz2U7zapPrwKoFuxPP9jybwX8SXnropR/AOj3ppt2ern4ItblU6UQQ==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.1.tgz", + "integrity": "sha512-TadKO0AaTDAPV2RyGZQ0AaiDTVYg7RsgNaA6OJjXXmoLbTs++NwHtzAmVFBq8Q/P9A11wgkv36HeyAYhWHbW1w==", "dev": true, "optional": true }, "@esbuild/freebsd-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.0.tgz", - "integrity": "sha512-NMdBSSdgwHCqCsucU5k1xflIIRU0qi1QZnM6+vdGy5fvxm1c8rKh50VzsWsIVTFUG3l91AtRxVwoz3Lcvy3I5w==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.1.tgz", + "integrity": "sha512-DrFMGLF0/aAcZgwhtZr1cby7aHlalpFjLCe5CiI8mm0Kqhhc8gyNZKreaZzvir8CQe0H17p9xx6M9ben5R3r0g==", "dev": true, "optional": true }, "@esbuild/linux-arm": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.0.tgz", - "integrity": "sha512-2F1+lH7ZBcCcgxiSs8EXQV0PPJJdTNiNcXxDb61vzxTRJJkXX1I/ye9mAhfHyScXzHaEibEXg1Jq9SW586zz7w==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.1.tgz", + "integrity": "sha512-lCWDVPpQO/Dt5MEqctKujgtUVmwQx7J2Q83EqX/9BejN7BIX4fGJ0QKMiIyy21PFh+/64ArN+Ovh1tzYkTt2wg==", "dev": true, "optional": true }, "@esbuild/linux-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.0.tgz", - "integrity": "sha512-I4zvE2srSZxRPapFnNqj+NL3sDJ1wkvEZqt903OZUlBBgigrQMvzUowvP/TTTu2OGYe1oweg5MFilfyrElIFag==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.1.tgz", + "integrity": "sha512-6ku/R2EzsdjyBaqQn+xGOPbv+BBYBXQYzlA04/46YQLmXkdApi0GYyUwiCXYBxm578iyywzGmM0rep1/q8tuFQ==", "dev": true, "optional": true }, "@esbuild/linux-ia32": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.0.tgz", - "integrity": "sha512-dz2Q7+P92r1Evc8kEN+cQnB3qqPjmCrOZ+EdBTn8lEc1yN8WDgaDORQQiX+mxaijbH8npXBT9GxUqE52Gt6Y+g==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.1.tgz", + "integrity": "sha512-8AKFBk9v/zBDsADvK/0BWZUxkjEc0QDwO8rvbHJKqAZx6DF/VSeBxTRmqWeecrJmx+n3kemEwML9z0eD9IHweQ==", "dev": true, "optional": true }, "@esbuild/linux-loong64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.0.tgz", - "integrity": "sha512-IcVJovJVflih4oFahhUw+N7YgNbuMSVFNr38awb0LNzfaiIfdqIh518nOfYaNQU3aVfiJnOIRVJDSAP4k35WxA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.1.tgz", + "integrity": "sha512-6mOS5CxTGD8qOymp2y4KoM4ir+/REgjdJQFYpwP+WqjrWBo+PUevDGeHHjzCdw/R19PkFqS1bRzv8cTCmB/5kA==", "dev": true, "optional": true }, "@esbuild/linux-mips64el": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.0.tgz", - "integrity": "sha512-bZGRAGySMquWsKw0gIdsClwfvgbsSq/7oq5KVu1H1r9Il+WzOcfkV1hguntIuBjRVL8agI95i4AukjdAV2YpUw==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.1.tgz", + "integrity": "sha512-Bzmv6rRMzR4ErG2k/jwfj5jKNzVMVEI1tThuirFdAoE+duUv+jlDnlwxsN3s1eqMzADTOV2sSIcUUOfgv++Dgg==", "dev": true, "optional": true }, "@esbuild/linux-ppc64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.0.tgz", - "integrity": "sha512-3LC6H5/gCDorxoRBUdpLV/m7UthYSdar0XcCu+ypycQxMS08MabZ06y1D1yZlDzL/BvOYliRNRWVG/YJJvQdbg==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.1.tgz", + "integrity": "sha512-mPOxA7bd3nmx8TkuO/9M/tE0fnvmuX0wlpwnTL6DPLgkb/Z/KkupexSIw4cLfznn/fPzD89y17VWBjlVNyrpCQ==", "dev": true, "optional": true }, "@esbuild/linux-riscv64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.0.tgz", - "integrity": "sha512-jfvdKjWk+Cp2sgLtEEdSHXO7qckrw2B2eFBaoRdmfhThqZs29GMMg7q/LsQpybA7BxCLLEs4di5ucsWzZC5XPA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.1.tgz", + "integrity": "sha512-znYb2Mhe9xKIDeIYuTD6vCcUltvYzRT5Yq6sVcdhPrGu8DRdsNZS04B2tSeM+j7T03jL4yY+7/G/jxSJJ9LX2A==", "dev": true, "optional": true }, "@esbuild/linux-s390x": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.0.tgz", - "integrity": "sha512-ofcucfNLkoXmcnJaw9ugdEOf40AWKGt09WBFCkpor+vFJVvmk/8OPjl/qRtks2Z7BuZbG3ztJuK1zS9z5Cgx9A==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.1.tgz", + "integrity": "sha512-BBIE32cyqAYhMOQ42/jnecoF5P/S5lMob2vXSUiFpD3xCFbXOFkjP1OjfFKnalSO9+B5emvPTQFfNQXuLeVGEw==", "dev": true, "optional": true }, "@esbuild/linux-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.0.tgz", - "integrity": "sha512-Fpf7zNDBti3xrQKQKLdXT0hTyOxgFdRJIMtNy8x1az9ATR9/GJ1brYbB/GLWoXhKiHsoWs+2DLkFVNNMTCLEwA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.1.tgz", + "integrity": "sha512-PoCvKdHTIbnHmVJ5OEdewGMSw40HDFRTrC/imwh8vrp695RbSUpOqBqNBT45neK0FQleGFbSE/A9X6HlXPDhqA==", "dev": true, "optional": true }, "@esbuild/netbsd-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.0.tgz", - "integrity": "sha512-AMQAp/5oENgDOvVhvOlbhVe1pWii7oFAMRHlmTjSEMcpjTpIHtFXhv9uAFgUERHm3eYtNvS9Vf+gT55cwuI6Aw==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.1.tgz", + "integrity": "sha512-4OrGMPorHCq9h52VLtyyyAmPjC2ZlANx54VDYyCrqXUOi+k0qxnPKXKKprVES67w2mE7TZJx9qZmT+jHeiZbHQ==", "dev": true, "optional": true }, "@esbuild/openbsd-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.0.tgz", - "integrity": "sha512-fDztEve1QUs3h/Dw2AUmBlWGkNQbhDoD05ppm5jKvzQv+HVuV13so7m5RYeiSMIC2XQy7PAjZh+afkxAnCRZxA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.1.tgz", + "integrity": "sha512-3a7ZYMjBC4P3FKdTmUZHJw7Mhzp71m+iSFFhX1PnLZ03qmyaB2K+vJZCk4PjRjAvm5lSupJQQtM/AFMyLgKlxQ==", "dev": true, "optional": true }, "@esbuild/sunos-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.0.tgz", - "integrity": "sha512-bKZzJ2/rvUjDzA5Ddyva2tMk89WzNJEibZEaq+wY6SiqPlwgFbqyQLimouxLHiHh1itb5P3SNCIF1bc2bw5H9w==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.1.tgz", + "integrity": "sha512-29yWBN5XfEjXT8yoeVb8cXfN1jAQLB+uskog1vBMhFR+YWOYvsrwPnh4hspETC/JnF95J+iETrvxgOUlICTWIw==", "dev": true, "optional": true }, "@esbuild/win32-arm64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.0.tgz", - "integrity": "sha512-NQJ+4jmnA79saI+sE+QzcEls19uZkoEmdxo7r//PDOjIpX8pmoWtTnWg6XcbnO7o4fieyAwb5U2LvgWynF4diA==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.1.tgz", + "integrity": "sha512-9Hb/WUXgyXlL55w3iNVyLkN9gq9x+agv3kk80foWbfpOwe7Qw4Vx6JGB+XQdsIfvvP1kShVQPIvBgVj0TxLlVw==", "dev": true, "optional": true }, "@esbuild/win32-ia32": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.0.tgz", - "integrity": "sha512-uyxiZAnsfu9diHm9/rIH2soecF/HWLXYUhJKW4q1+/LLmNQ+55lRjvSUDhUmsgJtSUscRJB/3S4RNiTb9o9mCg==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.1.tgz", + "integrity": "sha512-VGdtEcXX/f01NgoM8emDnpdOyrZCQ7VTwLv89MOl3mvJ5fbCOBMNCa8t7RZS4lf12RS87qOuJFX7Bh9aLTbSxg==", "dev": true, "optional": true }, "@esbuild/win32-x64": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.0.tgz", - "integrity": "sha512-jl+NXUjK2StMgqnZnqgNjZuerFG8zQqWXMBZdMMv4W/aO1ZKQaYWZBxTrtWKphkCBVEMh0wMVfGgOd2BjOZqUQ==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.1.tgz", + "integrity": "sha512-H6u8OHmJkKJubLbukVOyi9yA5lzK8VE4TFEkZj2vgusTUPvFeMQ8YnWviVc9F6PuKS6ZIpOvi2/sfiW8tQZQ2g==", "dev": true, "optional": true }, @@ -4108,9 +4108,9 @@ "dev": true }, "@eslint/eslintrc": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.1.tgz", - "integrity": "sha512-9t7ZA7NGGK8ckelF0PQCfcxIUzs1Md5rrO6U/c+FIQNanea5UZC0wqKXH4vHBccmu4ZJgZ2idtPeW7+Q2npOEA==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.2.tgz", + "integrity": "sha512-+wvgpDsrB1YqAMdEUCcnTlpfVBH7Vqn6A/NT3D8WVXFIaKMlErPIZT3oCIAVCOtarRpMtelZLqJeU3t7WY6X6g==", "dev": true, "requires": { "ajv": "^6.12.4", @@ -4125,9 +4125,9 @@ } }, "@eslint/js": { - "version": "8.46.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.46.0.tgz", - "integrity": "sha512-a8TLtmPi8xzPkCbp/OGFUo5yhRkHM2Ko9kOWP4znJr0WAhWyThaw3PnwX4vOTWOAMsV2uRt32PPDcEz63esSaA==", + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.47.0.tgz", + "integrity": "sha512-P6omY1zv5MItm93kLM8s2vr1HICJH8v0dvddDhysbIuZ+vcjOHg5Zbkf1mTkcmi2JA9oBG2anOkRnW8WJTS8Og==", "dev": true }, "@humanwhocodes/config-array": { @@ -4424,9 +4424,9 @@ "dev": true }, "@types/node": { - "version": "20.4.9", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.9.tgz", - "integrity": "sha512-8e2HYcg7ohnTUbHk8focoklEQYvemQmu9M/f43DZVx43kHn0tE3BY/6gSDxS7k0SprtS0NHvj+L80cGLnoOUcQ==", + "version": "20.4.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.10.tgz", + "integrity": "sha512-vwzFiiy8Rn6E0MtA13/Cxxgpan/N6UeNYR9oUu6kuJWxu6zCk98trcDp8CBhbtaeuq9SykCmXkFr2lWLoPcvLg==", "dev": true }, "@types/semver": { @@ -5023,33 +5023,33 @@ "dev": true }, "esbuild": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.0.tgz", - "integrity": "sha512-i7i8TP4vuG55bKeLyqqk5sTPu1ZjPH3wkcLvAj/0X/222iWFo3AJUYRKjbOoY6BWFMH3teizxHEdV9Su5ESl0w==", + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.1.tgz", + "integrity": "sha512-IknHHwV4B/H4imOAu+416fuCvPfRjdncoyGi7eunhSvHuHkdNs50sLWan2LEG2Mym07TuW6gJUIyRS9G1miHEg==", "dev": true, "requires": { - "@esbuild/android-arm": "0.19.0", - "@esbuild/android-arm64": "0.19.0", - "@esbuild/android-x64": "0.19.0", - "@esbuild/darwin-arm64": "0.19.0", - "@esbuild/darwin-x64": "0.19.0", - "@esbuild/freebsd-arm64": "0.19.0", - "@esbuild/freebsd-x64": "0.19.0", - "@esbuild/linux-arm": "0.19.0", - "@esbuild/linux-arm64": "0.19.0", - "@esbuild/linux-ia32": "0.19.0", - "@esbuild/linux-loong64": "0.19.0", - "@esbuild/linux-mips64el": "0.19.0", - "@esbuild/linux-ppc64": "0.19.0", - "@esbuild/linux-riscv64": "0.19.0", - "@esbuild/linux-s390x": "0.19.0", - "@esbuild/linux-x64": "0.19.0", - "@esbuild/netbsd-x64": "0.19.0", - "@esbuild/openbsd-x64": "0.19.0", - "@esbuild/sunos-x64": "0.19.0", - "@esbuild/win32-arm64": "0.19.0", - "@esbuild/win32-ia32": "0.19.0", - "@esbuild/win32-x64": "0.19.0" + "@esbuild/android-arm": "0.19.1", + "@esbuild/android-arm64": "0.19.1", + "@esbuild/android-x64": "0.19.1", + "@esbuild/darwin-arm64": "0.19.1", + "@esbuild/darwin-x64": "0.19.1", + "@esbuild/freebsd-arm64": "0.19.1", + "@esbuild/freebsd-x64": "0.19.1", + "@esbuild/linux-arm": "0.19.1", + "@esbuild/linux-arm64": "0.19.1", + "@esbuild/linux-ia32": "0.19.1", + "@esbuild/linux-loong64": "0.19.1", + "@esbuild/linux-mips64el": "0.19.1", + "@esbuild/linux-ppc64": "0.19.1", + "@esbuild/linux-riscv64": "0.19.1", + "@esbuild/linux-s390x": "0.19.1", + "@esbuild/linux-x64": "0.19.1", + "@esbuild/netbsd-x64": "0.19.1", + "@esbuild/openbsd-x64": "0.19.1", + "@esbuild/sunos-x64": "0.19.1", + "@esbuild/win32-arm64": "0.19.1", + "@esbuild/win32-ia32": "0.19.1", + "@esbuild/win32-x64": "0.19.1" } }, "escalade": { @@ -5065,15 +5065,15 @@ "dev": true }, "eslint": { - "version": "8.46.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.46.0.tgz", - "integrity": "sha512-cIO74PvbW0qU8e0mIvk5IV3ToWdCq5FYG6gWPHHkx6gNdjlbAYvtfHmlCMXxjcoVaIdwy/IAt3+mDkZkfvb2Dg==", + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.47.0.tgz", + "integrity": "sha512-spUQWrdPt+pRVP1TTJLmfRNJJHHZryFmptzcafwSvHsceV81djHOdnEeDmkdotZyLNjDhrOasNK8nikkoG1O8Q==", "dev": true, "requires": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.1", - "@eslint/js": "^8.46.0", + "@eslint/eslintrc": "^2.1.2", + "@eslint/js": "^8.47.0", "@humanwhocodes/config-array": "^0.11.10", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", @@ -5084,7 +5084,7 @@ "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.2", + "eslint-visitor-keys": "^3.4.3", "espree": "^9.6.1", "esquery": "^1.4.2", "esutils": "^2.0.2", @@ -5161,9 +5161,9 @@ } }, "eslint-visitor-keys": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.2.tgz", - "integrity": "sha512-8drBzUEyZ2llkpCA67iYrgEssKDUu68V8ChqqOfFupIaG/LCVPUT+CoGJpT77zJprs4T/W7p07LP7zAIMuweVw==", + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true }, "espree": { @@ -5439,9 +5439,9 @@ } }, "globals": { - "version": "13.20.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.20.0.tgz", - "integrity": "sha512-Qg5QtVkCy/kv3FUSlu4ukeZDVf9ee0iXLAUYX13gbR17bnejFTzr4iS9bY7kwCf1NztRNm1t91fjOiyx4CSwPQ==", + "version": "13.21.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.21.0.tgz", + "integrity": "sha512-ybyme3s4yy/t/3s35bewwXKOf7cvzfreG2lH0lZl0JB7I4GxRP2ghxOK/Nb9EkRXdbBXZLfq/p/0W2JUONB/Gg==", "dev": true, "requires": { "type-fest": "^0.20.2" From dcd970efd1d491cbcc4a55c45e31ead109153cdd Mon Sep 17 00:00:00 2001 From: Hardik Date: Sun, 13 Aug 2023 12:34:14 +0530 Subject: [PATCH 07/81] Adding Unit Test --- tests/cases/fourslash/autoImportNonModules.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 tests/cases/fourslash/autoImportNonModules.ts diff --git a/tests/cases/fourslash/autoImportNonModules.ts b/tests/cases/fourslash/autoImportNonModules.ts new file mode 100644 index 0000000000000..3cdd8ac4f47fe --- /dev/null +++ b/tests/cases/fourslash/autoImportNonModules.ts @@ -0,0 +1,10 @@ +/// +// @module: none +// @Filename:test.ts +//// export function f(){ return false } + +// @Filename:test1.ts +//// /**/ + +goTo.marker(""); +verify.completions(); \ No newline at end of file From fd390e78fe329dd2761d59ab1d5f3c5be2091018 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Mon, 14 Aug 2023 06:18:10 +0000 Subject: [PATCH 08/81] Update package-lock.json --- package-lock.json | 376 +++++++++++++++++++++++----------------------- 1 file changed, 188 insertions(+), 188 deletions(-) diff --git a/package-lock.json b/package-lock.json index 997774523cbb8..e2c485674307d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -76,9 +76,9 @@ "dev": true }, "node_modules/@esbuild/android-arm": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.1.tgz", - "integrity": "sha512-yjTucwcOua52z14RL30JMwmCdylsQ5WrErGkAb6VL0MWPbnwJyLejydaRcUqkPO6g0MowlzavdxrR7AcfCW+yA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.2.tgz", + "integrity": "sha512-tM8yLeYVe7pRyAu9VMi/Q7aunpLwD139EY1S99xbQkT4/q2qa6eA4ige/WJQYdJ8GBL1K33pPFhPfPdJ/WzT8Q==", "cpu": [ "arm" ], @@ -92,9 +92,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.1.tgz", - "integrity": "sha512-CqhrKvDSt76I0so/5afqgKrMv41FjbfUKFrcZddMnrZKqJU70I1MWLVJrImJuYMaY4Yb9rn4UKfF7oZ0BOleVw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.2.tgz", + "integrity": "sha512-lsB65vAbe90I/Qe10OjkmrdxSX4UJDjosDgb8sZUKcg3oefEuW2OT2Vozz8ef7wrJbMcmhvCC+hciF8jY/uAkw==", "cpu": [ "arm64" ], @@ -108,9 +108,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.1.tgz", - "integrity": "sha512-VA29h01MrPkymIL1bFtvL2L4WPogiMGW2N/M+vXZHHOv6LgA9vjzVskTt0v5LjeCjx1PFDcR0ASKy8Y7Gm+iIA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.2.tgz", + "integrity": "sha512-qK/TpmHt2M/Hg82WXHRc/W/2SGo/l1thtDHZWqFq7oi24AjZ4O/CpPSu6ZuYKFkEgmZlFoa7CooAyYmuvnaG8w==", "cpu": [ "x64" ], @@ -124,9 +124,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.1.tgz", - "integrity": "sha512-Be4Cf6WDH7QkLHEpfzQOlBOFdqmqYTSqw2yG3SVmzB3++wy3K7wiNGedezL+q6Jb4weqT9tchO5kkLDC08Jnzg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.2.tgz", + "integrity": "sha512-Ora8JokrvrzEPEpZO18ZYXkH4asCdc1DLdcVy8TGf5eWtPO1Ie4WroEJzwI52ZGtpODy3+m0a2yEX9l+KUn0tA==", "cpu": [ "arm64" ], @@ -140,9 +140,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.1.tgz", - "integrity": "sha512-SewtenJi6zCEfZRSUchb+LgJ/IQw8QvnKECPu/qHII1fLQKnVPUVR+VH2IuS03DD9WWnAi3yfOvBNwtrp3WXtg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.2.tgz", + "integrity": "sha512-tP+B5UuIbbFMj2hQaUr6EALlHOIOmlLM2FK7jeFBobPy2ERdohI4Ka6ZFjZ1ZYsrHE/hZimGuU90jusRE0pwDw==", "cpu": [ "x64" ], @@ -156,9 +156,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.1.tgz", - "integrity": "sha512-TadKO0AaTDAPV2RyGZQ0AaiDTVYg7RsgNaA6OJjXXmoLbTs++NwHtzAmVFBq8Q/P9A11wgkv36HeyAYhWHbW1w==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.2.tgz", + "integrity": "sha512-YbPY2kc0acfzL1VPVK6EnAlig4f+l8xmq36OZkU0jzBVHcOTyQDhnKQaLzZudNJQyymd9OqQezeaBgkTGdTGeQ==", "cpu": [ "arm64" ], @@ -172,9 +172,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.1.tgz", - "integrity": "sha512-DrFMGLF0/aAcZgwhtZr1cby7aHlalpFjLCe5CiI8mm0Kqhhc8gyNZKreaZzvir8CQe0H17p9xx6M9ben5R3r0g==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.2.tgz", + "integrity": "sha512-nSO5uZT2clM6hosjWHAsS15hLrwCvIWx+b2e3lZ3MwbYSaXwvfO528OF+dLjas1g3bZonciivI8qKR/Hm7IWGw==", "cpu": [ "x64" ], @@ -188,9 +188,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.1.tgz", - "integrity": "sha512-lCWDVPpQO/Dt5MEqctKujgtUVmwQx7J2Q83EqX/9BejN7BIX4fGJ0QKMiIyy21PFh+/64ArN+Ovh1tzYkTt2wg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.2.tgz", + "integrity": "sha512-Odalh8hICg7SOD7XCj0YLpYCEc+6mkoq63UnExDCiRA2wXEmGlK5JVrW50vZR9Qz4qkvqnHcpH+OFEggO3PgTg==", "cpu": [ "arm" ], @@ -204,9 +204,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.1.tgz", - "integrity": "sha512-6ku/R2EzsdjyBaqQn+xGOPbv+BBYBXQYzlA04/46YQLmXkdApi0GYyUwiCXYBxm578iyywzGmM0rep1/q8tuFQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.2.tgz", + "integrity": "sha512-ig2P7GeG//zWlU0AggA3pV1h5gdix0MA3wgB+NsnBXViwiGgY77fuN9Wr5uoCrs2YzaYfogXgsWZbm+HGr09xg==", "cpu": [ "arm64" ], @@ -220,9 +220,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.1.tgz", - "integrity": "sha512-8AKFBk9v/zBDsADvK/0BWZUxkjEc0QDwO8rvbHJKqAZx6DF/VSeBxTRmqWeecrJmx+n3kemEwML9z0eD9IHweQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.2.tgz", + "integrity": "sha512-mLfp0ziRPOLSTek0Gd9T5B8AtzKAkoZE70fneiiyPlSnUKKI4lp+mGEnQXcQEHLJAcIYDPSyBvsUbKUG2ri/XQ==", "cpu": [ "ia32" ], @@ -236,9 +236,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.1.tgz", - "integrity": "sha512-6mOS5CxTGD8qOymp2y4KoM4ir+/REgjdJQFYpwP+WqjrWBo+PUevDGeHHjzCdw/R19PkFqS1bRzv8cTCmB/5kA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.2.tgz", + "integrity": "sha512-hn28+JNDTxxCpnYjdDYVMNTR3SKavyLlCHHkufHV91fkewpIyQchS1d8wSbmXhs1fiYDpNww8KTFlJ1dHsxeSw==", "cpu": [ "loong64" ], @@ -252,9 +252,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.1.tgz", - "integrity": "sha512-Bzmv6rRMzR4ErG2k/jwfj5jKNzVMVEI1tThuirFdAoE+duUv+jlDnlwxsN3s1eqMzADTOV2sSIcUUOfgv++Dgg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.2.tgz", + "integrity": "sha512-KbXaC0Sejt7vD2fEgPoIKb6nxkfYW9OmFUK9XQE4//PvGIxNIfPk1NmlHmMg6f25x57rpmEFrn1OotASYIAaTg==", "cpu": [ "mips64el" ], @@ -268,9 +268,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.1.tgz", - "integrity": "sha512-mPOxA7bd3nmx8TkuO/9M/tE0fnvmuX0wlpwnTL6DPLgkb/Z/KkupexSIw4cLfznn/fPzD89y17VWBjlVNyrpCQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.2.tgz", + "integrity": "sha512-dJ0kE8KTqbiHtA3Fc/zn7lCd7pqVr4JcT0JqOnbj4LLzYnp+7h8Qi4yjfq42ZlHfhOCM42rBh0EwHYLL6LEzcw==", "cpu": [ "ppc64" ], @@ -284,9 +284,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.1.tgz", - "integrity": "sha512-znYb2Mhe9xKIDeIYuTD6vCcUltvYzRT5Yq6sVcdhPrGu8DRdsNZS04B2tSeM+j7T03jL4yY+7/G/jxSJJ9LX2A==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.2.tgz", + "integrity": "sha512-7Z/jKNFufZ/bbu4INqqCN6DDlrmOTmdw6D0gH+6Y7auok2r02Ur661qPuXidPOJ+FSgbEeQnnAGgsVynfLuOEw==", "cpu": [ "riscv64" ], @@ -300,9 +300,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.1.tgz", - "integrity": "sha512-BBIE32cyqAYhMOQ42/jnecoF5P/S5lMob2vXSUiFpD3xCFbXOFkjP1OjfFKnalSO9+B5emvPTQFfNQXuLeVGEw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.2.tgz", + "integrity": "sha512-U+RinR6aXXABFCcAY4gSlv4CL1oOVvSSCdseQmGO66H+XyuQGZIUdhG56SZaDJQcLmrSfRmx5XZOWyCJPRqS7g==", "cpu": [ "s390x" ], @@ -316,9 +316,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.1.tgz", - "integrity": "sha512-PoCvKdHTIbnHmVJ5OEdewGMSw40HDFRTrC/imwh8vrp695RbSUpOqBqNBT45neK0FQleGFbSE/A9X6HlXPDhqA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.2.tgz", + "integrity": "sha512-oxzHTEv6VPm3XXNaHPyUTTte+3wGv7qVQtqaZCrgstI16gCuhNOtBXLEBkBREP57YTd68P0VgDgG73jSD8bwXQ==", "cpu": [ "x64" ], @@ -332,9 +332,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.1.tgz", - "integrity": "sha512-4OrGMPorHCq9h52VLtyyyAmPjC2ZlANx54VDYyCrqXUOi+k0qxnPKXKKprVES67w2mE7TZJx9qZmT+jHeiZbHQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.2.tgz", + "integrity": "sha512-WNa5zZk1XpTTwMDompZmvQLHszDDDN7lYjEHCUmAGB83Bgs20EMs7ICD+oKeT6xt4phV4NDdSi/8OfjPbSbZfQ==", "cpu": [ "x64" ], @@ -348,9 +348,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.1.tgz", - "integrity": "sha512-3a7ZYMjBC4P3FKdTmUZHJw7Mhzp71m+iSFFhX1PnLZ03qmyaB2K+vJZCk4PjRjAvm5lSupJQQtM/AFMyLgKlxQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.2.tgz", + "integrity": "sha512-S6kI1aT3S++Dedb7vxIuUOb3oAxqxk2Rh5rOXOTYnzN8JzW1VzBd+IqPiSpgitu45042SYD3HCoEyhLKQcDFDw==", "cpu": [ "x64" ], @@ -364,9 +364,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.1.tgz", - "integrity": "sha512-29yWBN5XfEjXT8yoeVb8cXfN1jAQLB+uskog1vBMhFR+YWOYvsrwPnh4hspETC/JnF95J+iETrvxgOUlICTWIw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.2.tgz", + "integrity": "sha512-VXSSMsmb+Z8LbsQGcBMiM+fYObDNRm8p7tkUDMPG/g4fhFX5DEFmjxIEa3N8Zr96SjsJ1woAhF0DUnS3MF3ARw==", "cpu": [ "x64" ], @@ -380,9 +380,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.1.tgz", - "integrity": "sha512-9Hb/WUXgyXlL55w3iNVyLkN9gq9x+agv3kk80foWbfpOwe7Qw4Vx6JGB+XQdsIfvvP1kShVQPIvBgVj0TxLlVw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.2.tgz", + "integrity": "sha512-5NayUlSAyb5PQYFAU9x3bHdsqB88RC3aM9lKDAz4X1mo/EchMIT1Q+pSeBXNgkfNmRecLXA0O8xP+x8V+g/LKg==", "cpu": [ "arm64" ], @@ -396,9 +396,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.1.tgz", - "integrity": "sha512-VGdtEcXX/f01NgoM8emDnpdOyrZCQ7VTwLv89MOl3mvJ5fbCOBMNCa8t7RZS4lf12RS87qOuJFX7Bh9aLTbSxg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.2.tgz", + "integrity": "sha512-47gL/ek1v36iN0wL9L4Q2MFdujR0poLZMJwhO2/N3gA89jgHp4MR8DKCmwYtGNksbfJb9JoTtbkoe6sDhg2QTA==", "cpu": [ "ia32" ], @@ -412,9 +412,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.1.tgz", - "integrity": "sha512-H6u8OHmJkKJubLbukVOyi9yA5lzK8VE4TFEkZj2vgusTUPvFeMQ8YnWviVc9F6PuKS6ZIpOvi2/sfiW8tQZQ2g==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.2.tgz", + "integrity": "sha512-tcuhV7ncXBqbt/Ybf0IyrMcwVOAPDckMK9rXNHtF17UTK18OKLpg08glminN06pt2WCoALhXdLfSPbVvK/6fxw==", "cpu": [ "x64" ], @@ -870,9 +870,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.4.10", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.10.tgz", - "integrity": "sha512-vwzFiiy8Rn6E0MtA13/Cxxgpan/N6UeNYR9oUu6kuJWxu6zCk98trcDp8CBhbtaeuq9SykCmXkFr2lWLoPcvLg==", + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.0.tgz", + "integrity": "sha512-Mgq7eCtoTjT89FqNoTzzXg2XvCi5VMhRV6+I2aYanc6kQCBImeNaAYRs/DyoVqk1YEUJK5gN9VO7HRIdz4Wo3Q==", "dev": true }, "node_modules/@types/semver": { @@ -1708,9 +1708,9 @@ "dev": true }, "node_modules/esbuild": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.1.tgz", - "integrity": "sha512-IknHHwV4B/H4imOAu+416fuCvPfRjdncoyGi7eunhSvHuHkdNs50sLWan2LEG2Mym07TuW6gJUIyRS9G1miHEg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.2.tgz", + "integrity": "sha512-G6hPax8UbFakEj3hWO0Vs52LQ8k3lnBhxZWomUJDxfz3rZTLqF5k/FCzuNdLx2RbpBiQQF9H9onlDDH1lZsnjg==", "dev": true, "hasInstallScript": true, "bin": { @@ -1720,28 +1720,28 @@ "node": ">=12" }, "optionalDependencies": { - "@esbuild/android-arm": "0.19.1", - "@esbuild/android-arm64": "0.19.1", - "@esbuild/android-x64": "0.19.1", - "@esbuild/darwin-arm64": "0.19.1", - "@esbuild/darwin-x64": "0.19.1", - "@esbuild/freebsd-arm64": "0.19.1", - "@esbuild/freebsd-x64": "0.19.1", - "@esbuild/linux-arm": "0.19.1", - "@esbuild/linux-arm64": "0.19.1", - "@esbuild/linux-ia32": "0.19.1", - "@esbuild/linux-loong64": "0.19.1", - "@esbuild/linux-mips64el": "0.19.1", - "@esbuild/linux-ppc64": "0.19.1", - "@esbuild/linux-riscv64": "0.19.1", - "@esbuild/linux-s390x": "0.19.1", - "@esbuild/linux-x64": "0.19.1", - "@esbuild/netbsd-x64": "0.19.1", - "@esbuild/openbsd-x64": "0.19.1", - "@esbuild/sunos-x64": "0.19.1", - "@esbuild/win32-arm64": "0.19.1", - "@esbuild/win32-ia32": "0.19.1", - "@esbuild/win32-x64": "0.19.1" + "@esbuild/android-arm": "0.19.2", + "@esbuild/android-arm64": "0.19.2", + "@esbuild/android-x64": "0.19.2", + "@esbuild/darwin-arm64": "0.19.2", + "@esbuild/darwin-x64": "0.19.2", + "@esbuild/freebsd-arm64": "0.19.2", + "@esbuild/freebsd-x64": "0.19.2", + "@esbuild/linux-arm": "0.19.2", + "@esbuild/linux-arm64": "0.19.2", + "@esbuild/linux-ia32": "0.19.2", + "@esbuild/linux-loong64": "0.19.2", + "@esbuild/linux-mips64el": "0.19.2", + "@esbuild/linux-ppc64": "0.19.2", + "@esbuild/linux-riscv64": "0.19.2", + "@esbuild/linux-s390x": "0.19.2", + "@esbuild/linux-x64": "0.19.2", + "@esbuild/netbsd-x64": "0.19.2", + "@esbuild/openbsd-x64": "0.19.2", + "@esbuild/sunos-x64": "0.19.2", + "@esbuild/win32-arm64": "0.19.2", + "@esbuild/win32-ia32": "0.19.2", + "@esbuild/win32-x64": "0.19.2" } }, "node_modules/escalade": { @@ -3913,156 +3913,156 @@ "dev": true }, "@esbuild/android-arm": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.1.tgz", - "integrity": "sha512-yjTucwcOua52z14RL30JMwmCdylsQ5WrErGkAb6VL0MWPbnwJyLejydaRcUqkPO6g0MowlzavdxrR7AcfCW+yA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.2.tgz", + "integrity": "sha512-tM8yLeYVe7pRyAu9VMi/Q7aunpLwD139EY1S99xbQkT4/q2qa6eA4ige/WJQYdJ8GBL1K33pPFhPfPdJ/WzT8Q==", "dev": true, "optional": true }, "@esbuild/android-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.1.tgz", - "integrity": "sha512-CqhrKvDSt76I0so/5afqgKrMv41FjbfUKFrcZddMnrZKqJU70I1MWLVJrImJuYMaY4Yb9rn4UKfF7oZ0BOleVw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.2.tgz", + "integrity": "sha512-lsB65vAbe90I/Qe10OjkmrdxSX4UJDjosDgb8sZUKcg3oefEuW2OT2Vozz8ef7wrJbMcmhvCC+hciF8jY/uAkw==", "dev": true, "optional": true }, "@esbuild/android-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.1.tgz", - "integrity": "sha512-VA29h01MrPkymIL1bFtvL2L4WPogiMGW2N/M+vXZHHOv6LgA9vjzVskTt0v5LjeCjx1PFDcR0ASKy8Y7Gm+iIA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.2.tgz", + "integrity": "sha512-qK/TpmHt2M/Hg82WXHRc/W/2SGo/l1thtDHZWqFq7oi24AjZ4O/CpPSu6ZuYKFkEgmZlFoa7CooAyYmuvnaG8w==", "dev": true, "optional": true }, "@esbuild/darwin-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.1.tgz", - "integrity": "sha512-Be4Cf6WDH7QkLHEpfzQOlBOFdqmqYTSqw2yG3SVmzB3++wy3K7wiNGedezL+q6Jb4weqT9tchO5kkLDC08Jnzg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.2.tgz", + "integrity": "sha512-Ora8JokrvrzEPEpZO18ZYXkH4asCdc1DLdcVy8TGf5eWtPO1Ie4WroEJzwI52ZGtpODy3+m0a2yEX9l+KUn0tA==", "dev": true, "optional": true }, "@esbuild/darwin-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.1.tgz", - "integrity": "sha512-SewtenJi6zCEfZRSUchb+LgJ/IQw8QvnKECPu/qHII1fLQKnVPUVR+VH2IuS03DD9WWnAi3yfOvBNwtrp3WXtg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.2.tgz", + "integrity": "sha512-tP+B5UuIbbFMj2hQaUr6EALlHOIOmlLM2FK7jeFBobPy2ERdohI4Ka6ZFjZ1ZYsrHE/hZimGuU90jusRE0pwDw==", "dev": true, "optional": true }, "@esbuild/freebsd-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.1.tgz", - "integrity": "sha512-TadKO0AaTDAPV2RyGZQ0AaiDTVYg7RsgNaA6OJjXXmoLbTs++NwHtzAmVFBq8Q/P9A11wgkv36HeyAYhWHbW1w==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.2.tgz", + "integrity": "sha512-YbPY2kc0acfzL1VPVK6EnAlig4f+l8xmq36OZkU0jzBVHcOTyQDhnKQaLzZudNJQyymd9OqQezeaBgkTGdTGeQ==", "dev": true, "optional": true }, "@esbuild/freebsd-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.1.tgz", - "integrity": "sha512-DrFMGLF0/aAcZgwhtZr1cby7aHlalpFjLCe5CiI8mm0Kqhhc8gyNZKreaZzvir8CQe0H17p9xx6M9ben5R3r0g==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.2.tgz", + "integrity": "sha512-nSO5uZT2clM6hosjWHAsS15hLrwCvIWx+b2e3lZ3MwbYSaXwvfO528OF+dLjas1g3bZonciivI8qKR/Hm7IWGw==", "dev": true, "optional": true }, "@esbuild/linux-arm": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.1.tgz", - "integrity": "sha512-lCWDVPpQO/Dt5MEqctKujgtUVmwQx7J2Q83EqX/9BejN7BIX4fGJ0QKMiIyy21PFh+/64ArN+Ovh1tzYkTt2wg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.2.tgz", + "integrity": "sha512-Odalh8hICg7SOD7XCj0YLpYCEc+6mkoq63UnExDCiRA2wXEmGlK5JVrW50vZR9Qz4qkvqnHcpH+OFEggO3PgTg==", "dev": true, "optional": true }, "@esbuild/linux-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.1.tgz", - "integrity": "sha512-6ku/R2EzsdjyBaqQn+xGOPbv+BBYBXQYzlA04/46YQLmXkdApi0GYyUwiCXYBxm578iyywzGmM0rep1/q8tuFQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.2.tgz", + "integrity": "sha512-ig2P7GeG//zWlU0AggA3pV1h5gdix0MA3wgB+NsnBXViwiGgY77fuN9Wr5uoCrs2YzaYfogXgsWZbm+HGr09xg==", "dev": true, "optional": true }, "@esbuild/linux-ia32": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.1.tgz", - "integrity": "sha512-8AKFBk9v/zBDsADvK/0BWZUxkjEc0QDwO8rvbHJKqAZx6DF/VSeBxTRmqWeecrJmx+n3kemEwML9z0eD9IHweQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.2.tgz", + "integrity": "sha512-mLfp0ziRPOLSTek0Gd9T5B8AtzKAkoZE70fneiiyPlSnUKKI4lp+mGEnQXcQEHLJAcIYDPSyBvsUbKUG2ri/XQ==", "dev": true, "optional": true }, "@esbuild/linux-loong64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.1.tgz", - "integrity": "sha512-6mOS5CxTGD8qOymp2y4KoM4ir+/REgjdJQFYpwP+WqjrWBo+PUevDGeHHjzCdw/R19PkFqS1bRzv8cTCmB/5kA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.2.tgz", + "integrity": "sha512-hn28+JNDTxxCpnYjdDYVMNTR3SKavyLlCHHkufHV91fkewpIyQchS1d8wSbmXhs1fiYDpNww8KTFlJ1dHsxeSw==", "dev": true, "optional": true }, "@esbuild/linux-mips64el": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.1.tgz", - "integrity": "sha512-Bzmv6rRMzR4ErG2k/jwfj5jKNzVMVEI1tThuirFdAoE+duUv+jlDnlwxsN3s1eqMzADTOV2sSIcUUOfgv++Dgg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.2.tgz", + "integrity": "sha512-KbXaC0Sejt7vD2fEgPoIKb6nxkfYW9OmFUK9XQE4//PvGIxNIfPk1NmlHmMg6f25x57rpmEFrn1OotASYIAaTg==", "dev": true, "optional": true }, "@esbuild/linux-ppc64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.1.tgz", - "integrity": "sha512-mPOxA7bd3nmx8TkuO/9M/tE0fnvmuX0wlpwnTL6DPLgkb/Z/KkupexSIw4cLfznn/fPzD89y17VWBjlVNyrpCQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.2.tgz", + "integrity": "sha512-dJ0kE8KTqbiHtA3Fc/zn7lCd7pqVr4JcT0JqOnbj4LLzYnp+7h8Qi4yjfq42ZlHfhOCM42rBh0EwHYLL6LEzcw==", "dev": true, "optional": true }, "@esbuild/linux-riscv64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.1.tgz", - "integrity": "sha512-znYb2Mhe9xKIDeIYuTD6vCcUltvYzRT5Yq6sVcdhPrGu8DRdsNZS04B2tSeM+j7T03jL4yY+7/G/jxSJJ9LX2A==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.2.tgz", + "integrity": "sha512-7Z/jKNFufZ/bbu4INqqCN6DDlrmOTmdw6D0gH+6Y7auok2r02Ur661qPuXidPOJ+FSgbEeQnnAGgsVynfLuOEw==", "dev": true, "optional": true }, "@esbuild/linux-s390x": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.1.tgz", - "integrity": "sha512-BBIE32cyqAYhMOQ42/jnecoF5P/S5lMob2vXSUiFpD3xCFbXOFkjP1OjfFKnalSO9+B5emvPTQFfNQXuLeVGEw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.2.tgz", + "integrity": "sha512-U+RinR6aXXABFCcAY4gSlv4CL1oOVvSSCdseQmGO66H+XyuQGZIUdhG56SZaDJQcLmrSfRmx5XZOWyCJPRqS7g==", "dev": true, "optional": true }, "@esbuild/linux-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.1.tgz", - "integrity": "sha512-PoCvKdHTIbnHmVJ5OEdewGMSw40HDFRTrC/imwh8vrp695RbSUpOqBqNBT45neK0FQleGFbSE/A9X6HlXPDhqA==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.2.tgz", + "integrity": "sha512-oxzHTEv6VPm3XXNaHPyUTTte+3wGv7qVQtqaZCrgstI16gCuhNOtBXLEBkBREP57YTd68P0VgDgG73jSD8bwXQ==", "dev": true, "optional": true }, "@esbuild/netbsd-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.1.tgz", - "integrity": "sha512-4OrGMPorHCq9h52VLtyyyAmPjC2ZlANx54VDYyCrqXUOi+k0qxnPKXKKprVES67w2mE7TZJx9qZmT+jHeiZbHQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.2.tgz", + "integrity": "sha512-WNa5zZk1XpTTwMDompZmvQLHszDDDN7lYjEHCUmAGB83Bgs20EMs7ICD+oKeT6xt4phV4NDdSi/8OfjPbSbZfQ==", "dev": true, "optional": true }, "@esbuild/openbsd-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.1.tgz", - "integrity": "sha512-3a7ZYMjBC4P3FKdTmUZHJw7Mhzp71m+iSFFhX1PnLZ03qmyaB2K+vJZCk4PjRjAvm5lSupJQQtM/AFMyLgKlxQ==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.2.tgz", + "integrity": "sha512-S6kI1aT3S++Dedb7vxIuUOb3oAxqxk2Rh5rOXOTYnzN8JzW1VzBd+IqPiSpgitu45042SYD3HCoEyhLKQcDFDw==", "dev": true, "optional": true }, "@esbuild/sunos-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.1.tgz", - "integrity": "sha512-29yWBN5XfEjXT8yoeVb8cXfN1jAQLB+uskog1vBMhFR+YWOYvsrwPnh4hspETC/JnF95J+iETrvxgOUlICTWIw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.2.tgz", + "integrity": "sha512-VXSSMsmb+Z8LbsQGcBMiM+fYObDNRm8p7tkUDMPG/g4fhFX5DEFmjxIEa3N8Zr96SjsJ1woAhF0DUnS3MF3ARw==", "dev": true, "optional": true }, "@esbuild/win32-arm64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.1.tgz", - "integrity": "sha512-9Hb/WUXgyXlL55w3iNVyLkN9gq9x+agv3kk80foWbfpOwe7Qw4Vx6JGB+XQdsIfvvP1kShVQPIvBgVj0TxLlVw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.2.tgz", + "integrity": "sha512-5NayUlSAyb5PQYFAU9x3bHdsqB88RC3aM9lKDAz4X1mo/EchMIT1Q+pSeBXNgkfNmRecLXA0O8xP+x8V+g/LKg==", "dev": true, "optional": true }, "@esbuild/win32-ia32": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.1.tgz", - "integrity": "sha512-VGdtEcXX/f01NgoM8emDnpdOyrZCQ7VTwLv89MOl3mvJ5fbCOBMNCa8t7RZS4lf12RS87qOuJFX7Bh9aLTbSxg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.2.tgz", + "integrity": "sha512-47gL/ek1v36iN0wL9L4Q2MFdujR0poLZMJwhO2/N3gA89jgHp4MR8DKCmwYtGNksbfJb9JoTtbkoe6sDhg2QTA==", "dev": true, "optional": true }, "@esbuild/win32-x64": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.1.tgz", - "integrity": "sha512-H6u8OHmJkKJubLbukVOyi9yA5lzK8VE4TFEkZj2vgusTUPvFeMQ8YnWviVc9F6PuKS6ZIpOvi2/sfiW8tQZQ2g==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.2.tgz", + "integrity": "sha512-tcuhV7ncXBqbt/Ybf0IyrMcwVOAPDckMK9rXNHtF17UTK18OKLpg08glminN06pt2WCoALhXdLfSPbVvK/6fxw==", "dev": true, "optional": true }, @@ -4424,9 +4424,9 @@ "dev": true }, "@types/node": { - "version": "20.4.10", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.10.tgz", - "integrity": "sha512-vwzFiiy8Rn6E0MtA13/Cxxgpan/N6UeNYR9oUu6kuJWxu6zCk98trcDp8CBhbtaeuq9SykCmXkFr2lWLoPcvLg==", + "version": "20.5.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.0.tgz", + "integrity": "sha512-Mgq7eCtoTjT89FqNoTzzXg2XvCi5VMhRV6+I2aYanc6kQCBImeNaAYRs/DyoVqk1YEUJK5gN9VO7HRIdz4Wo3Q==", "dev": true }, "@types/semver": { @@ -5023,33 +5023,33 @@ "dev": true }, "esbuild": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.1.tgz", - "integrity": "sha512-IknHHwV4B/H4imOAu+416fuCvPfRjdncoyGi7eunhSvHuHkdNs50sLWan2LEG2Mym07TuW6gJUIyRS9G1miHEg==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.2.tgz", + "integrity": "sha512-G6hPax8UbFakEj3hWO0Vs52LQ8k3lnBhxZWomUJDxfz3rZTLqF5k/FCzuNdLx2RbpBiQQF9H9onlDDH1lZsnjg==", "dev": true, "requires": { - "@esbuild/android-arm": "0.19.1", - "@esbuild/android-arm64": "0.19.1", - "@esbuild/android-x64": "0.19.1", - "@esbuild/darwin-arm64": "0.19.1", - "@esbuild/darwin-x64": "0.19.1", - "@esbuild/freebsd-arm64": "0.19.1", - "@esbuild/freebsd-x64": "0.19.1", - "@esbuild/linux-arm": "0.19.1", - "@esbuild/linux-arm64": "0.19.1", - "@esbuild/linux-ia32": "0.19.1", - "@esbuild/linux-loong64": "0.19.1", - "@esbuild/linux-mips64el": "0.19.1", - "@esbuild/linux-ppc64": "0.19.1", - "@esbuild/linux-riscv64": "0.19.1", - "@esbuild/linux-s390x": "0.19.1", - "@esbuild/linux-x64": "0.19.1", - "@esbuild/netbsd-x64": "0.19.1", - "@esbuild/openbsd-x64": "0.19.1", - "@esbuild/sunos-x64": "0.19.1", - "@esbuild/win32-arm64": "0.19.1", - "@esbuild/win32-ia32": "0.19.1", - "@esbuild/win32-x64": "0.19.1" + "@esbuild/android-arm": "0.19.2", + "@esbuild/android-arm64": "0.19.2", + "@esbuild/android-x64": "0.19.2", + "@esbuild/darwin-arm64": "0.19.2", + "@esbuild/darwin-x64": "0.19.2", + "@esbuild/freebsd-arm64": "0.19.2", + "@esbuild/freebsd-x64": "0.19.2", + "@esbuild/linux-arm": "0.19.2", + "@esbuild/linux-arm64": "0.19.2", + "@esbuild/linux-ia32": "0.19.2", + "@esbuild/linux-loong64": "0.19.2", + "@esbuild/linux-mips64el": "0.19.2", + "@esbuild/linux-ppc64": "0.19.2", + "@esbuild/linux-riscv64": "0.19.2", + "@esbuild/linux-s390x": "0.19.2", + "@esbuild/linux-x64": "0.19.2", + "@esbuild/netbsd-x64": "0.19.2", + "@esbuild/openbsd-x64": "0.19.2", + "@esbuild/sunos-x64": "0.19.2", + "@esbuild/win32-arm64": "0.19.2", + "@esbuild/win32-ia32": "0.19.2", + "@esbuild/win32-x64": "0.19.2" } }, "escalade": { From 3c6c557039eddcc1b2c103ba2ff3e0f00e7c44b6 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Mon, 14 Aug 2023 12:45:27 -0700 Subject: [PATCH 09/81] Move tsserverlibrary.js to typescript.js, make tsserverlibrary.js a shim (#55273) --- Herebyfile.mjs | 51 +- src/testRunner/unittests/publicApi.ts | 16 - src/tsconfig.json | 1 - src/tsserverlibrary/_namespaces/ts.ts | 8 - src/tsserverlibrary/tsconfig.json | 12 - src/tsserverlibrary/tsserverlibrary.ts | 3 - .../_namespaces/ts.server.ts | 0 src/typescript/_namespaces/ts.ts | 4 +- src/typescript/tsconfig.json | 2 +- tests/baselines/reference/APILibCheck.types | 4 +- .../reference/api/tsserverlibrary.d.ts | 11261 +--------------- tests/baselines/reference/api/typescript.d.ts | 4144 +++++- 12 files changed, 4105 insertions(+), 11401 deletions(-) delete mode 100644 src/tsserverlibrary/_namespaces/ts.ts delete mode 100644 src/tsserverlibrary/tsconfig.json delete mode 100644 src/tsserverlibrary/tsserverlibrary.ts rename src/{tsserverlibrary => typescript}/_namespaces/ts.server.ts (100%) diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 3fd78e0af7b07..38269cbcc3929 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -404,27 +404,50 @@ export const watchMin = task({ -const { main: lssl, build: buildLssl, watch: watchLssl } = entrypointBuildTask({ +// This is technically not enough to make tsserverlibrary loadable in the +// browser, but it's unlikely that anyone has actually been doing that. +const lsslJs = ` +if (typeof module !== "undefined" && module.exports) { + module.exports = require("./typescript.js"); +} +else { + throw new Error("tsserverlibrary requires CommonJS; use typescript.js instead"); +} +`; + +const lsslDts = ` +import ts = require("./typescript.js"); +export = ts; +`; + +const lsslDtsInternal = ` +import ts = require("./typescript.internal.js"); +export = ts; +`; + +/** + * @param {string} contents + */ +async function fileContentsWithCopyright(contents) { + return await copyright() + contents.trim().replace(/\r\n/g, "\n") + "\n"; +} + +const lssl = task({ name: "lssl", description: "Builds language service server library", - buildDeps: [generateDiagnostics], - project: "src/tsserverlibrary", - srcEntrypoint: "./src/tsserverlibrary/tsserverlibrary.ts", - builtEntrypoint: "./built/local/tsserverlibrary/tsserverlibrary.js", - output: "./built/local/tsserverlibrary.js", - mainDeps: [generateLibs], - bundlerOptions: { exportIsTsObject: true }, + dependencies: [services], + run: async () => { + await fs.promises.writeFile("./built/local/tsserverlibrary.js", await fileContentsWithCopyright(lsslJs)); + } }); -export { lssl, watchLssl }; export const dtsLssl = task({ name: "dts-lssl", description: "Bundles tsserverlibrary.d.ts", - dependencies: [buildLssl], + dependencies: [dtsServices], run: async () => { - if (needsUpdate("./built/local/tsserverlibrary/tsconfig.tsbuildinfo", ["./built/local/tsserverlibrary.d.ts", "./built/local/tsserverlibrary.internal.d.ts"])) { - await runDtsBundler("./built/local/tsserverlibrary/tsserverlibrary.d.ts", "./built/local/tsserverlibrary.d.ts"); - } + await fs.promises.writeFile("./built/local/tsserverlibrary.d.ts", await fileContentsWithCopyright(lsslDts)); + await fs.promises.writeFile("./built/local/tsserverlibrary.internal.d.ts", await fileContentsWithCopyright(lsslDtsInternal)); } }); @@ -563,7 +586,7 @@ export const watchLocal = task({ name: "watch-local", description: "Watches the full compiler and services", hiddenFromTaskList: true, - dependencies: [localize, watchTsc, watchTsserver, watchServices, watchLssl, watchOtherOutputs, dts, watchSrc], + dependencies: [localize, watchTsc, watchTsserver, watchServices, lssl, watchOtherOutputs, dts, watchSrc], }); const runtestsDeps = [tests, generateLibs].concat(cmdLineOptions.typecheck ? [dts] : []); diff --git a/src/testRunner/unittests/publicApi.ts b/src/testRunner/unittests/publicApi.ts index 3afe25d4e9709..e0facd0594d82 100644 --- a/src/testRunner/unittests/publicApi.ts +++ b/src/testRunner/unittests/publicApi.ts @@ -1,4 +1,3 @@ -import * as compiler from "../_namespaces/compiler"; import * as documents from "../_namespaces/documents"; import * as fakes from "../_namespaces/fakes"; import * as Harness from "../_namespaces/Harness"; @@ -19,21 +18,6 @@ describe("unittests:: Public APIs", () => { it("should be acknowledged when they change", () => { Harness.Baseline.runBaseline(api, fileContent, { PrintDiff: true }); }); - - it("should compile", () => { - const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false); - fs.linkSync(`${vfs.builtFolder}/${fileName}`, `${vfs.srcFolder}/${fileName}`); - const sys = new fakes.System(fs); - const options: ts.CompilerOptions = { - ...ts.getDefaultCompilerOptions(), - strict: true, - exactOptionalPropertyTypes: true, - lib: ["lib.es2018.d.ts"], - }; - const host = new fakes.CompilerHost(sys, options); - const result = compiler.compileFiles(host, [`${vfs.srcFolder}/${fileName}`], options); - assert(!result.diagnostics || !result.diagnostics.length, Harness.Compiler.minimalDiagnosticsToString(result.diagnostics, /*pretty*/ true)); - }); } describe("for the language service and compiler", () => { diff --git a/src/tsconfig.json b/src/tsconfig.json index 41c4a2026a723..004634f5683d7 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -13,7 +13,6 @@ { "path": "./testRunner" }, { "path": "./tsc" }, { "path": "./tsserver" }, - { "path": "./tsserverlibrary" }, { "path": "./typescript" }, { "path": "./typingsInstaller" }, { "path": "./typingsInstallerCore" }, diff --git a/src/tsserverlibrary/_namespaces/ts.ts b/src/tsserverlibrary/_namespaces/ts.ts deleted file mode 100644 index 3060a64378787..0000000000000 --- a/src/tsserverlibrary/_namespaces/ts.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* Generated file to emulate the ts namespace. */ - -export * from "../../compiler/_namespaces/ts"; -export * from "../../jsTyping/_namespaces/ts"; -export * from "../../services/_namespaces/ts"; -export * from "../../server/_namespaces/ts"; -import * as server from "./ts.server"; -export { server }; diff --git a/src/tsserverlibrary/tsconfig.json b/src/tsserverlibrary/tsconfig.json deleted file mode 100644 index 20b8306af53eb..0000000000000 --- a/src/tsserverlibrary/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../tsconfig-base", - "compilerOptions": { - }, - "references": [ - { "path": "../compiler" }, - { "path": "../jsTyping" }, - { "path": "../services" }, - { "path": "../server" } - ], - "include": ["**/*"] -} diff --git a/src/tsserverlibrary/tsserverlibrary.ts b/src/tsserverlibrary/tsserverlibrary.ts deleted file mode 100644 index 6651ea687d4d7..0000000000000 --- a/src/tsserverlibrary/tsserverlibrary.ts +++ /dev/null @@ -1,3 +0,0 @@ -import * as ts from "./_namespaces/ts"; - -export = ts; diff --git a/src/tsserverlibrary/_namespaces/ts.server.ts b/src/typescript/_namespaces/ts.server.ts similarity index 100% rename from src/tsserverlibrary/_namespaces/ts.server.ts rename to src/typescript/_namespaces/ts.server.ts diff --git a/src/typescript/_namespaces/ts.ts b/src/typescript/_namespaces/ts.ts index e55b26438094f..3060a64378787 100644 --- a/src/typescript/_namespaces/ts.ts +++ b/src/typescript/_namespaces/ts.ts @@ -3,4 +3,6 @@ export * from "../../compiler/_namespaces/ts"; export * from "../../jsTyping/_namespaces/ts"; export * from "../../services/_namespaces/ts"; -export * from "../../deprecatedCompat/_namespaces/ts"; +export * from "../../server/_namespaces/ts"; +import * as server from "./ts.server"; +export { server }; diff --git a/src/typescript/tsconfig.json b/src/typescript/tsconfig.json index 4bc23cc65b439..20b8306af53eb 100644 --- a/src/typescript/tsconfig.json +++ b/src/typescript/tsconfig.json @@ -6,7 +6,7 @@ { "path": "../compiler" }, { "path": "../jsTyping" }, { "path": "../services" }, - { "path": "../deprecatedCompat" } + { "path": "../server" } ], "include": ["**/*"] } diff --git a/tests/baselines/reference/APILibCheck.types b/tests/baselines/reference/APILibCheck.types index 6c30c99d7c432..28d48dfbeb22f 100644 --- a/tests/baselines/reference/APILibCheck.types +++ b/tests/baselines/reference/APILibCheck.types @@ -8,8 +8,8 @@ import tsInternal = require("typescript-internal"); >tsInternal : typeof tsInternal import tsserverlibrary = require("tsserverlibrary"); ->tsserverlibrary : typeof tsserverlibrary +>tsserverlibrary : typeof ts import tsserverlibraryInternal = require("tsserverlibrary-internal"); ->tsserverlibraryInternal : typeof tsserverlibraryInternal +>tsserverlibraryInternal : typeof tsInternal diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 0421149e4cff8..3db5faa718232 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -13,11262 +13,5 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ -declare namespace ts { - namespace server { - type ActionSet = "action::set"; - type ActionInvalidate = "action::invalidate"; - type ActionPackageInstalled = "action::packageInstalled"; - type EventTypesRegistry = "event::typesRegistry"; - type EventBeginInstallTypes = "event::beginInstallTypes"; - type EventEndInstallTypes = "event::endInstallTypes"; - type EventInitializationFailed = "event::initializationFailed"; - type ActionWatchTypingLocations = "action::watchTypingLocations"; - interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed | ActionWatchTypingLocations; - } - interface TypingInstallerRequestWithProjectName { - readonly projectName: string; - } - interface DiscoverTypings extends TypingInstallerRequestWithProjectName { - readonly fileNames: string[]; - readonly projectRootPath: Path; - readonly compilerOptions: CompilerOptions; - readonly typeAcquisition: TypeAcquisition; - readonly unresolvedImports: SortedReadonlyArray; - readonly cachePath?: string; - readonly kind: "discover"; - } - interface CloseProject extends TypingInstallerRequestWithProjectName { - readonly kind: "closeProject"; - } - interface TypesRegistryRequest { - readonly kind: "typesRegistry"; - } - interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { - readonly kind: "installPackage"; - readonly fileName: Path; - readonly packageName: string; - readonly projectRootPath: Path; - } - interface PackageInstalledResponse extends ProjectResponse { - readonly kind: ActionPackageInstalled; - readonly success: boolean; - readonly message: string; - } - interface InitializationFailedResponse extends TypingInstallerResponse { - readonly kind: EventInitializationFailed; - readonly message: string; - readonly stack?: string; - } - interface ProjectResponse extends TypingInstallerResponse { - readonly projectName: string; - } - interface InvalidateCachedTypings extends ProjectResponse { - readonly kind: ActionInvalidate; - } - interface InstallTypes extends ProjectResponse { - readonly kind: EventBeginInstallTypes | EventEndInstallTypes; - readonly eventId: number; - readonly typingsInstallerVersion: string; - readonly packagesToInstall: readonly string[]; - } - interface BeginInstallTypes extends InstallTypes { - readonly kind: EventBeginInstallTypes; - } - interface EndInstallTypes extends InstallTypes { - readonly kind: EventEndInstallTypes; - readonly installSuccess: boolean; - } - interface InstallTypingHost extends JsTyping.TypingResolutionHost { - useCaseSensitiveFileNames: boolean; - writeFile(path: string, content: string): void; - createDirectory(path: string): void; - getCurrentDirectory?(): string; - } - interface SetTypings extends ProjectResponse { - readonly typeAcquisition: TypeAcquisition; - readonly compilerOptions: CompilerOptions; - readonly typings: string[]; - readonly unresolvedImports: SortedReadonlyArray; - readonly kind: ActionSet; - } - interface WatchTypingLocations extends ProjectResponse { - /** if files is undefined, retain same set of watchers */ - readonly files: readonly string[] | undefined; - readonly kind: ActionWatchTypingLocations; - } - namespace protocol { - enum CommandTypes { - JsxClosingTag = "jsxClosingTag", - LinkedEditingRange = "linkedEditingRange", - Brace = "brace", - BraceCompletion = "braceCompletion", - GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", - Change = "change", - Close = "close", - /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ - Completions = "completions", - CompletionInfo = "completionInfo", - CompletionDetails = "completionEntryDetails", - CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", - CompileOnSaveEmitFile = "compileOnSaveEmitFile", - Configure = "configure", - Definition = "definition", - DefinitionAndBoundSpan = "definitionAndBoundSpan", - Implementation = "implementation", - Exit = "exit", - FileReferences = "fileReferences", - Format = "format", - Formatonkey = "formatonkey", - Geterr = "geterr", - GeterrForProject = "geterrForProject", - SemanticDiagnosticsSync = "semanticDiagnosticsSync", - SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", - SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", - NavBar = "navbar", - Navto = "navto", - NavTree = "navtree", - NavTreeFull = "navtree-full", - DocumentHighlights = "documentHighlights", - Open = "open", - Quickinfo = "quickinfo", - References = "references", - Reload = "reload", - Rename = "rename", - Saveto = "saveto", - SignatureHelp = "signatureHelp", - FindSourceDefinition = "findSourceDefinition", - Status = "status", - TypeDefinition = "typeDefinition", - ProjectInfo = "projectInfo", - ReloadProjects = "reloadProjects", - Unknown = "unknown", - OpenExternalProject = "openExternalProject", - OpenExternalProjects = "openExternalProjects", - CloseExternalProject = "closeExternalProject", - UpdateOpen = "updateOpen", - GetOutliningSpans = "getOutliningSpans", - TodoComments = "todoComments", - Indentation = "indentation", - DocCommentTemplate = "docCommentTemplate", - CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", - GetCodeFixes = "getCodeFixes", - GetCombinedCodeFix = "getCombinedCodeFix", - ApplyCodeActionCommand = "applyCodeActionCommand", - GetSupportedCodeFixes = "getSupportedCodeFixes", - GetApplicableRefactors = "getApplicableRefactors", - GetEditsForRefactor = "getEditsForRefactor", - GetMoveToRefactoringFileSuggestions = "getMoveToRefactoringFileSuggestions", - OrganizeImports = "organizeImports", - GetEditsForFileRename = "getEditsForFileRename", - ConfigurePlugin = "configurePlugin", - SelectionRange = "selectionRange", - ToggleLineComment = "toggleLineComment", - ToggleMultilineComment = "toggleMultilineComment", - CommentSelection = "commentSelection", - UncommentSelection = "uncommentSelection", - PrepareCallHierarchy = "prepareCallHierarchy", - ProvideCallHierarchyIncomingCalls = "provideCallHierarchyIncomingCalls", - ProvideCallHierarchyOutgoingCalls = "provideCallHierarchyOutgoingCalls", - ProvideInlayHints = "provideInlayHints" - } - /** - * A TypeScript Server message - */ - interface Message { - /** - * Sequence number of the message - */ - seq: number; - /** - * One of "request", "response", or "event" - */ - type: "request" | "response" | "event"; - } - /** - * Client-initiated request message - */ - interface Request extends Message { - type: "request"; - /** - * The command to execute - */ - command: string; - /** - * Object containing arguments for the command - */ - arguments?: any; - } - /** - * Request to reload the project structure for all the opened files - */ - interface ReloadProjectsRequest extends Message { - command: CommandTypes.ReloadProjects; - } - /** - * Server-initiated event message - */ - interface Event extends Message { - type: "event"; - /** - * Name of event - */ - event: string; - /** - * Event-specific information - */ - body?: any; - } - /** - * Response by server to client request message. - */ - interface Response extends Message { - type: "response"; - /** - * Sequence number of the request message. - */ - request_seq: number; - /** - * Outcome of the request. - */ - success: boolean; - /** - * The command requested. - */ - command: string; - /** - * If success === false, this should always be provided. - * Otherwise, may (or may not) contain a success message. - */ - message?: string; - /** - * Contains message body if success === true. - */ - body?: any; - /** - * Contains extra information that plugin can include to be passed on - */ - metadata?: unknown; - /** - * Exposes information about the performance of this request-response pair. - */ - performanceData?: PerformanceData; - } - interface PerformanceData { - /** - * Time spent updating the program graph, in milliseconds. - */ - updateGraphDurationMs?: number; - /** - * The time spent creating or updating the auto-import program, in milliseconds. - */ - createAutoImportProviderProgramDurationMs?: number; - } - /** - * Arguments for FileRequest messages. - */ - interface FileRequestArgs { - /** - * The file for the request (absolute pathname required). - */ - file: string; - projectFileName?: string; - } - interface StatusRequest extends Request { - command: CommandTypes.Status; - } - interface StatusResponseBody { - /** - * The TypeScript version (`ts.version`). - */ - version: string; - } - /** - * Response to StatusRequest - */ - interface StatusResponse extends Response { - body: StatusResponseBody; - } - /** - * Requests a JS Doc comment template for a given position - */ - interface DocCommentTemplateRequest extends FileLocationRequest { - command: CommandTypes.DocCommentTemplate; - } - /** - * Response to DocCommentTemplateRequest - */ - interface DocCommandTemplateResponse extends Response { - body?: TextInsertion; - } - /** - * A request to get TODO comments from the file - */ - interface TodoCommentRequest extends FileRequest { - command: CommandTypes.TodoComments; - arguments: TodoCommentRequestArgs; - } - /** - * Arguments for TodoCommentRequest request. - */ - interface TodoCommentRequestArgs extends FileRequestArgs { - /** - * Array of target TodoCommentDescriptors that describes TODO comments to be found - */ - descriptors: TodoCommentDescriptor[]; - } - /** - * Response for TodoCommentRequest request. - */ - interface TodoCommentsResponse extends Response { - body?: TodoComment[]; - } - /** - * A request to determine if the caret is inside a comment. - */ - interface SpanOfEnclosingCommentRequest extends FileLocationRequest { - command: CommandTypes.GetSpanOfEnclosingComment; - arguments: SpanOfEnclosingCommentRequestArgs; - } - interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { - /** - * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. - */ - onlyMultiLine: boolean; - } - /** - * Request to obtain outlining spans in file. - */ - interface OutliningSpansRequest extends FileRequest { - command: CommandTypes.GetOutliningSpans; - } - interface OutliningSpan { - /** The span of the document to actually collapse. */ - textSpan: TextSpan; - /** The span of the document to display when the user hovers over the collapsed span. */ - hintSpan: TextSpan; - /** The text to display in the editor for the collapsed region. */ - bannerText: string; - /** - * Whether or not this region should be automatically collapsed when - * the 'Collapse to Definitions' command is invoked. - */ - autoCollapse: boolean; - /** - * Classification of the contents of the span - */ - kind: OutliningSpanKind; - } - /** - * Response to OutliningSpansRequest request. - */ - interface OutliningSpansResponse extends Response { - body?: OutliningSpan[]; - } - /** - * A request to get indentation for a location in file - */ - interface IndentationRequest extends FileLocationRequest { - command: CommandTypes.Indentation; - arguments: IndentationRequestArgs; - } - /** - * Response for IndentationRequest request. - */ - interface IndentationResponse extends Response { - body?: IndentationResult; - } - /** - * Indentation result representing where indentation should be placed - */ - interface IndentationResult { - /** - * The base position in the document that the indent should be relative to - */ - position: number; - /** - * The number of columns the indent should be at relative to the position's column. - */ - indentation: number; - } - /** - * Arguments for IndentationRequest request. - */ - interface IndentationRequestArgs extends FileLocationRequestArgs { - /** - * An optional set of settings to be used when computing indentation. - * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. - */ - options?: EditorSettings; - } - /** - * Arguments for ProjectInfoRequest request. - */ - interface ProjectInfoRequestArgs extends FileRequestArgs { - /** - * Indicate if the file name list of the project is needed - */ - needFileNameList: boolean; - } - /** - * A request to get the project information of the current file. - */ - interface ProjectInfoRequest extends Request { - command: CommandTypes.ProjectInfo; - arguments: ProjectInfoRequestArgs; - } - /** - * A request to retrieve compiler options diagnostics for a project - */ - interface CompilerOptionsDiagnosticsRequest extends Request { - arguments: CompilerOptionsDiagnosticsRequestArgs; - } - /** - * Arguments for CompilerOptionsDiagnosticsRequest request. - */ - interface CompilerOptionsDiagnosticsRequestArgs { - /** - * Name of the project to retrieve compiler options diagnostics. - */ - projectFileName: string; - } - /** - * Response message body for "projectInfo" request - */ - interface ProjectInfo { - /** - * For configured project, this is the normalized path of the 'tsconfig.json' file - * For inferred project, this is undefined - */ - configFileName: string; - /** - * The list of normalized file name in the project, including 'lib.d.ts' - */ - fileNames?: string[]; - /** - * Indicates if the project has a active language service instance - */ - languageServiceDisabled?: boolean; - } - /** - * Represents diagnostic info that includes location of diagnostic in two forms - * - start position and length of the error span - * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. - */ - interface DiagnosticWithLinePosition { - message: string; - start: number; - length: number; - startLocation: Location; - endLocation: Location; - category: string; - code: number; - /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ - reportsUnnecessary?: {}; - reportsDeprecated?: {}; - relatedInformation?: DiagnosticRelatedInformation[]; - } - /** - * Response message for "projectInfo" request - */ - interface ProjectInfoResponse extends Response { - body?: ProjectInfo; - } - /** - * Request whose sole parameter is a file name. - */ - interface FileRequest extends Request { - arguments: FileRequestArgs; - } - /** - * Instances of this interface specify a location in a source file: - * (file, line, character offset), where line and character offset are 1-based. - */ - interface FileLocationRequestArgs extends FileRequestArgs { - /** - * The line number for the request (1-based). - */ - line: number; - /** - * The character offset (on the line) for the request (1-based). - */ - offset: number; - } - type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; - /** - * Request refactorings at a given position or selection area. - */ - interface GetApplicableRefactorsRequest extends Request { - command: CommandTypes.GetApplicableRefactors; - arguments: GetApplicableRefactorsRequestArgs; - } - type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs & { - triggerReason?: RefactorTriggerReason; - kind?: string; - /** - * Include refactor actions that require additional arguments to be passed when - * calling 'GetEditsForRefactor'. When true, clients should inspect the - * `isInteractive` property of each returned `RefactorActionInfo` - * and ensure they are able to collect the appropriate arguments for any - * interactive refactor before offering it. - */ - includeInteractiveActions?: boolean; - }; - type RefactorTriggerReason = "implicit" | "invoked"; - /** - * Response is a list of available refactorings. - * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring - */ - interface GetApplicableRefactorsResponse extends Response { - body?: ApplicableRefactorInfo[]; - } - /** - * Request refactorings at a given position or selection area to move to an existing file. - */ - interface GetMoveToRefactoringFileSuggestionsRequest extends Request { - command: CommandTypes.GetMoveToRefactoringFileSuggestions; - arguments: GetMoveToRefactoringFileSuggestionsRequestArgs; - } - type GetMoveToRefactoringFileSuggestionsRequestArgs = FileLocationOrRangeRequestArgs & { - kind?: string; - }; - /** - * Response is a list of available files. - * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring - */ - interface GetMoveToRefactoringFileSuggestions extends Response { - body: { - newFileName: string; - files: string[]; - }; - } - /** - * A set of one or more available refactoring actions, grouped under a parent refactoring. - */ - interface ApplicableRefactorInfo { - /** - * The programmatic name of the refactoring - */ - name: string; - /** - * A description of this refactoring category to show to the user. - * If the refactoring gets inlined (see below), this text will not be visible. - */ - description: string; - /** - * Inlineable refactorings can have their actions hoisted out to the top level - * of a context menu. Non-inlineanable refactorings should always be shown inside - * their parent grouping. - * - * If not specified, this value is assumed to be 'true' - */ - inlineable?: boolean; - actions: RefactorActionInfo[]; - } - /** - * Represents a single refactoring action - for example, the "Extract Method..." refactor might - * offer several actions, each corresponding to a surround class or closure to extract into. - */ - interface RefactorActionInfo { - /** - * The programmatic name of the refactoring action - */ - name: string; - /** - * A description of this refactoring action to show to the user. - * If the parent refactoring is inlined away, this will be the only text shown, - * so this description should make sense by itself if the parent is inlineable=true - */ - description: string; - /** - * A message to show to the user if the refactoring cannot be applied in - * the current context. - */ - notApplicableReason?: string; - /** - * The hierarchical dotted name of the refactor action. - */ - kind?: string; - /** - * Indicates that the action requires additional arguments to be passed - * when calling 'GetEditsForRefactor'. - */ - isInteractive?: boolean; - } - interface GetEditsForRefactorRequest extends Request { - command: CommandTypes.GetEditsForRefactor; - arguments: GetEditsForRefactorRequestArgs; - } - /** - * Request the edits that a particular refactoring action produces. - * Callers must specify the name of the refactor and the name of the action. - */ - type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { - refactor: string; - action: string; - interactiveRefactorArguments?: InteractiveRefactorArguments; - }; - interface GetEditsForRefactorResponse extends Response { - body?: RefactorEditInfo; - } - interface RefactorEditInfo { - edits: FileCodeEdits[]; - /** - * An optional location where the editor should start a rename operation once - * the refactoring edits have been applied - */ - renameLocation?: Location; - renameFilename?: string; - notApplicableReason?: string; - } - /** - * Organize imports by: - * 1) Removing unused imports - * 2) Coalescing imports from the same module - * 3) Sorting imports - */ - interface OrganizeImportsRequest extends Request { - command: CommandTypes.OrganizeImports; - arguments: OrganizeImportsRequestArgs; - } - type OrganizeImportsScope = GetCombinedCodeFixScope; - enum OrganizeImportsMode { - All = "All", - SortAndCombine = "SortAndCombine", - RemoveUnused = "RemoveUnused" - } - interface OrganizeImportsRequestArgs { - scope: OrganizeImportsScope; - /** @deprecated Use `mode` instead */ - skipDestructiveCodeActions?: boolean; - mode?: OrganizeImportsMode; - } - interface OrganizeImportsResponse extends Response { - body: readonly FileCodeEdits[]; - } - interface GetEditsForFileRenameRequest extends Request { - command: CommandTypes.GetEditsForFileRename; - arguments: GetEditsForFileRenameRequestArgs; - } - /** Note: Paths may also be directories. */ - interface GetEditsForFileRenameRequestArgs { - readonly oldFilePath: string; - readonly newFilePath: string; - } - interface GetEditsForFileRenameResponse extends Response { - body: readonly FileCodeEdits[]; - } - /** - * Request for the available codefixes at a specific position. - */ - interface CodeFixRequest extends Request { - command: CommandTypes.GetCodeFixes; - arguments: CodeFixRequestArgs; - } - interface GetCombinedCodeFixRequest extends Request { - command: CommandTypes.GetCombinedCodeFix; - arguments: GetCombinedCodeFixRequestArgs; - } - interface GetCombinedCodeFixResponse extends Response { - body: CombinedCodeActions; - } - interface ApplyCodeActionCommandRequest extends Request { - command: CommandTypes.ApplyCodeActionCommand; - arguments: ApplyCodeActionCommandRequestArgs; - } - interface ApplyCodeActionCommandResponse extends Response { - } - interface FileRangeRequestArgs extends FileRequestArgs { - /** - * The line number for the request (1-based). - */ - startLine: number; - /** - * The character offset (on the line) for the request (1-based). - */ - startOffset: number; - /** - * The line number for the request (1-based). - */ - endLine: number; - /** - * The character offset (on the line) for the request (1-based). - */ - endOffset: number; - } - /** - * Instances of this interface specify errorcodes on a specific location in a sourcefile. - */ - interface CodeFixRequestArgs extends FileRangeRequestArgs { - /** - * Errorcodes we want to get the fixes for. - */ - errorCodes: readonly number[]; - } - interface GetCombinedCodeFixRequestArgs { - scope: GetCombinedCodeFixScope; - fixId: {}; - } - interface GetCombinedCodeFixScope { - type: "file"; - args: FileRequestArgs; - } - interface ApplyCodeActionCommandRequestArgs { - /** May also be an array of commands. */ - command: {}; - } - /** - * Response for GetCodeFixes request. - */ - interface GetCodeFixesResponse extends Response { - body?: CodeAction[]; - } - /** - * A request whose arguments specify a file location (file, line, col). - */ - interface FileLocationRequest extends FileRequest { - arguments: FileLocationRequestArgs; - } - /** - * A request to get codes of supported code fixes. - */ - interface GetSupportedCodeFixesRequest extends Request { - command: CommandTypes.GetSupportedCodeFixes; - arguments?: Partial; - } - /** - * A response for GetSupportedCodeFixesRequest request. - */ - interface GetSupportedCodeFixesResponse extends Response { - /** - * List of error codes supported by the server. - */ - body?: string[]; - } - /** - * A request to get encoded semantic classifications for a span in the file - */ - interface EncodedSemanticClassificationsRequest extends FileRequest { - arguments: EncodedSemanticClassificationsRequestArgs; - } - /** - * Arguments for EncodedSemanticClassificationsRequest request. - */ - interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { - /** - * Start position of the span. - */ - start: number; - /** - * Length of the span. - */ - length: number; - /** - * Optional parameter for the semantic highlighting response, if absent it - * defaults to "original". - */ - format?: "original" | "2020"; - } - /** The response for a EncodedSemanticClassificationsRequest */ - interface EncodedSemanticClassificationsResponse extends Response { - body?: EncodedSemanticClassificationsResponseBody; - } - /** - * Implementation response message. Gives series of text spans depending on the format ar. - */ - interface EncodedSemanticClassificationsResponseBody { - endOfLineState: EndOfLineState; - spans: number[]; - } - /** - * Arguments in document highlight request; include: filesToSearch, file, - * line, offset. - */ - interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { - /** - * List of files to search for document highlights. - */ - filesToSearch: string[]; - } - /** - * Go to definition request; value of command field is - * "definition". Return response giving the file locations that - * define the symbol found in file at location line, col. - */ - interface DefinitionRequest extends FileLocationRequest { - command: CommandTypes.Definition; - } - interface DefinitionAndBoundSpanRequest extends FileLocationRequest { - readonly command: CommandTypes.DefinitionAndBoundSpan; - } - interface FindSourceDefinitionRequest extends FileLocationRequest { - readonly command: CommandTypes.FindSourceDefinition; - } - interface DefinitionAndBoundSpanResponse extends Response { - readonly body: DefinitionInfoAndBoundSpan; - } - /** - * Go to type request; value of command field is - * "typeDefinition". Return response giving the file locations that - * define the type for the symbol found in file at location line, col. - */ - interface TypeDefinitionRequest extends FileLocationRequest { - command: CommandTypes.TypeDefinition; - } - /** - * Go to implementation request; value of command field is - * "implementation". Return response giving the file locations that - * implement the symbol found in file at location line, col. - */ - interface ImplementationRequest extends FileLocationRequest { - command: CommandTypes.Implementation; - } - /** - * Location in source code expressed as (one-based) line and (one-based) column offset. - */ - interface Location { - line: number; - offset: number; - } - /** - * Object found in response messages defining a span of text in source code. - */ - interface TextSpan { - /** - * First character of the definition. - */ - start: Location; - /** - * One character past last character of the definition. - */ - end: Location; - } - /** - * Object found in response messages defining a span of text in a specific source file. - */ - interface FileSpan extends TextSpan { - /** - * File containing text span. - */ - file: string; - } - interface JSDocTagInfo { - /** Name of the JSDoc tag */ - name: string; - /** - * Comment text after the JSDoc tag -- the text after the tag name until the next tag or end of comment - * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. - */ - text?: string | SymbolDisplayPart[]; - } - interface TextSpanWithContext extends TextSpan { - contextStart?: Location; - contextEnd?: Location; - } - interface FileSpanWithContext extends FileSpan, TextSpanWithContext { - } - interface DefinitionInfo extends FileSpanWithContext { - /** - * When true, the file may or may not exist. - */ - unverified?: boolean; - } - interface DefinitionInfoAndBoundSpan { - definitions: readonly DefinitionInfo[]; - textSpan: TextSpan; - } - /** - * Definition response message. Gives text range for definition. - */ - interface DefinitionResponse extends Response { - body?: DefinitionInfo[]; - } - interface DefinitionInfoAndBoundSpanResponse extends Response { - body?: DefinitionInfoAndBoundSpan; - } - /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ - type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; - /** - * Definition response message. Gives text range for definition. - */ - interface TypeDefinitionResponse extends Response { - body?: FileSpanWithContext[]; - } - /** - * Implementation response message. Gives text range for implementations. - */ - interface ImplementationResponse extends Response { - body?: FileSpanWithContext[]; - } - /** - * Request to get brace completion for a location in the file. - */ - interface BraceCompletionRequest extends FileLocationRequest { - command: CommandTypes.BraceCompletion; - arguments: BraceCompletionRequestArgs; - } - /** - * Argument for BraceCompletionRequest request. - */ - interface BraceCompletionRequestArgs extends FileLocationRequestArgs { - /** - * Kind of opening brace - */ - openingBrace: string; - } - interface JsxClosingTagRequest extends FileLocationRequest { - readonly command: CommandTypes.JsxClosingTag; - readonly arguments: JsxClosingTagRequestArgs; - } - interface JsxClosingTagRequestArgs extends FileLocationRequestArgs { - } - interface JsxClosingTagResponse extends Response { - readonly body: TextInsertion; - } - interface LinkedEditingRangeRequest extends FileLocationRequest { - readonly command: CommandTypes.LinkedEditingRange; - } - interface LinkedEditingRangesBody { - ranges: TextSpan[]; - wordPattern?: string; - } - interface LinkedEditingRangeResponse extends Response { - readonly body: LinkedEditingRangesBody; - } - /** - * Get document highlights request; value of command field is - * "documentHighlights". Return response giving spans that are relevant - * in the file at a given line and column. - */ - interface DocumentHighlightsRequest extends FileLocationRequest { - command: CommandTypes.DocumentHighlights; - arguments: DocumentHighlightsRequestArgs; - } - /** - * Span augmented with extra information that denotes the kind of the highlighting to be used for span. - */ - interface HighlightSpan extends TextSpanWithContext { - kind: HighlightSpanKind; - } - /** - * Represents a set of highligh spans for a give name - */ - interface DocumentHighlightsItem { - /** - * File containing highlight spans. - */ - file: string; - /** - * Spans to highlight in file. - */ - highlightSpans: HighlightSpan[]; - } - /** - * Response for a DocumentHighlightsRequest request. - */ - interface DocumentHighlightsResponse extends Response { - body?: DocumentHighlightsItem[]; - } - /** - * Find references request; value of command field is - * "references". Return response giving the file locations that - * reference the symbol found in file at location line, col. - */ - interface ReferencesRequest extends FileLocationRequest { - command: CommandTypes.References; - } - interface ReferencesResponseItem extends FileSpanWithContext { - /** - * Text of line containing the reference. Including this - * with the response avoids latency of editor loading files - * to show text of reference line (the server already has loaded the referencing files). - * - * If {@link UserPreferences.disableLineTextInReferences} is enabled, the property won't be filled - */ - lineText?: string; - /** - * True if reference is a write location, false otherwise. - */ - isWriteAccess: boolean; - /** - * Present only if the search was triggered from a declaration. - * True indicates that the references refers to the same symbol - * (i.e. has the same meaning) as the declaration that began the - * search. - */ - isDefinition?: boolean; - } - /** - * The body of a "references" response message. - */ - interface ReferencesResponseBody { - /** - * The file locations referencing the symbol. - */ - refs: readonly ReferencesResponseItem[]; - /** - * The name of the symbol. - */ - symbolName: string; - /** - * The start character offset of the symbol (on the line provided by the references request). - */ - symbolStartOffset: number; - /** - * The full display name of the symbol. - */ - symbolDisplayString: string; - } - /** - * Response to "references" request. - */ - interface ReferencesResponse extends Response { - body?: ReferencesResponseBody; - } - interface FileReferencesRequest extends FileRequest { - command: CommandTypes.FileReferences; - } - interface FileReferencesResponseBody { - /** - * The file locations referencing the symbol. - */ - refs: readonly ReferencesResponseItem[]; - /** - * The name of the symbol. - */ - symbolName: string; - } - interface FileReferencesResponse extends Response { - body?: FileReferencesResponseBody; - } - /** - * Argument for RenameRequest request. - */ - interface RenameRequestArgs extends FileLocationRequestArgs { - /** - * Should text at specified location be found/changed in comments? - */ - findInComments?: boolean; - /** - * Should text at specified location be found/changed in strings? - */ - findInStrings?: boolean; - } - /** - * Rename request; value of command field is "rename". Return - * response giving the file locations that reference the symbol - * found in file at location line, col. Also return full display - * name of the symbol so that client can print it unambiguously. - */ - interface RenameRequest extends FileLocationRequest { - command: CommandTypes.Rename; - arguments: RenameRequestArgs; - } - /** - * Information about the item to be renamed. - */ - type RenameInfo = RenameInfoSuccess | RenameInfoFailure; - interface RenameInfoSuccess { - /** - * True if item can be renamed. - */ - canRename: true; - /** - * File or directory to rename. - * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. - */ - fileToRename?: string; - /** - * Display name of the item to be renamed. - */ - displayName: string; - /** - * Full display name of item to be renamed. - */ - fullDisplayName: string; - /** - * The items's kind (such as 'className' or 'parameterName' or plain 'text'). - */ - kind: ScriptElementKind; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers: string; - /** Span of text to rename. */ - triggerSpan: TextSpan; - } - interface RenameInfoFailure { - canRename: false; - /** - * Error message if item can not be renamed. - */ - localizedErrorMessage: string; - } - /** - * A group of text spans, all in 'file'. - */ - interface SpanGroup { - /** The file to which the spans apply */ - file: string; - /** The text spans in this group */ - locs: RenameTextSpan[]; - } - interface RenameTextSpan extends TextSpanWithContext { - readonly prefixText?: string; - readonly suffixText?: string; - } - interface RenameResponseBody { - /** - * Information about the item to be renamed. - */ - info: RenameInfo; - /** - * An array of span groups (one per file) that refer to the item to be renamed. - */ - locs: readonly SpanGroup[]; - } - /** - * Rename response message. - */ - interface RenameResponse extends Response { - body?: RenameResponseBody; - } - /** - * Represents a file in external project. - * External project is project whose set of files, compilation options and open\close state - * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). - * External project will exist even if all files in it are closed and should be closed explicitly. - * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will - * create configured project for every config file but will maintain a link that these projects were created - * as a result of opening external project so they should be removed once external project is closed. - */ - interface ExternalFile { - /** - * Name of file file - */ - fileName: string; - /** - * Script kind of the file - */ - scriptKind?: ScriptKindName | ScriptKind; - /** - * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) - */ - hasMixedContent?: boolean; - /** - * Content of the file - */ - content?: string; - } - /** - * Represent an external project - */ - interface ExternalProject { - /** - * Project name - */ - projectFileName: string; - /** - * List of root files in project - */ - rootFiles: ExternalFile[]; - /** - * Compiler options for the project - */ - options: ExternalProjectCompilerOptions; - /** - * Explicitly specified type acquisition for the project - */ - typeAcquisition?: TypeAcquisition; - } - interface CompileOnSaveMixin { - /** - * If compile on save is enabled for the project - */ - compileOnSave?: boolean; - } - /** - * For external projects, some of the project settings are sent together with - * compiler settings. - */ - type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin & WatchOptions; - interface FileWithProjectReferenceRedirectInfo { - /** - * Name of file - */ - fileName: string; - /** - * True if the file is primarily included in a referenced project - */ - isSourceOfProjectReferenceRedirect: boolean; - } - /** - * Represents a set of changes that happen in project - */ - interface ProjectChanges { - /** - * List of added files - */ - added: string[] | FileWithProjectReferenceRedirectInfo[]; - /** - * List of removed files - */ - removed: string[] | FileWithProjectReferenceRedirectInfo[]; - /** - * List of updated files - */ - updated: string[] | FileWithProjectReferenceRedirectInfo[]; - /** - * List of files that have had their project reference redirect status updated - * Only provided when the synchronizeProjectList request has includeProjectReferenceRedirectInfo set to true - */ - updatedRedirects?: FileWithProjectReferenceRedirectInfo[]; - } - /** - * Information found in a configure request. - */ - interface ConfigureRequestArguments { - /** - * Information about the host, for example 'Emacs 24.4' or - * 'Sublime Text version 3075' - */ - hostInfo?: string; - /** - * If present, tab settings apply only to this file. - */ - file?: string; - /** - * The format options to use during formatting and other code editing features. - */ - formatOptions?: FormatCodeSettings; - preferences?: UserPreferences; - /** - * The host's additional supported .js file extensions - */ - extraFileExtensions?: FileExtensionInfo[]; - watchOptions?: WatchOptions; - } - enum WatchFileKind { - FixedPollingInterval = "FixedPollingInterval", - PriorityPollingInterval = "PriorityPollingInterval", - DynamicPriorityPolling = "DynamicPriorityPolling", - FixedChunkSizePolling = "FixedChunkSizePolling", - UseFsEvents = "UseFsEvents", - UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory" - } - enum WatchDirectoryKind { - UseFsEvents = "UseFsEvents", - FixedPollingInterval = "FixedPollingInterval", - DynamicPriorityPolling = "DynamicPriorityPolling", - FixedChunkSizePolling = "FixedChunkSizePolling" - } - enum PollingWatchKind { - FixedInterval = "FixedInterval", - PriorityInterval = "PriorityInterval", - DynamicPriority = "DynamicPriority", - FixedChunkSize = "FixedChunkSize" - } - interface WatchOptions { - watchFile?: WatchFileKind | ts.WatchFileKind; - watchDirectory?: WatchDirectoryKind | ts.WatchDirectoryKind; - fallbackPolling?: PollingWatchKind | ts.PollingWatchKind; - synchronousWatchDirectory?: boolean; - excludeDirectories?: string[]; - excludeFiles?: string[]; - [option: string]: CompilerOptionsValue | undefined; - } - /** - * Configure request; value of command field is "configure". Specifies - * host information, such as host type, tab size, and indent size. - */ - interface ConfigureRequest extends Request { - command: CommandTypes.Configure; - arguments: ConfigureRequestArguments; - } - /** - * Response to "configure" request. This is just an acknowledgement, so - * no body field is required. - */ - interface ConfigureResponse extends Response { - } - interface ConfigurePluginRequestArguments { - pluginName: string; - configuration: any; - } - interface ConfigurePluginRequest extends Request { - command: CommandTypes.ConfigurePlugin; - arguments: ConfigurePluginRequestArguments; - } - interface ConfigurePluginResponse extends Response { - } - interface SelectionRangeRequest extends FileRequest { - command: CommandTypes.SelectionRange; - arguments: SelectionRangeRequestArgs; - } - interface SelectionRangeRequestArgs extends FileRequestArgs { - locations: Location[]; - } - interface SelectionRangeResponse extends Response { - body?: SelectionRange[]; - } - interface SelectionRange { - textSpan: TextSpan; - parent?: SelectionRange; - } - interface ToggleLineCommentRequest extends FileRequest { - command: CommandTypes.ToggleLineComment; - arguments: FileRangeRequestArgs; - } - interface ToggleMultilineCommentRequest extends FileRequest { - command: CommandTypes.ToggleMultilineComment; - arguments: FileRangeRequestArgs; - } - interface CommentSelectionRequest extends FileRequest { - command: CommandTypes.CommentSelection; - arguments: FileRangeRequestArgs; - } - interface UncommentSelectionRequest extends FileRequest { - command: CommandTypes.UncommentSelection; - arguments: FileRangeRequestArgs; - } - /** - * Information found in an "open" request. - */ - interface OpenRequestArgs extends FileRequestArgs { - /** - * Used when a version of the file content is known to be more up to date than the one on disk. - * Then the known content will be used upon opening instead of the disk copy - */ - fileContent?: string; - /** - * Used to specify the script kind of the file explicitly. It could be one of the following: - * "TS", "JS", "TSX", "JSX" - */ - scriptKindName?: ScriptKindName; - /** - * Used to limit the searching for project config file. If given the searching will stop at this - * root path; otherwise it will go all the way up to the dist root path. - */ - projectRootPath?: string; - } - type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; - /** - * Open request; value of command field is "open". Notify the - * server that the client has file open. The server will not - * monitor the filesystem for changes in this file and will assume - * that the client is updating the server (using the change and/or - * reload messages) when the file changes. Server does not currently - * send a response to an open request. - */ - interface OpenRequest extends Request { - command: CommandTypes.Open; - arguments: OpenRequestArgs; - } - /** - * Request to open or update external project - */ - interface OpenExternalProjectRequest extends Request { - command: CommandTypes.OpenExternalProject; - arguments: OpenExternalProjectArgs; - } - /** - * Arguments to OpenExternalProjectRequest request - */ - type OpenExternalProjectArgs = ExternalProject; - /** - * Request to open multiple external projects - */ - interface OpenExternalProjectsRequest extends Request { - command: CommandTypes.OpenExternalProjects; - arguments: OpenExternalProjectsArgs; - } - /** - * Arguments to OpenExternalProjectsRequest - */ - interface OpenExternalProjectsArgs { - /** - * List of external projects to open or update - */ - projects: ExternalProject[]; - } - /** - * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so - * no body field is required. - */ - interface OpenExternalProjectResponse extends Response { - } - /** - * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so - * no body field is required. - */ - interface OpenExternalProjectsResponse extends Response { - } - /** - * Request to close external project. - */ - interface CloseExternalProjectRequest extends Request { - command: CommandTypes.CloseExternalProject; - arguments: CloseExternalProjectRequestArgs; - } - /** - * Arguments to CloseExternalProjectRequest request - */ - interface CloseExternalProjectRequestArgs { - /** - * Name of the project to close - */ - projectFileName: string; - } - /** - * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so - * no body field is required. - */ - interface CloseExternalProjectResponse extends Response { - } - /** - * Request to synchronize list of open files with the client - */ - interface UpdateOpenRequest extends Request { - command: CommandTypes.UpdateOpen; - arguments: UpdateOpenRequestArgs; - } - /** - * Arguments to UpdateOpenRequest - */ - interface UpdateOpenRequestArgs { - /** - * List of newly open files - */ - openFiles?: OpenRequestArgs[]; - /** - * List of open files files that were changes - */ - changedFiles?: FileCodeEdits[]; - /** - * List of files that were closed - */ - closedFiles?: string[]; - } - /** - * External projects have a typeAcquisition option so they need to be added separately to compiler options for inferred projects. - */ - type InferredProjectCompilerOptions = ExternalProjectCompilerOptions & TypeAcquisition; - /** - * Request to set compiler options for inferred projects. - * External projects are opened / closed explicitly. - * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. - * This configuration file will be used to obtain a list of files and configuration settings for the project. - * Inferred projects are created when user opens a loose file that is not the part of external project - * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, - * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. - */ - interface SetCompilerOptionsForInferredProjectsRequest extends Request { - command: CommandTypes.CompilerOptionsForInferredProjects; - arguments: SetCompilerOptionsForInferredProjectsArgs; - } - /** - * Argument for SetCompilerOptionsForInferredProjectsRequest request. - */ - interface SetCompilerOptionsForInferredProjectsArgs { - /** - * Compiler options to be used with inferred projects. - */ - options: InferredProjectCompilerOptions; - /** - * Specifies the project root path used to scope compiler options. - * It is an error to provide this property if the server has not been started with - * `useInferredProjectPerProjectRoot` enabled. - */ - projectRootPath?: string; - } - /** - * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so - * no body field is required. - */ - interface SetCompilerOptionsForInferredProjectsResponse extends Response { - } - /** - * Exit request; value of command field is "exit". Ask the server process - * to exit. - */ - interface ExitRequest extends Request { - command: CommandTypes.Exit; - } - /** - * Close request; value of command field is "close". Notify the - * server that the client has closed a previously open file. If - * file is still referenced by open files, the server will resume - * monitoring the filesystem for changes to file. Server does not - * currently send a response to a close request. - */ - interface CloseRequest extends FileRequest { - command: CommandTypes.Close; - } - /** - * Request to obtain the list of files that should be regenerated if target file is recompiled. - * NOTE: this us query-only operation and does not generate any output on disk. - */ - interface CompileOnSaveAffectedFileListRequest extends FileRequest { - command: CommandTypes.CompileOnSaveAffectedFileList; - } - /** - * Contains a list of files that should be regenerated in a project - */ - interface CompileOnSaveAffectedFileListSingleProject { - /** - * Project name - */ - projectFileName: string; - /** - * List of files names that should be recompiled - */ - fileNames: string[]; - /** - * true if project uses outFile or out compiler option - */ - projectUsesOutFile: boolean; - } - /** - * Response for CompileOnSaveAffectedFileListRequest request; - */ - interface CompileOnSaveAffectedFileListResponse extends Response { - body: CompileOnSaveAffectedFileListSingleProject[]; - } - /** - * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. - */ - interface CompileOnSaveEmitFileRequest extends FileRequest { - command: CommandTypes.CompileOnSaveEmitFile; - arguments: CompileOnSaveEmitFileRequestArgs; - } - /** - * Arguments for CompileOnSaveEmitFileRequest - */ - interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { - /** - * if true - then file should be recompiled even if it does not have any changes. - */ - forced?: boolean; - includeLinePosition?: boolean; - /** if true - return response as object with emitSkipped and diagnostics */ - richResponse?: boolean; - } - interface CompileOnSaveEmitFileResponse extends Response { - body: boolean | EmitResult; - } - interface EmitResult { - emitSkipped: boolean; - diagnostics: Diagnostic[] | DiagnosticWithLinePosition[]; - } - /** - * Quickinfo request; value of command field is - * "quickinfo". Return response giving a quick type and - * documentation string for the symbol found in file at location - * line, col. - */ - interface QuickInfoRequest extends FileLocationRequest { - command: CommandTypes.Quickinfo; - arguments: FileLocationRequestArgs; - } - /** - * Body of QuickInfoResponse. - */ - interface QuickInfoResponseBody { - /** - * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). - */ - kind: ScriptElementKind; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers: string; - /** - * Starting file location of symbol. - */ - start: Location; - /** - * One past last character of symbol. - */ - end: Location; - /** - * Type and kind of symbol. - */ - displayString: string; - /** - * Documentation associated with symbol. - * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. - */ - documentation: string | SymbolDisplayPart[]; - /** - * JSDoc tags associated with symbol. - */ - tags: JSDocTagInfo[]; - } - /** - * Quickinfo response message. - */ - interface QuickInfoResponse extends Response { - body?: QuickInfoResponseBody; - } - /** - * Arguments for format messages. - */ - interface FormatRequestArgs extends FileLocationRequestArgs { - /** - * Last line of range for which to format text in file. - */ - endLine: number; - /** - * Character offset on last line of range for which to format text in file. - */ - endOffset: number; - /** - * Format options to be used. - */ - options?: FormatCodeSettings; - } - /** - * Format request; value of command field is "format". Return - * response giving zero or more edit instructions. The edit - * instructions will be sorted in file order. Applying the edit - * instructions in reverse to file will result in correctly - * reformatted text. - */ - interface FormatRequest extends FileLocationRequest { - command: CommandTypes.Format; - arguments: FormatRequestArgs; - } - /** - * Object found in response messages defining an editing - * instruction for a span of text in source code. The effect of - * this instruction is to replace the text starting at start and - * ending one character before end with newText. For an insertion, - * the text span is empty. For a deletion, newText is empty. - */ - interface CodeEdit { - /** - * First character of the text span to edit. - */ - start: Location; - /** - * One character past last character of the text span to edit. - */ - end: Location; - /** - * Replace the span defined above with this string (may be - * the empty string). - */ - newText: string; - } - interface FileCodeEdits { - fileName: string; - textChanges: CodeEdit[]; - } - interface CodeFixResponse extends Response { - /** The code actions that are available */ - body?: CodeFixAction[]; - } - interface CodeAction { - /** Description of the code action to display in the UI of the editor */ - description: string; - /** Text changes to apply to each file as part of the code action */ - changes: FileCodeEdits[]; - /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ - commands?: {}[]; - } - interface CombinedCodeActions { - changes: readonly FileCodeEdits[]; - commands?: readonly {}[]; - } - interface CodeFixAction extends CodeAction { - /** Short name to identify the fix, for use by telemetry. */ - fixName: string; - /** - * If present, one may call 'getCombinedCodeFix' with this fixId. - * This may be omitted to indicate that the code fix can't be applied in a group. - */ - fixId?: {}; - /** Should be present if and only if 'fixId' is. */ - fixAllDescription?: string; - } - /** - * Format and format on key response message. - */ - interface FormatResponse extends Response { - body?: CodeEdit[]; - } - /** - * Arguments for format on key messages. - */ - interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { - /** - * Key pressed (';', '\n', or '}'). - */ - key: string; - options?: FormatCodeSettings; - } - /** - * Format on key request; value of command field is - * "formatonkey". Given file location and key typed (as string), - * return response giving zero or more edit instructions. The - * edit instructions will be sorted in file order. Applying the - * edit instructions in reverse to file will result in correctly - * reformatted text. - */ - interface FormatOnKeyRequest extends FileLocationRequest { - command: CommandTypes.Formatonkey; - arguments: FormatOnKeyRequestArgs; - } - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; - enum CompletionTriggerKind { - /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ - Invoked = 1, - /** Completion was triggered by a trigger character. */ - TriggerCharacter = 2, - /** Completion was re-triggered as the current completion list is incomplete. */ - TriggerForIncompleteCompletions = 3 - } - /** - * Arguments for completions messages. - */ - interface CompletionsRequestArgs extends FileLocationRequestArgs { - /** - * Optional prefix to apply to possible completions. - */ - prefix?: string; - /** - * Character that was responsible for triggering completion. - * Should be `undefined` if a user manually requested completion. - */ - triggerCharacter?: CompletionsTriggerCharacter; - triggerKind?: CompletionTriggerKind; - /** - * @deprecated Use UserPreferences.includeCompletionsForModuleExports - */ - includeExternalModuleExports?: boolean; - /** - * @deprecated Use UserPreferences.includeCompletionsWithInsertText - */ - includeInsertTextCompletions?: boolean; - } - /** - * Completions request; value of command field is "completions". - * Given a file location (file, line, col) and a prefix (which may - * be the empty string), return the possible completions that - * begin with prefix. - */ - interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions | CommandTypes.CompletionInfo; - arguments: CompletionsRequestArgs; - } - /** - * Arguments for completion details request. - */ - interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { - /** - * Names of one or more entries for which to obtain details. - */ - entryNames: (string | CompletionEntryIdentifier)[]; - } - interface CompletionEntryIdentifier { - name: string; - source?: string; - data?: unknown; - } - /** - * Completion entry details request; value of command field is - * "completionEntryDetails". Given a file location (file, line, - * col) and an array of completion entry names return more - * detailed information for each completion entry. - */ - interface CompletionDetailsRequest extends FileLocationRequest { - command: CommandTypes.CompletionDetails; - arguments: CompletionDetailsRequestArgs; - } - /** - * Part of a symbol description. - */ - interface SymbolDisplayPart { - /** - * Text of an item describing the symbol. - */ - text: string; - /** - * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). - */ - kind: string; - } - /** A part of a symbol description that links from a jsdoc @link tag to a declaration */ - interface JSDocLinkDisplayPart extends SymbolDisplayPart { - /** The location of the declaration that the @link tag links to. */ - target: FileSpan; - } - /** - * An item found in a completion response. - */ - interface CompletionEntry { - /** - * The symbol's name. - */ - name: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: ScriptElementKind; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers?: string; - /** - * A string that is used for comparing completion items so that they can be ordered. This - * is often the same as the name but may be different in certain circumstances. - */ - sortText: string; - /** - * Text to insert instead of `name`. - * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, - * coupled with `replacementSpan` to replace a dotted access with a bracket access. - */ - insertText?: string; - /** - * A string that should be used when filtering a set of - * completion items. - */ - filterText?: string; - /** - * `insertText` should be interpreted as a snippet if true. - */ - isSnippet?: true; - /** - * An optional span that indicates the text to be replaced by this completion item. - * If present, this span should be used instead of the default one. - * It will be set if the required span differs from the one generated by the default replacement behavior. - */ - replacementSpan?: TextSpan; - /** - * Indicates whether commiting this completion entry will require additional code actions to be - * made to avoid errors. The CompletionEntryDetails will have these actions. - */ - hasAction?: true; - /** - * Identifier (not necessarily human-readable) identifying where this completion came from. - */ - source?: string; - /** - * Human-readable description of the `source`. - */ - sourceDisplay?: SymbolDisplayPart[]; - /** - * Additional details for the label. - */ - labelDetails?: CompletionEntryLabelDetails; - /** - * If true, this completion should be highlighted as recommended. There will only be one of these. - * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. - * Then either that enum/class or a namespace containing it will be the recommended symbol. - */ - isRecommended?: true; - /** - * If true, this completion was generated from traversing the name table of an unchecked JS file, - * and therefore may not be accurate. - */ - isFromUncheckedFile?: true; - /** - * If true, this completion was for an auto-import of a module not yet in the program, but listed - * in the project package.json. Used for telemetry reporting. - */ - isPackageJsonImport?: true; - /** - * If true, this completion was an auto-import-style completion of an import statement (i.e., the - * module specifier was inserted along with the imported identifier). Used for telemetry reporting. - */ - isImportStatementCompletion?: true; - /** - * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, - * that allows TS Server to look up the symbol represented by the completion item, disambiguating - * items with the same name. - */ - data?: unknown; - } - interface CompletionEntryLabelDetails { - /** - * An optional string which is rendered less prominently directly after - * {@link CompletionEntry.name name}, without any spacing. Should be - * used for function signatures or type annotations. - */ - detail?: string; - /** - * An optional string which is rendered less prominently after - * {@link CompletionEntryLabelDetails.detail}. Should be used for fully qualified - * names or file path. - */ - description?: string; - } - /** - * Additional completion entry details, available on demand - */ - interface CompletionEntryDetails { - /** - * The symbol's name. - */ - name: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: ScriptElementKind; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers: string; - /** - * Display parts of the symbol (similar to quick info). - */ - displayParts: SymbolDisplayPart[]; - /** - * Documentation strings for the symbol. - */ - documentation?: SymbolDisplayPart[]; - /** - * JSDoc tags for the symbol. - */ - tags?: JSDocTagInfo[]; - /** - * The associated code actions for this entry - */ - codeActions?: CodeAction[]; - /** - * @deprecated Use `sourceDisplay` instead. - */ - source?: SymbolDisplayPart[]; - /** - * Human-readable description of the `source` from the CompletionEntry. - */ - sourceDisplay?: SymbolDisplayPart[]; - } - /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ - interface CompletionsResponse extends Response { - body?: CompletionEntry[]; - } - interface CompletionInfoResponse extends Response { - body?: CompletionInfo; - } - interface CompletionInfo { - readonly flags?: number; - readonly isGlobalCompletion: boolean; - readonly isMemberCompletion: boolean; - readonly isNewIdentifierLocation: boolean; - /** - * In the absence of `CompletionEntry["replacementSpan"]`, the editor may choose whether to use - * this span or its default one. If `CompletionEntry["replacementSpan"]` is defined, that span - * must be used to commit that completion entry. - */ - readonly optionalReplacementSpan?: TextSpan; - readonly isIncomplete?: boolean; - readonly entries: readonly CompletionEntry[]; - } - interface CompletionDetailsResponse extends Response { - body?: CompletionEntryDetails[]; - } - /** - * Signature help information for a single parameter - */ - interface SignatureHelpParameter { - /** - * The parameter's name - */ - name: string; - /** - * Documentation of the parameter. - */ - documentation: SymbolDisplayPart[]; - /** - * Display parts of the parameter. - */ - displayParts: SymbolDisplayPart[]; - /** - * Whether the parameter is optional or not. - */ - isOptional: boolean; - } - /** - * Represents a single signature to show in signature help. - */ - interface SignatureHelpItem { - /** - * Whether the signature accepts a variable number of arguments. - */ - isVariadic: boolean; - /** - * The prefix display parts. - */ - prefixDisplayParts: SymbolDisplayPart[]; - /** - * The suffix display parts. - */ - suffixDisplayParts: SymbolDisplayPart[]; - /** - * The separator display parts. - */ - separatorDisplayParts: SymbolDisplayPart[]; - /** - * The signature helps items for the parameters. - */ - parameters: SignatureHelpParameter[]; - /** - * The signature's documentation - */ - documentation: SymbolDisplayPart[]; - /** - * The signature's JSDoc tags - */ - tags: JSDocTagInfo[]; - } - /** - * Signature help items found in the response of a signature help request. - */ - interface SignatureHelpItems { - /** - * The signature help items. - */ - items: SignatureHelpItem[]; - /** - * The span for which signature help should appear on a signature - */ - applicableSpan: TextSpan; - /** - * The item selected in the set of available help items. - */ - selectedItemIndex: number; - /** - * The argument selected in the set of parameters. - */ - argumentIndex: number; - /** - * The argument count - */ - argumentCount: number; - } - type SignatureHelpTriggerCharacter = "," | "(" | "<"; - type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; - /** - * Arguments of a signature help request. - */ - interface SignatureHelpRequestArgs extends FileLocationRequestArgs { - /** - * Reason why signature help was invoked. - * See each individual possible - */ - triggerReason?: SignatureHelpTriggerReason; - } - type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; - /** - * Signals that the user manually requested signature help. - * The language service will unconditionally attempt to provide a result. - */ - interface SignatureHelpInvokedReason { - kind: "invoked"; - triggerCharacter?: undefined; - } - /** - * Signals that the signature help request came from a user typing a character. - * Depending on the character and the syntactic context, the request may or may not be served a result. - */ - interface SignatureHelpCharacterTypedReason { - kind: "characterTyped"; - /** - * Character that was responsible for triggering signature help. - */ - triggerCharacter: SignatureHelpTriggerCharacter; - } - /** - * Signals that this signature help request came from typing a character or moving the cursor. - * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. - * The language service will unconditionally attempt to provide a result. - * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. - */ - interface SignatureHelpRetriggeredReason { - kind: "retrigger"; - /** - * Character that was responsible for triggering signature help. - */ - triggerCharacter?: SignatureHelpRetriggerCharacter; - } - /** - * Signature help request; value of command field is "signatureHelp". - * Given a file location (file, line, col), return the signature - * help. - */ - interface SignatureHelpRequest extends FileLocationRequest { - command: CommandTypes.SignatureHelp; - arguments: SignatureHelpRequestArgs; - } - /** - * Response object for a SignatureHelpRequest. - */ - interface SignatureHelpResponse extends Response { - body?: SignatureHelpItems; - } - type InlayHintKind = "Type" | "Parameter" | "Enum"; - interface InlayHintsRequestArgs extends FileRequestArgs { - /** - * Start position of the span. - */ - start: number; - /** - * Length of the span. - */ - length: number; - } - interface InlayHintsRequest extends Request { - command: CommandTypes.ProvideInlayHints; - arguments: InlayHintsRequestArgs; - } - interface InlayHintItem { - /** This property will be the empty string when displayParts is set. */ - text: string; - position: Location; - kind: InlayHintKind; - whitespaceBefore?: boolean; - whitespaceAfter?: boolean; - displayParts?: InlayHintItemDisplayPart[]; - } - interface InlayHintItemDisplayPart { - text: string; - span?: FileSpan; - } - interface InlayHintsResponse extends Response { - body?: InlayHintItem[]; - } - /** - * Synchronous request for semantic diagnostics of one file. - */ - interface SemanticDiagnosticsSyncRequest extends FileRequest { - command: CommandTypes.SemanticDiagnosticsSync; - arguments: SemanticDiagnosticsSyncRequestArgs; - } - interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { - includeLinePosition?: boolean; - } - /** - * Response object for synchronous sematic diagnostics request. - */ - interface SemanticDiagnosticsSyncResponse extends Response { - body?: Diagnostic[] | DiagnosticWithLinePosition[]; - } - interface SuggestionDiagnosticsSyncRequest extends FileRequest { - command: CommandTypes.SuggestionDiagnosticsSync; - arguments: SuggestionDiagnosticsSyncRequestArgs; - } - type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; - type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; - /** - * Synchronous request for syntactic diagnostics of one file. - */ - interface SyntacticDiagnosticsSyncRequest extends FileRequest { - command: CommandTypes.SyntacticDiagnosticsSync; - arguments: SyntacticDiagnosticsSyncRequestArgs; - } - interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { - includeLinePosition?: boolean; - } - /** - * Response object for synchronous syntactic diagnostics request. - */ - interface SyntacticDiagnosticsSyncResponse extends Response { - body?: Diagnostic[] | DiagnosticWithLinePosition[]; - } - /** - * Arguments for GeterrForProject request. - */ - interface GeterrForProjectRequestArgs { - /** - * the file requesting project error list - */ - file: string; - /** - * Delay in milliseconds to wait before starting to compute - * errors for the files in the file list - */ - delay: number; - } - /** - * GeterrForProjectRequest request; value of command field is - * "geterrForProject". It works similarly with 'Geterr', only - * it request for every file in this project. - */ - interface GeterrForProjectRequest extends Request { - command: CommandTypes.GeterrForProject; - arguments: GeterrForProjectRequestArgs; - } - /** - * Arguments for geterr messages. - */ - interface GeterrRequestArgs { - /** - * List of file names for which to compute compiler errors. - * The files will be checked in list order. - */ - files: string[]; - /** - * Delay in milliseconds to wait before starting to compute - * errors for the files in the file list - */ - delay: number; - } - /** - * Geterr request; value of command field is "geterr". Wait for - * delay milliseconds and then, if during the wait no change or - * reload messages have arrived for the first file in the files - * list, get the syntactic errors for the file, field requests, - * and then get the semantic errors for the file. Repeat with a - * smaller delay for each subsequent file on the files list. Best - * practice for an editor is to send a file list containing each - * file that is currently visible, in most-recently-used order. - */ - interface GeterrRequest extends Request { - command: CommandTypes.Geterr; - arguments: GeterrRequestArgs; - } - type RequestCompletedEventName = "requestCompleted"; - /** - * Event that is sent when server have finished processing request with specified id. - */ - interface RequestCompletedEvent extends Event { - event: RequestCompletedEventName; - body: RequestCompletedEventBody; - } - interface RequestCompletedEventBody { - request_seq: number; - } - /** - * Item of diagnostic information found in a DiagnosticEvent message. - */ - interface Diagnostic { - /** - * Starting file location at which text applies. - */ - start: Location; - /** - * The last file location at which the text applies. - */ - end: Location; - /** - * Text of diagnostic message. - */ - text: string; - /** - * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". - */ - category: string; - reportsUnnecessary?: {}; - reportsDeprecated?: {}; - /** - * Any related spans the diagnostic may have, such as other locations relevant to an error, such as declarartion sites - */ - relatedInformation?: DiagnosticRelatedInformation[]; - /** - * The error code of the diagnostic message. - */ - code?: number; - /** - * The name of the plugin reporting the message. - */ - source?: string; - } - interface DiagnosticWithFileName extends Diagnostic { - /** - * Name of the file the diagnostic is in - */ - fileName: string; - } - /** - * Represents additional spans returned with a diagnostic which are relevant to it - */ - interface DiagnosticRelatedInformation { - /** - * The category of the related information message, e.g. "error", "warning", or "suggestion". - */ - category: string; - /** - * The code used ot identify the related information - */ - code: number; - /** - * Text of related or additional information. - */ - message: string; - /** - * Associated location - */ - span?: FileSpan; - } - interface DiagnosticEventBody { - /** - * The file for which diagnostic information is reported. - */ - file: string; - /** - * An array of diagnostic information items. - */ - diagnostics: Diagnostic[]; - } - type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; - /** - * Event message for DiagnosticEventKind event types. - * These events provide syntactic and semantic errors for a file. - */ - interface DiagnosticEvent extends Event { - body?: DiagnosticEventBody; - event: DiagnosticEventKind; - } - interface ConfigFileDiagnosticEventBody { - /** - * The file which trigged the searching and error-checking of the config file - */ - triggerFile: string; - /** - * The name of the found config file. - */ - configFile: string; - /** - * An arry of diagnostic information items for the found config file. - */ - diagnostics: DiagnosticWithFileName[]; - } - /** - * Event message for "configFileDiag" event type. - * This event provides errors for a found config file. - */ - interface ConfigFileDiagnosticEvent extends Event { - body?: ConfigFileDiagnosticEventBody; - event: "configFileDiag"; - } - type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; - interface ProjectLanguageServiceStateEvent extends Event { - event: ProjectLanguageServiceStateEventName; - body?: ProjectLanguageServiceStateEventBody; - } - interface ProjectLanguageServiceStateEventBody { - /** - * Project name that has changes in the state of language service. - * For configured projects this will be the config file path. - * For external projects this will be the name of the projects specified when project was open. - * For inferred projects this event is not raised. - */ - projectName: string; - /** - * True if language service state switched from disabled to enabled - * and false otherwise. - */ - languageServiceEnabled: boolean; - } - type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; - interface ProjectsUpdatedInBackgroundEvent extends Event { - event: ProjectsUpdatedInBackgroundEventName; - body: ProjectsUpdatedInBackgroundEventBody; - } - interface ProjectsUpdatedInBackgroundEventBody { - /** - * Current set of open files - */ - openFiles: string[]; - } - type ProjectLoadingStartEventName = "projectLoadingStart"; - interface ProjectLoadingStartEvent extends Event { - event: ProjectLoadingStartEventName; - body: ProjectLoadingStartEventBody; - } - interface ProjectLoadingStartEventBody { - /** name of the project */ - projectName: string; - /** reason for loading */ - reason: string; - } - type ProjectLoadingFinishEventName = "projectLoadingFinish"; - interface ProjectLoadingFinishEvent extends Event { - event: ProjectLoadingFinishEventName; - body: ProjectLoadingFinishEventBody; - } - interface ProjectLoadingFinishEventBody { - /** name of the project */ - projectName: string; - } - type SurveyReadyEventName = "surveyReady"; - interface SurveyReadyEvent extends Event { - event: SurveyReadyEventName; - body: SurveyReadyEventBody; - } - interface SurveyReadyEventBody { - /** Name of the survey. This is an internal machine- and programmer-friendly name */ - surveyId: string; - } - type LargeFileReferencedEventName = "largeFileReferenced"; - interface LargeFileReferencedEvent extends Event { - event: LargeFileReferencedEventName; - body: LargeFileReferencedEventBody; - } - interface LargeFileReferencedEventBody { - /** - * name of the large file being loaded - */ - file: string; - /** - * size of the file - */ - fileSize: number; - /** - * max file size allowed on the server - */ - maxFileSize: number; - } - /** - * Arguments for reload request. - */ - interface ReloadRequestArgs extends FileRequestArgs { - /** - * Name of temporary file from which to reload file - * contents. May be same as file. - */ - tmpfile: string; - } - /** - * Reload request message; value of command field is "reload". - * Reload contents of file with name given by the 'file' argument - * from temporary file with name given by the 'tmpfile' argument. - * The two names can be identical. - */ - interface ReloadRequest extends FileRequest { - command: CommandTypes.Reload; - arguments: ReloadRequestArgs; - } - /** - * Response to "reload" request. This is just an acknowledgement, so - * no body field is required. - */ - interface ReloadResponse extends Response { - } - /** - * Arguments for saveto request. - */ - interface SavetoRequestArgs extends FileRequestArgs { - /** - * Name of temporary file into which to save server's view of - * file contents. - */ - tmpfile: string; - } - /** - * Saveto request message; value of command field is "saveto". - * For debugging purposes, save to a temporaryfile (named by - * argument 'tmpfile') the contents of file named by argument - * 'file'. The server does not currently send a response to a - * "saveto" request. - */ - interface SavetoRequest extends FileRequest { - command: CommandTypes.Saveto; - arguments: SavetoRequestArgs; - } - /** - * Arguments for navto request message. - */ - interface NavtoRequestArgs { - /** - * Search term to navigate to from current location; term can - * be '.*' or an identifier prefix. - */ - searchValue: string; - /** - * Optional limit on the number of items to return. - */ - maxResultCount?: number; - /** - * The file for the request (absolute pathname required). - */ - file?: string; - /** - * Optional flag to indicate we want results for just the current file - * or the entire project. - */ - currentFileOnly?: boolean; - projectFileName?: string; - } - /** - * Navto request message; value of command field is "navto". - * Return list of objects giving file locations and symbols that - * match the search term given in argument 'searchTerm'. The - * context for the search is given by the named file. - */ - interface NavtoRequest extends Request { - command: CommandTypes.Navto; - arguments: NavtoRequestArgs; - } - /** - * An item found in a navto response. - */ - interface NavtoItem extends FileSpan { - /** - * The symbol's name. - */ - name: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: ScriptElementKind; - /** - * exact, substring, or prefix. - */ - matchKind: string; - /** - * If this was a case sensitive or insensitive match. - */ - isCaseSensitive: boolean; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers?: string; - /** - * Name of symbol's container symbol (if any); for example, - * the class name if symbol is a class member. - */ - containerName?: string; - /** - * Kind of symbol's container symbol (if any). - */ - containerKind?: ScriptElementKind; - } - /** - * Navto response message. Body is an array of navto items. Each - * item gives a symbol that matched the search term. - */ - interface NavtoResponse extends Response { - body?: NavtoItem[]; - } - /** - * Arguments for change request message. - */ - interface ChangeRequestArgs extends FormatRequestArgs { - /** - * Optional string to insert at location (file, line, offset). - */ - insertString?: string; - } - /** - * Change request message; value of command field is "change". - * Update the server's view of the file named by argument 'file'. - * Server does not currently send a response to a change request. - */ - interface ChangeRequest extends FileLocationRequest { - command: CommandTypes.Change; - arguments: ChangeRequestArgs; - } - /** - * Response to "brace" request. - */ - interface BraceResponse extends Response { - body?: TextSpan[]; - } - /** - * Brace matching request; value of command field is "brace". - * Return response giving the file locations of matching braces - * found in file at location line, offset. - */ - interface BraceRequest extends FileLocationRequest { - command: CommandTypes.Brace; - } - /** - * NavBar items request; value of command field is "navbar". - * Return response giving the list of navigation bar entries - * extracted from the requested file. - */ - interface NavBarRequest extends FileRequest { - command: CommandTypes.NavBar; - } - /** - * NavTree request; value of command field is "navtree". - * Return response giving the navigation tree of the requested file. - */ - interface NavTreeRequest extends FileRequest { - command: CommandTypes.NavTree; - } - interface NavigationBarItem { - /** - * The item's display text. - */ - text: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: ScriptElementKind; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers?: string; - /** - * The definition locations of the item. - */ - spans: TextSpan[]; - /** - * Optional children. - */ - childItems?: NavigationBarItem[]; - /** - * Number of levels deep this item should appear. - */ - indent: number; - } - /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ - interface NavigationTree { - text: string; - kind: ScriptElementKind; - kindModifiers: string; - spans: TextSpan[]; - nameSpan: TextSpan | undefined; - childItems?: NavigationTree[]; - } - type TelemetryEventName = "telemetry"; - interface TelemetryEvent extends Event { - event: TelemetryEventName; - body: TelemetryEventBody; - } - interface TelemetryEventBody { - telemetryEventName: string; - payload: any; - } - type TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; - interface TypesInstallerInitializationFailedEvent extends Event { - event: TypesInstallerInitializationFailedEventName; - body: TypesInstallerInitializationFailedEventBody; - } - interface TypesInstallerInitializationFailedEventBody { - message: string; - } - type TypingsInstalledTelemetryEventName = "typingsInstalled"; - interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { - telemetryEventName: TypingsInstalledTelemetryEventName; - payload: TypingsInstalledTelemetryEventPayload; - } - interface TypingsInstalledTelemetryEventPayload { - /** - * Comma separated list of installed typing packages - */ - installedPackages: string; - /** - * true if install request succeeded, otherwise - false - */ - installSuccess: boolean; - /** - * version of typings installer - */ - typingsInstallerVersion: string; - } - type BeginInstallTypesEventName = "beginInstallTypes"; - type EndInstallTypesEventName = "endInstallTypes"; - interface BeginInstallTypesEvent extends Event { - event: BeginInstallTypesEventName; - body: BeginInstallTypesEventBody; - } - interface EndInstallTypesEvent extends Event { - event: EndInstallTypesEventName; - body: EndInstallTypesEventBody; - } - interface InstallTypesEventBody { - /** - * correlation id to match begin and end events - */ - eventId: number; - /** - * list of packages to install - */ - packages: readonly string[]; - } - interface BeginInstallTypesEventBody extends InstallTypesEventBody { - } - interface EndInstallTypesEventBody extends InstallTypesEventBody { - /** - * true if installation succeeded, otherwise false - */ - success: boolean; - } - interface NavBarResponse extends Response { - body?: NavigationBarItem[]; - } - interface NavTreeResponse extends Response { - body?: NavigationTree; - } - interface CallHierarchyItem { - name: string; - kind: ScriptElementKind; - kindModifiers?: string; - file: string; - span: TextSpan; - selectionSpan: TextSpan; - containerName?: string; - } - interface CallHierarchyIncomingCall { - from: CallHierarchyItem; - fromSpans: TextSpan[]; - } - interface CallHierarchyOutgoingCall { - to: CallHierarchyItem; - fromSpans: TextSpan[]; - } - interface PrepareCallHierarchyRequest extends FileLocationRequest { - command: CommandTypes.PrepareCallHierarchy; - } - interface PrepareCallHierarchyResponse extends Response { - readonly body: CallHierarchyItem | CallHierarchyItem[]; - } - interface ProvideCallHierarchyIncomingCallsRequest extends FileLocationRequest { - command: CommandTypes.ProvideCallHierarchyIncomingCalls; - } - interface ProvideCallHierarchyIncomingCallsResponse extends Response { - readonly body: CallHierarchyIncomingCall[]; - } - interface ProvideCallHierarchyOutgoingCallsRequest extends FileLocationRequest { - command: CommandTypes.ProvideCallHierarchyOutgoingCalls; - } - interface ProvideCallHierarchyOutgoingCallsResponse extends Response { - readonly body: CallHierarchyOutgoingCall[]; - } - enum IndentStyle { - None = "None", - Block = "Block", - Smart = "Smart" - } - enum SemicolonPreference { - Ignore = "ignore", - Insert = "insert", - Remove = "remove" - } - interface EditorSettings { - baseIndentSize?: number; - indentSize?: number; - tabSize?: number; - newLineCharacter?: string; - convertTabsToSpaces?: boolean; - indentStyle?: IndentStyle | ts.IndentStyle; - trimTrailingWhitespace?: boolean; - } - interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter?: boolean; - insertSpaceAfterSemicolonInForStatements?: boolean; - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - insertSpaceAfterConstructor?: boolean; - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - insertSpaceAfterOpeningAndBeforeClosingEmptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - insertSpaceAfterTypeAssertion?: boolean; - insertSpaceBeforeFunctionParenthesis?: boolean; - placeOpenBraceOnNewLineForFunctions?: boolean; - placeOpenBraceOnNewLineForControlBlocks?: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - semicolons?: SemicolonPreference; - indentSwitchCase?: boolean; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "auto" | "double" | "single"; - /** - * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. - * This affects lone identifier completions but not completions on the right hand side of `obj.`. - */ - readonly includeCompletionsForModuleExports?: boolean; - /** - * Enables auto-import-style completions on partially-typed import statements. E.g., allows - * `import write|` to be completed to `import { writeFile } from "fs"`. - */ - readonly includeCompletionsForImportStatements?: boolean; - /** - * Allows completions to be formatted with snippet text, indicated by `CompletionItem["isSnippet"]`. - */ - readonly includeCompletionsWithSnippetText?: boolean; - /** - * If enabled, the completion list will include completions with invalid identifier names. - * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. - */ - readonly includeCompletionsWithInsertText?: boolean; - /** - * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, - * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined - * values, with insertion text to replace preceding `.` tokens with `?.`. - */ - readonly includeAutomaticOptionalChainCompletions?: boolean; - /** - * If enabled, completions for class members (e.g. methods and properties) will include - * a whole declaration for the member. - * E.g., `class A { f| }` could be completed to `class A { foo(): number {} }`, instead of - * `class A { foo }`. - */ - readonly includeCompletionsWithClassMemberSnippets?: boolean; - /** - * If enabled, object literal methods will have a method declaration completion entry in addition - * to the regular completion entry containing just the method name. - * E.g., `const objectLiteral: T = { f| }` could be completed to `const objectLiteral: T = { foo(): void {} }`, - * in addition to `const objectLiteral: T = { foo }`. - */ - readonly includeCompletionsWithObjectLiteralMethodSnippets?: boolean; - /** - * Indicates whether {@link CompletionEntry.labelDetails completion entry label details} are supported. - * If not, contents of `labelDetails` may be included in the {@link CompletionEntry.name} property. - */ - readonly useLabelDetailsInCompletionEntries?: boolean; - readonly allowIncompleteCompletions?: boolean; - readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; - /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ - readonly importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js"; - readonly allowTextChangesInNewFiles?: boolean; - readonly lazyConfiguredProjectsFromExternalProject?: boolean; - readonly providePrefixAndSuffixTextForRename?: boolean; - readonly provideRefactorNotApplicableReason?: boolean; - readonly allowRenameOfImportPath?: boolean; - readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; - readonly jsxAttributeCompletionStyle?: "auto" | "braces" | "none"; - readonly displayPartsForJSDoc?: boolean; - readonly generateReturnInDocTemplate?: boolean; - readonly includeInlayParameterNameHints?: "none" | "literals" | "all"; - readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; - readonly includeInlayFunctionParameterTypeHints?: boolean; - readonly includeInlayVariableTypeHints?: boolean; - readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; - readonly includeInlayPropertyDeclarationTypeHints?: boolean; - readonly includeInlayFunctionLikeReturnTypeHints?: boolean; - readonly includeInlayEnumMemberValueHints?: boolean; - readonly interactiveInlayHints?: boolean; - readonly autoImportFileExcludePatterns?: string[]; - /** - * Indicates whether imports should be organized in a case-insensitive manner. - */ - readonly organizeImportsIgnoreCase?: "auto" | boolean; - /** - * Indicates whether imports should be organized via an "ordinal" (binary) comparison using the numeric value - * of their code points, or via "unicode" collation (via the - * [Unicode Collation Algorithm](https://unicode.org/reports/tr10/#Scope)) using rules associated with the locale - * specified in {@link organizeImportsCollationLocale}. - * - * Default: `"ordinal"`. - */ - readonly organizeImportsCollation?: "ordinal" | "unicode"; - /** - * Indicates the locale to use for "unicode" collation. If not specified, the locale `"en"` is used as an invariant - * for the sake of consistent sorting. Use `"auto"` to use the detected UI locale. - * - * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. - * - * Default: `"en"` - */ - readonly organizeImportsCollationLocale?: string; - /** - * Indicates whether numeric collation should be used for digit sequences in strings. When `true`, will collate - * strings such that `a1z < a2z < a100z`. When `false`, will collate strings such that `a1z < a100z < a2z`. - * - * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. - * - * Default: `false` - */ - readonly organizeImportsNumericCollation?: boolean; - /** - * Indicates whether accents and other diacritic marks are considered unequal for the purpose of collation. When - * `true`, characters with accents and other diacritics will be collated in the order defined by the locale specified - * in {@link organizeImportsCollationLocale}. - * - * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. - * - * Default: `true` - */ - readonly organizeImportsAccentCollation?: boolean; - /** - * Indicates whether upper case or lower case should sort first. When `false`, the default order for the locale - * specified in {@link organizeImportsCollationLocale} is used. - * - * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. This preference is also - * ignored if we are using case-insensitive sorting, which occurs when {@link organizeImportsIgnoreCase} is `true`, - * or if {@link organizeImportsIgnoreCase} is `"auto"` and the auto-detected case sensitivity is determined to be - * case-insensitive. - * - * Default: `false` - */ - readonly organizeImportsCaseFirst?: "upper" | "lower" | false; - /** - * Indicates whether {@link ReferencesResponseItem.lineText} is supported. - */ - readonly disableLineTextInReferences?: boolean; - } - interface CompilerOptions { - allowJs?: boolean; - allowSyntheticDefaultImports?: boolean; - allowUnreachableCode?: boolean; - allowUnusedLabels?: boolean; - alwaysStrict?: boolean; - baseUrl?: string; - charset?: string; - checkJs?: boolean; - declaration?: boolean; - declarationDir?: string; - disableSizeLimit?: boolean; - downlevelIteration?: boolean; - emitBOM?: boolean; - emitDecoratorMetadata?: boolean; - experimentalDecorators?: boolean; - forceConsistentCasingInFileNames?: boolean; - importHelpers?: boolean; - inlineSourceMap?: boolean; - inlineSources?: boolean; - isolatedModules?: boolean; - jsx?: JsxEmit | ts.JsxEmit; - lib?: string[]; - locale?: string; - mapRoot?: string; - maxNodeModuleJsDepth?: number; - module?: ModuleKind | ts.ModuleKind; - moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; - newLine?: NewLineKind | ts.NewLineKind; - noEmit?: boolean; - noEmitHelpers?: boolean; - noEmitOnError?: boolean; - noErrorTruncation?: boolean; - noFallthroughCasesInSwitch?: boolean; - noImplicitAny?: boolean; - noImplicitReturns?: boolean; - noImplicitThis?: boolean; - noUnusedLocals?: boolean; - noUnusedParameters?: boolean; - noImplicitUseStrict?: boolean; - noLib?: boolean; - noResolve?: boolean; - out?: string; - outDir?: string; - outFile?: string; - paths?: MapLike; - plugins?: PluginImport[]; - preserveConstEnums?: boolean; - preserveSymlinks?: boolean; - project?: string; - reactNamespace?: string; - removeComments?: boolean; - references?: ProjectReference[]; - rootDir?: string; - rootDirs?: string[]; - skipLibCheck?: boolean; - skipDefaultLibCheck?: boolean; - sourceMap?: boolean; - sourceRoot?: string; - strict?: boolean; - strictNullChecks?: boolean; - suppressExcessPropertyErrors?: boolean; - suppressImplicitAnyIndexErrors?: boolean; - useDefineForClassFields?: boolean; - target?: ScriptTarget | ts.ScriptTarget; - traceResolution?: boolean; - resolveJsonModule?: boolean; - types?: string[]; - /** Paths used to used to compute primary types search locations */ - typeRoots?: string[]; - [option: string]: CompilerOptionsValue | undefined; - } - enum JsxEmit { - None = "None", - Preserve = "Preserve", - ReactNative = "ReactNative", - React = "React" - } - enum ModuleKind { - None = "None", - CommonJS = "CommonJS", - AMD = "AMD", - UMD = "UMD", - System = "System", - ES6 = "ES6", - ES2015 = "ES2015", - ESNext = "ESNext" - } - enum ModuleResolutionKind { - Classic = "Classic", - Node = "Node" - } - enum NewLineKind { - Crlf = "Crlf", - Lf = "Lf" - } - enum ScriptTarget { - ES3 = "ES3", - ES5 = "ES5", - ES6 = "ES6", - ES2015 = "ES2015", - ES2016 = "ES2016", - ES2017 = "ES2017", - ES2018 = "ES2018", - ES2019 = "ES2019", - ES2020 = "ES2020", - ES2021 = "ES2021", - ES2022 = "ES2022", - ESNext = "ESNext" - } - enum ClassificationType { - comment = 1, - identifier = 2, - keyword = 3, - numericLiteral = 4, - operator = 5, - stringLiteral = 6, - regularExpressionLiteral = 7, - whiteSpace = 8, - text = 9, - punctuation = 10, - className = 11, - enumName = 12, - interfaceName = 13, - moduleName = 14, - typeParameterName = 15, - typeAliasName = 16, - parameterName = 17, - docCommentTagName = 18, - jsxOpenTagName = 19, - jsxCloseTagName = 20, - jsxSelfClosingTagName = 21, - jsxAttribute = 22, - jsxText = 23, - jsxAttributeStringLiteralValue = 24, - bigintLiteral = 25 - } - } - namespace typingsInstaller { - interface Log { - isEnabled(): boolean; - writeLine(text: string): void; - } - type RequestCompletedAction = (success: boolean) => void; - interface PendingRequest { - requestId: number; - packageNames: string[]; - cwd: string; - onRequestCompleted: RequestCompletedAction; - } - abstract class TypingsInstaller { - protected readonly installTypingHost: InstallTypingHost; - private readonly globalCachePath; - private readonly safeListPath; - private readonly typesMapLocation; - private readonly throttleLimit; - protected readonly log: Log; - private readonly packageNameToTypingLocation; - private readonly missingTypingsSet; - private readonly knownCachesSet; - private readonly projectWatchers; - private safeList; - private installRunCount; - private inFlightRequestCount; - abstract readonly typesRegistry: Map>; - constructor(installTypingHost: InstallTypingHost, globalCachePath: string, safeListPath: Path, typesMapLocation: Path, throttleLimit: number, log?: Log); - closeProject(req: CloseProject): void; - private closeWatchers; - install(req: DiscoverTypings): void; - private initializeSafeList; - private processCacheLocation; - private filterTypings; - protected ensurePackageDirectoryExists(directory: string): void; - private installTypings; - private ensureDirectoryExists; - private watchFiles; - private createSetTypings; - private installTypingsAsync; - private executeWithThrottling; - protected abstract installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void; - protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | WatchTypingLocations): void; - protected readonly latestDistTag = "latest"; - } - } - interface CompressedData { - length: number; - compressionKind: string; - data: any; - } - type ModuleImportResult = { - module: {}; - error: undefined; - } | { - module: undefined; - error: { - stack?: string; - message?: string; - }; - }; - /** @deprecated Use {@link ModuleImportResult} instead. */ - type RequireResult = ModuleImportResult; - interface ServerHost extends System { - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; - setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - clearTimeout(timeoutId: any): void; - setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; - clearImmediate(timeoutId: any): void; - gc?(): void; - trace?(s: string): void; - require?(initialPath: string, moduleName: string): ModuleImportResult; - } - function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings; - function toNormalizedPath(fileName: string): NormalizedPath; - function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; - function asNormalizedPath(fileName: string): NormalizedPath; - function createNormalizedPathMap(): NormalizedPathMap; - function isInferredProjectName(name: string): boolean; - function makeInferredProjectName(counter: number): string; - function createSortedArray(): SortedArray; - enum LogLevel { - terse = 0, - normal = 1, - requestTime = 2, - verbose = 3 - } - const emptyArray: SortedReadonlyArray; - interface Logger { - close(): void; - hasLevel(level: LogLevel): boolean; - loggingEnabled(): boolean; - perftrc(s: string): void; - info(s: string): void; - startGroup(): void; - endGroup(): void; - msg(s: string, type?: Msg): void; - getLogFileName(): string | undefined; - } - enum Msg { - Err = "Err", - Info = "Info", - Perf = "Perf" - } - namespace Errors { - function ThrowNoProject(): never; - function ThrowProjectLanguageServiceDisabled(): never; - function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; - } - type NormalizedPath = string & { - __normalizedPathTag: any; - }; - interface NormalizedPathMap { - get(path: NormalizedPath): T | undefined; - set(path: NormalizedPath, value: T): void; - contains(path: NormalizedPath): boolean; - remove(path: NormalizedPath): void; - } - function isDynamicFileName(fileName: NormalizedPath): boolean; - class ScriptInfo { - private readonly host; - readonly fileName: NormalizedPath; - readonly scriptKind: ScriptKind; - readonly hasMixedContent: boolean; - readonly path: Path; - /** - * All projects that include this file - */ - readonly containingProjects: Project[]; - private formatSettings; - private preferences; - constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path, initialVersion?: number); - isScriptOpen(): boolean; - open(newText: string | undefined): void; - close(fileExists?: boolean): void; - getSnapshot(): IScriptSnapshot; - private ensureRealPath; - getFormatCodeSettings(): FormatCodeSettings | undefined; - getPreferences(): protocol.UserPreferences | undefined; - attachToProject(project: Project): boolean; - isAttached(project: Project): boolean; - detachFromProject(project: Project): void; - detachAllProjects(): void; - getDefaultProject(): Project; - registerFileUpdate(): void; - setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; - getLatestVersion(): string; - saveTo(fileName: string): void; - reloadFromFile(tempFileName?: NormalizedPath): boolean; - editContent(start: number, end: number, newText: string): void; - markContainingProjectsAsDirty(): void; - isOrphan(): boolean; - /** - * @param line 1 based index - */ - lineToTextSpan(line: number): TextSpan; - /** - * @param line 1 based index - * @param offset 1 based index - */ - lineOffsetToPosition(line: number, offset: number): number; - positionToLineOffset(position: number): protocol.Location; - isJavaScript(): boolean; - } - interface InstallPackageOptionsWithProject extends InstallPackageOptions { - projectName: string; - projectRootPath: Path; - } - interface ITypingsInstaller { - isKnownTypesPackageName(name: string): boolean; - installPackage(options: InstallPackageOptionsWithProject): Promise; - enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; - attach(projectService: ProjectService): void; - onProjectClosed(p: Project): void; - readonly globalTypingsCacheLocation: string | undefined; - } - const nullTypingsInstaller: ITypingsInstaller; - function allRootFilesAreJsOrDts(project: Project): boolean; - function allFilesAreJsOrDts(project: Project): boolean; - enum ProjectKind { - Inferred = 0, - Configured = 1, - External = 2, - AutoImportProvider = 3, - Auxiliary = 4 - } - interface PluginCreateInfo { - project: Project; - languageService: LanguageService; - languageServiceHost: LanguageServiceHost; - serverHost: ServerHost; - session?: Session; - config: any; - } - interface PluginModule { - create(createInfo: PluginCreateInfo): LanguageService; - getExternalFiles?(proj: Project): string[]; - onConfigurationChanged?(config: any): void; - } - interface PluginModuleWithName { - name: string; - module: PluginModule; - } - type PluginModuleFactory = (mod: { - typescript: typeof ts; - }) => PluginModule; - abstract class Project implements LanguageServiceHost, ModuleResolutionHost { - readonly projectKind: ProjectKind; - readonly projectService: ProjectService; - private documentRegistry; - private compilerOptions; - compileOnSaveEnabled: boolean; - protected watchOptions: WatchOptions | undefined; - private rootFiles; - private rootFilesMap; - private program; - private externalFiles; - private missingFilesMap; - private generatedFilesMap; - protected languageService: LanguageService; - languageServiceEnabled: boolean; - readonly trace?: (s: string) => void; - readonly realpath?: (path: string) => string; - private builderState; - /** - * Set of files names that were updated since the last call to getChangesSinceVersion. - */ - private updatedFileNames; - /** - * Set of files that was returned from the last call to getChangesSinceVersion. - */ - private lastReportedFileNames; - /** - * Last version that was reported. - */ - private lastReportedVersion; - /** - * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) - * This property is changed in 'updateGraph' based on the set of files in program - */ - private projectProgramVersion; - /** - * Current version of the project state. It is changed when: - * - new root file was added/removed - * - edit happen in some file that is currently included in the project. - * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project - */ - private projectStateVersion; - protected projectErrors: Diagnostic[] | undefined; - protected isInitialLoadPending: () => boolean; - private readonly cancellationToken; - isNonTsProject(): boolean; - isJsOnlyProject(): boolean; - static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined; - isKnownTypesPackageName(name: string): boolean; - installPackage(options: InstallPackageOptions): Promise; - private get typingsCache(); - getCompilationSettings(): ts.CompilerOptions; - getCompilerOptions(): ts.CompilerOptions; - getNewLine(): string; - getProjectVersion(): string; - getProjectReferences(): readonly ProjectReference[] | undefined; - getScriptFileNames(): string[]; - private getOrCreateScriptInfoAndAttachToProject; - getScriptKind(fileName: string): ts.ScriptKind; - getScriptVersion(filename: string): string; - getScriptSnapshot(filename: string): IScriptSnapshot | undefined; - getCancellationToken(): HostCancellationToken; - getCurrentDirectory(): string; - getDefaultLibFileName(): string; - useCaseSensitiveFileNames(): boolean; - readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; - readFile(fileName: string): string | undefined; - writeFile(fileName: string, content: string): void; - fileExists(file: string): boolean; - getModuleResolutionCache(): ModuleResolutionCache | undefined; - directoryExists(path: string): boolean; - getDirectories(path: string): string[]; - log(s: string): void; - error(s: string): void; - private setInternalCompilerOptionsForEmittingJsFiles; - /** - * Get the errors that dont have any file name associated - */ - getGlobalProjectErrors(): readonly Diagnostic[]; - /** - * Get all the project errors - */ - getAllProjectErrors(): readonly Diagnostic[]; - setProjectErrors(projectErrors: Diagnostic[] | undefined): void; - getLanguageService(ensureSynchronized?: boolean): LanguageService; - getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; - /** - * Returns true if emit was conducted - */ - emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): EmitResult; - enableLanguageService(): void; - disableLanguageService(lastFileExceededProgramSize?: string): void; - getProjectName(): string; - protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; - getExternalFiles(): SortedReadonlyArray; - getSourceFile(path: Path): ts.SourceFile | undefined; - close(): void; - private detachScriptInfoIfNotRoot; - isClosed(): boolean; - hasRoots(): boolean; - getRootFiles(): ts.server.NormalizedPath[]; - getRootScriptInfos(): ts.server.ScriptInfo[]; - getScriptInfos(): ScriptInfo[]; - getExcludedFiles(): readonly NormalizedPath[]; - getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): ts.server.NormalizedPath[]; - hasConfigFile(configFilePath: NormalizedPath): boolean; - containsScriptInfo(info: ScriptInfo): boolean; - containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; - isRoot(info: ScriptInfo): boolean; - addRoot(info: ScriptInfo, fileName?: NormalizedPath): void; - addMissingFileRoot(fileName: NormalizedPath): void; - removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; - registerFileUpdate(fileName: string): void; - markAsDirty(): void; - /** - * Updates set of files that contribute to this project - * @returns: true if set of files in the project stays the same and false - otherwise. - */ - updateGraph(): boolean; - protected removeExistingTypings(include: string[]): string[]; - private updateGraphWorker; - private detachScriptInfoFromProject; - private addMissingFileWatcher; - private isWatchedMissingFile; - private createGeneratedFileWatcher; - private isValidGeneratedFileWatcher; - private clearGeneratedFileWatch; - getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; - getScriptInfo(uncheckedFileName: string): ts.server.ScriptInfo | undefined; - filesToString(writeProjectFileNames: boolean): string; - setCompilerOptions(compilerOptions: CompilerOptions): void; - setTypeAcquisition(newTypeAcquisition: TypeAcquisition | undefined): void; - getTypeAcquisition(): ts.TypeAcquisition; - protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(options: CompilerOptions): void; - protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; - /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ - refreshDiagnostics(): void; - } - /** - * If a file is opened and no tsconfig (or jsconfig) is found, - * the file and its imports/references are put into an InferredProject. - */ - class InferredProject extends Project { - private _isJsInferredProject; - toggleJsInferredProject(isJsInferredProject: boolean): void; - setCompilerOptions(options?: CompilerOptions): void; - /** this is canonical project root path */ - readonly projectRootPath: string | undefined; - addRoot(info: ScriptInfo): void; - removeRoot(info: ScriptInfo): void; - isProjectWithSingleRoot(): boolean; - close(): void; - getTypeAcquisition(): TypeAcquisition; - } - class AutoImportProviderProject extends Project { - private hostProject; - private rootFileNames; - isOrphan(): boolean; - updateGraph(): boolean; - hasRoots(): boolean; - markAsDirty(): void; - getScriptFileNames(): string[]; - getLanguageService(): never; - getHostForAutoImportProvider(): never; - getProjectReferences(): readonly ts.ProjectReference[] | undefined; - getTypeAcquisition(): TypeAcquisition; - } - /** - * If a file is opened, the server will look for a tsconfig (or jsconfig) - * and if successful create a ConfiguredProject for it. - * Otherwise it will create an InferredProject. - */ - class ConfiguredProject extends Project { - readonly canonicalConfigFilePath: NormalizedPath; - /** Ref count to the project when opened from external project */ - private externalProjectRefCount; - private projectReferences; - /** - * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph - * @returns: true if set of files in the project stays the same and false - otherwise. - */ - updateGraph(): boolean; - getConfigFilePath(): ts.server.NormalizedPath; - getProjectReferences(): readonly ProjectReference[] | undefined; - updateReferences(refs: readonly ProjectReference[] | undefined): void; - /** - * Get the errors that dont have any file name associated - */ - getGlobalProjectErrors(): readonly Diagnostic[]; - /** - * Get all the project errors - */ - getAllProjectErrors(): readonly Diagnostic[]; - setProjectErrors(projectErrors: Diagnostic[]): void; - close(): void; - getEffectiveTypeRoots(): string[]; - } - /** - * Project whose configuration is handled externally, such as in a '.csproj'. - * These are created only if a host explicitly calls `openExternalProject`. - */ - class ExternalProject extends Project { - externalProjectName: string; - compileOnSaveEnabled: boolean; - excludedFiles: readonly NormalizedPath[]; - updateGraph(): boolean; - getExcludedFiles(): readonly ts.server.NormalizedPath[]; - } - function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; - function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; - function convertWatchOptions(protocolOptions: protocol.ExternalProjectCompilerOptions, currentDirectory?: string): WatchOptionsAndErrors | undefined; - function convertTypeAcquisition(protocolOptions: protocol.InferredProjectCompilerOptions): TypeAcquisition | undefined; - function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; - function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; - const maxProgramSizeForNonTsFiles: number; - const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; - interface ProjectsUpdatedInBackgroundEvent { - eventName: typeof ProjectsUpdatedInBackgroundEvent; - data: { - openFiles: string[]; - }; - } - const ProjectLoadingStartEvent = "projectLoadingStart"; - interface ProjectLoadingStartEvent { - eventName: typeof ProjectLoadingStartEvent; - data: { - project: Project; - reason: string; - }; - } - const ProjectLoadingFinishEvent = "projectLoadingFinish"; - interface ProjectLoadingFinishEvent { - eventName: typeof ProjectLoadingFinishEvent; - data: { - project: Project; - }; - } - const LargeFileReferencedEvent = "largeFileReferenced"; - interface LargeFileReferencedEvent { - eventName: typeof LargeFileReferencedEvent; - data: { - file: string; - fileSize: number; - maxFileSize: number; - }; - } - const ConfigFileDiagEvent = "configFileDiag"; - interface ConfigFileDiagEvent { - eventName: typeof ConfigFileDiagEvent; - data: { - triggerFile: string; - configFileName: string; - diagnostics: readonly Diagnostic[]; - }; - } - const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; - interface ProjectLanguageServiceStateEvent { - eventName: typeof ProjectLanguageServiceStateEvent; - data: { - project: Project; - languageServiceEnabled: boolean; - }; - } - const ProjectInfoTelemetryEvent = "projectInfo"; - /** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */ - interface ProjectInfoTelemetryEvent { - readonly eventName: typeof ProjectInfoTelemetryEvent; - readonly data: ProjectInfoTelemetryEventData; - } - const OpenFileInfoTelemetryEvent = "openFileInfo"; - /** - * Info that we may send about a file that was just opened. - * Info about a file will only be sent once per session, even if the file changes in ways that might affect the info. - * Currently this is only sent for '.js' files. - */ - interface OpenFileInfoTelemetryEvent { - readonly eventName: typeof OpenFileInfoTelemetryEvent; - readonly data: OpenFileInfoTelemetryEventData; - } - interface ProjectInfoTelemetryEventData { - /** Cryptographically secure hash of project file location. */ - readonly projectId: string; - /** Count of file extensions seen in the project. */ - readonly fileStats: FileStats; - /** - * Any compiler options that might contain paths will be taken out. - * Enum compiler options will be converted to strings. - */ - readonly compilerOptions: CompilerOptions; - readonly extends: boolean | undefined; - readonly files: boolean | undefined; - readonly include: boolean | undefined; - readonly exclude: boolean | undefined; - readonly compileOnSave: boolean; - readonly typeAcquisition: ProjectInfoTypeAcquisitionData; - readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other"; - readonly projectType: "external" | "configured"; - readonly languageServiceEnabled: boolean; - /** TypeScript version used by the server. */ - readonly version: string; - } - interface OpenFileInfoTelemetryEventData { - readonly info: OpenFileInfo; - } - interface ProjectInfoTypeAcquisitionData { - readonly enable: boolean | undefined; - readonly include: boolean; - readonly exclude: boolean; - } - interface FileStats { - readonly js: number; - readonly jsSize?: number; - readonly jsx: number; - readonly jsxSize?: number; - readonly ts: number; - readonly tsSize?: number; - readonly tsx: number; - readonly tsxSize?: number; - readonly dts: number; - readonly dtsSize?: number; - readonly deferred: number; - readonly deferredSize?: number; - } - interface OpenFileInfo { - readonly checkJs: boolean; - } - type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; - type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; - interface SafeList { - [name: string]: { - match: RegExp; - exclude?: (string | number)[][]; - types?: string[]; - }; - } - interface TypesMapFile { - typesMap: SafeList; - simpleMap: { - [libName: string]: string; - }; - } - interface HostConfiguration { - formatCodeOptions: FormatCodeSettings; - preferences: protocol.UserPreferences; - hostInfo: string; - extraFileExtensions?: FileExtensionInfo[]; - watchOptions?: WatchOptions; - } - interface OpenConfiguredProjectResult { - configFileName?: NormalizedPath; - configFileErrors?: readonly Diagnostic[]; - } - interface ProjectServiceOptions { - host: ServerHost; - logger: Logger; - cancellationToken: HostCancellationToken; - useSingleInferredProject: boolean; - useInferredProjectPerProjectRoot: boolean; - typingsInstaller?: ITypingsInstaller; - eventHandler?: ProjectServiceEventHandler; - suppressDiagnosticEvents?: boolean; - throttleWaitMilliseconds?: number; - globalPlugins?: readonly string[]; - pluginProbeLocations?: readonly string[]; - allowLocalPluginLoads?: boolean; - typesMapLocation?: string; - serverMode?: LanguageServiceMode; - session: Session | undefined; - } - interface WatchOptionsAndErrors { - watchOptions: WatchOptions; - errors: Diagnostic[] | undefined; - } - class ProjectService { - private readonly nodeModulesWatchers; - /** - * Contains all the deleted script info's version information so that - * it does not reset when creating script info again - * (and could have potentially collided with version where contents mismatch) - */ - private readonly filenameToScriptInfoVersion; - private readonly allJsFilesForOpenFileTelemetry; - /** - * maps external project file name to list of config files that were the part of this project - */ - private readonly externalProjectToConfiguredProjectMap; - /** - * external projects (configuration and list of root files is not controlled by tsserver) - */ - readonly externalProjects: ExternalProject[]; - /** - * projects built from openFileRoots - */ - readonly inferredProjects: InferredProject[]; - /** - * projects specified by a tsconfig.json file - */ - readonly configuredProjects: Map; - /** - * Open files: with value being project root path, and key being Path of the file that is open - */ - readonly openFiles: Map; - /** - * Map of open files that are opened without complete path but have projectRoot as current directory - */ - private readonly openFilesWithNonRootedDiskPath; - private compilerOptionsForInferredProjects; - private compilerOptionsForInferredProjectsPerProjectRoot; - private watchOptionsForInferredProjects; - private watchOptionsForInferredProjectsPerProjectRoot; - private typeAcquisitionForInferredProjects; - private typeAcquisitionForInferredProjectsPerProjectRoot; - /** - * Project size for configured or external projects - */ - private readonly projectToSizeMap; - private readonly hostConfiguration; - private safelist; - private readonly legacySafelist; - private pendingProjectUpdates; - readonly currentDirectory: NormalizedPath; - readonly toCanonicalFileName: (f: string) => string; - readonly host: ServerHost; - readonly logger: Logger; - readonly cancellationToken: HostCancellationToken; - readonly useSingleInferredProject: boolean; - readonly useInferredProjectPerProjectRoot: boolean; - readonly typingsInstaller: ITypingsInstaller; - private readonly globalCacheLocationDirectoryPath; - readonly throttleWaitMilliseconds?: number; - private readonly eventHandler?; - private readonly suppressDiagnosticEvents?; - readonly globalPlugins: readonly string[]; - readonly pluginProbeLocations: readonly string[]; - readonly allowLocalPluginLoads: boolean; - readonly typesMapLocation: string | undefined; - readonly serverMode: LanguageServiceMode; - /** Tracks projects that we have already sent telemetry for. */ - private readonly seenProjects; - private performanceEventHandler?; - private pendingPluginEnablements?; - private currentPluginEnablementPromise?; - constructor(opts: ProjectServiceOptions); - toPath(fileName: string): Path; - private loadTypesMap; - updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; - private delayUpdateProjectGraph; - private delayUpdateProjectGraphs; - setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.InferredProjectCompilerOptions, projectRootPath?: string): void; - findProject(projectName: string): Project | undefined; - getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined; - private doEnsureDefaultProjectForFile; - getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined; - /** - * Ensures the project structures are upto date - * This means, - * - we go through all the projects and update them if they are dirty - * - if updates reflect some change in structure or there was pending request to ensure projects for open files - * ensure that each open script info has project - */ - private ensureProjectStructuresUptoDate; - getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; - getPreferences(file: NormalizedPath): protocol.UserPreferences; - getHostFormatCodeOptions(): FormatCodeSettings; - getHostPreferences(): protocol.UserPreferences; - private onSourceFileChanged; - private handleSourceMapProjects; - private delayUpdateSourceInfoProjects; - private delayUpdateProjectsOfScriptInfoPath; - private handleDeletedFile; - private removeProject; - private assignOrphanScriptInfosToInferredProject; - /** - * Remove this file from the set of open, non-configured files. - * @param info The file that has been closed or newly configured - */ - private closeOpenFile; - private deleteScriptInfo; - private configFileExists; - /** - * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project - */ - private configFileExistenceImpactsRootOfInferredProject; - /** - * This is called on file close, so that we stop watching the config file for this script info - */ - private stopWatchingConfigFilesForClosedScriptInfo; - /** - * This function tries to search for a tsconfig.json for the given file. - * This is different from the method the compiler uses because - * the compiler can assume it will always start searching in the - * current directory (the directory in which tsc was invoked). - * The server must start searching from the directory containing - * the newly opened file. - */ - private forEachConfigFileLocation; - /** - * This function tries to search for a tsconfig.json for the given file. - * This is different from the method the compiler uses because - * the compiler can assume it will always start searching in the - * current directory (the directory in which tsc was invoked). - * The server must start searching from the directory containing - * the newly opened file. - * If script info is passed in, it is asserted to be open script info - * otherwise just file name - */ - private getConfigFileNameForFile; - private printProjects; - private getConfiguredProjectByCanonicalConfigFilePath; - private findExternalProjectByProjectName; - /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ - private getFilenameForExceededTotalSizeLimitForNonTsFiles; - private createExternalProject; - private addFilesToNonInferredProject; - private updateNonInferredProjectFiles; - private updateRootAndOptionsOfNonInferredProject; - private sendConfigFileDiagEvent; - private getOrCreateInferredProjectForProjectRootPathIfEnabled; - private getOrCreateSingleInferredProjectIfEnabled; - private getOrCreateSingleInferredWithoutProjectRoot; - private createInferredProject; - getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; - private watchClosedScriptInfo; - private createNodeModulesWatcher; - private watchClosedScriptInfoInNodeModules; - private getModifiedTime; - private refreshScriptInfo; - private refreshScriptInfosInDirectory; - private stopWatchingScriptInfo; - private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; - private getOrCreateScriptInfoOpenedByClientForNormalizedPath; - getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { - fileExists(path: string): boolean; - }): ScriptInfo | undefined; - private getOrCreateScriptInfoWorker; - /** - * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred - */ - getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; - getScriptInfoForPath(fileName: Path): ScriptInfo | undefined; - private addSourceInfoToSourceMap; - private addMissingSourceMapFile; - setHostConfiguration(args: protocol.ConfigureRequestArguments): void; - closeLog(): void; - /** - * This function rebuilds the project for every file opened by the client - * This does not reload contents of open files from disk. But we could do that if needed - */ - reloadProjects(): void; - /** - * This function goes through all the openFiles and tries to file the config file for them. - * If the config file is found and it refers to existing project, it reloads it either immediately - * or schedules it for reload depending on delayReload option - * If there is no existing project it just opens the configured project for the config file - * reloadForInfo provides a way to filter out files to reload configured project for - */ - private reloadConfiguredProjectForFiles; - /** - * Remove the root of inferred project if script info is part of another project - */ - private removeRootOfInferredProjectIfNowPartOfOtherProject; - /** - * This function is to update the project structure for every inferred project. - * It is called on the premise that all the configured projects are - * up to date. - * This will go through open files and assign them to inferred project if open file is not part of any other project - * After that all the inferred project graphs are updated - */ - private ensureProjectForOpenFiles; - /** - * Open file whose contents is managed by the client - * @param filename is absolute pathname - * @param fileContent is a known version of the file content that is more up to date than the one on disk - */ - openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; - private findExternalProjectContainingOpenScriptInfo; - private getOrCreateOpenScriptInfo; - private assignProjectToOpenedScriptInfo; - private createAncestorProjects; - private ensureProjectChildren; - private cleanupAfterOpeningFile; - openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; - private removeOrphanConfiguredProjects; - private removeOrphanScriptInfos; - private telemetryOnOpenFile; - /** - * Close file whose contents is managed by the client - * @param filename is absolute pathname - */ - closeClientFile(uncheckedFileName: string): void; - private collectChanges; - private closeConfiguredProjectReferencedFromExternalProject; - closeExternalProject(uncheckedFileName: string): void; - openExternalProjects(projects: protocol.ExternalProject[]): void; - /** Makes a filename safe to insert in a RegExp */ - private static readonly filenameEscapeRegexp; - private static escapeFilenameForRegex; - resetSafeList(): void; - applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; - openExternalProject(proj: protocol.ExternalProject): void; - hasDeferredExtension(): boolean; - private enableRequestedPluginsAsync; - private enableRequestedPluginsWorker; - private enableRequestedPluginsForProjectAsync; - configurePlugin(args: protocol.ConfigurePluginRequestArguments): void; - } - function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: BufferEncoding) => number, newLine: string): string; - interface ServerCancellationToken extends HostCancellationToken { - setRequest(requestId: number): void; - resetRequest(requestId: number): void; - } - const nullCancellationToken: ServerCancellationToken; - interface PendingErrorCheck { - fileName: NormalizedPath; - project: Project; - } - /** @deprecated use ts.server.protocol.CommandTypes */ - type CommandNames = protocol.CommandTypes; - /** @deprecated use ts.server.protocol.CommandTypes */ - const CommandNames: any; - type Event = (body: T, eventName: string) => void; - interface EventSender { - event: Event; - } - interface SessionOptions { - host: ServerHost; - cancellationToken: ServerCancellationToken; - useSingleInferredProject: boolean; - useInferredProjectPerProjectRoot: boolean; - typingsInstaller?: ITypingsInstaller; - byteLength: (buf: string, encoding?: BufferEncoding) => number; - hrtime: (start?: [ - number, - number - ]) => [ - number, - number - ]; - logger: Logger; - /** - * If falsy, all events are suppressed. - */ - canUseEvents: boolean; - eventHandler?: ProjectServiceEventHandler; - /** Has no effect if eventHandler is also specified. */ - suppressDiagnosticEvents?: boolean; - serverMode?: LanguageServiceMode; - throttleWaitMilliseconds?: number; - noGetErrOnBackgroundUpdate?: boolean; - globalPlugins?: readonly string[]; - pluginProbeLocations?: readonly string[]; - allowLocalPluginLoads?: boolean; - typesMapLocation?: string; - } - class Session implements EventSender { - private readonly gcTimer; - protected projectService: ProjectService; - private changeSeq; - private performanceData; - private currentRequestId; - private errorCheck; - protected host: ServerHost; - private readonly cancellationToken; - protected readonly typingsInstaller: ITypingsInstaller; - protected byteLength: (buf: string, encoding?: BufferEncoding) => number; - private hrtime; - protected logger: Logger; - protected canUseEvents: boolean; - private suppressDiagnosticEvents?; - private eventHandler; - private readonly noGetErrOnBackgroundUpdate?; - constructor(opts: SessionOptions); - private sendRequestCompletedEvent; - private addPerformanceData; - private performanceEventHandler; - private defaultEventHandler; - private projectsUpdatedInBackgroundEvent; - logError(err: Error, cmd: string): void; - private logErrorWorker; - send(msg: protocol.Message): void; - protected writeMessage(msg: protocol.Message): void; - event(body: T, eventName: string): void; - private semanticCheck; - private syntacticCheck; - private suggestionCheck; - private sendDiagnosticsEvent; - /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ - private updateErrorCheck; - private cleanProjects; - private cleanup; - private getEncodedSyntacticClassifications; - private getEncodedSemanticClassifications; - private getProject; - private getConfigFileAndProject; - private getConfigFileDiagnostics; - private convertToDiagnosticsWithLinePositionFromDiagnosticFile; - private getCompilerOptionsDiagnostics; - private convertToDiagnosticsWithLinePosition; - private getDiagnosticsWorker; - private getDefinition; - private mapDefinitionInfoLocations; - private getDefinitionAndBoundSpan; - private findSourceDefinition; - private getEmitOutput; - private mapJSDocTagInfo; - private mapDisplayParts; - private mapSignatureHelpItems; - private mapDefinitionInfo; - private static mapToOriginalLocation; - private toFileSpan; - private toFileSpanWithContext; - private getTypeDefinition; - private mapImplementationLocations; - private getImplementation; - private getSyntacticDiagnosticsSync; - private getSemanticDiagnosticsSync; - private getSuggestionDiagnosticsSync; - private getJsxClosingTag; - private getLinkedEditingRange; - private getDocumentHighlights; - private provideInlayHints; - private setCompilerOptionsForInferredProjects; - private getProjectInfo; - private getProjectInfoWorker; - private getRenameInfo; - private getProjects; - private getDefaultProject; - private getRenameLocations; - private mapRenameInfo; - private toSpanGroups; - private getReferences; - private getFileReferences; - /** - * @param fileName is the name of the file to be opened - * @param fileContent is a version of the file content that is known to be more up to date than the one on disk - */ - private openClientFile; - private getPosition; - private getPositionInFile; - private getFileAndProject; - private getFileAndLanguageServiceForSyntacticOperation; - private getFileAndProjectWorker; - private getOutliningSpans; - private getTodoComments; - private getDocCommentTemplate; - private getSpanOfEnclosingComment; - private getIndentation; - private getBreakpointStatement; - private getNameOrDottedNameSpan; - private isValidBraceCompletion; - private getQuickInfoWorker; - private getFormattingEditsForRange; - private getFormattingEditsForRangeFull; - private getFormattingEditsForDocumentFull; - private getFormattingEditsAfterKeystrokeFull; - private getFormattingEditsAfterKeystroke; - private getCompletions; - private getCompletionEntryDetails; - private getCompileOnSaveAffectedFileList; - private emitFile; - private getSignatureHelpItems; - private toPendingErrorCheck; - private getDiagnostics; - private change; - private reload; - private saveToTmp; - private closeClientFile; - private mapLocationNavigationBarItems; - private getNavigationBarItems; - private toLocationNavigationTree; - private getNavigationTree; - private getNavigateToItems; - private getFullNavigateToItems; - private getSupportedCodeFixes; - private isLocation; - private extractPositionOrRange; - private getRange; - private getApplicableRefactors; - private getEditsForRefactor; - private getMoveToRefactoringFileSuggestions; - private organizeImports; - private getEditsForFileRename; - private getCodeFixes; - private getCombinedCodeFix; - private applyCodeActionCommand; - private getStartAndEndPosition; - private mapCodeAction; - private mapCodeFixAction; - private mapTextChangesToCodeEdits; - private mapTextChangeToCodeEdit; - private convertTextChangeToCodeEdit; - private getBraceMatching; - private getDiagnosticsForProject; - private configurePlugin; - private getSmartSelectionRange; - private toggleLineComment; - private toggleMultilineComment; - private commentSelection; - private uncommentSelection; - private mapSelectionRange; - private getScriptInfoFromProjectService; - private toProtocolCallHierarchyItem; - private toProtocolCallHierarchyIncomingCall; - private toProtocolCallHierarchyOutgoingCall; - private prepareCallHierarchy; - private provideCallHierarchyIncomingCalls; - private provideCallHierarchyOutgoingCalls; - getCanonicalFileName(fileName: string): string; - exit(): void; - private notRequired; - private requiredResponse; - private handlers; - addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; - private setCurrentRequest; - private resetCurrentRequest; - executeWithRequestId(requestId: number, f: () => T): T; - executeCommand(request: protocol.Request): HandlerResponse; - onMessage(message: TMessage): void; - protected parseMessage(message: TMessage): protocol.Request; - protected toStringMessage(message: TMessage): string; - private getFormatOptions; - private getPreferences; - private getHostFormatOptions; - private getHostPreferences; - } - interface HandlerResponse { - response?: {}; - responseRequired?: boolean; - } - } - const versionMajorMinor = "5.3"; - /** The version of the TypeScript compiler release */ - const version: string; - /** - * Type of objects whose values are all of the same type. - * The `in` and `for-in` operators can *not* be safely used, - * since `Object.prototype` may be modified by outside code. - */ - interface MapLike { - [index: string]: T; - } - interface SortedReadonlyArray extends ReadonlyArray { - " __sortedArrayBrand": any; - } - interface SortedArray extends Array { - " __sortedArrayBrand": any; - } - type Path = string & { - __pathBrand: any; - }; - interface TextRange { - pos: number; - end: number; - } - interface ReadonlyTextRange { - readonly pos: number; - readonly end: number; - } - enum SyntaxKind { - Unknown = 0, - EndOfFileToken = 1, - SingleLineCommentTrivia = 2, - MultiLineCommentTrivia = 3, - NewLineTrivia = 4, - WhitespaceTrivia = 5, - ShebangTrivia = 6, - ConflictMarkerTrivia = 7, - NonTextFileMarkerTrivia = 8, - NumericLiteral = 9, - BigIntLiteral = 10, - StringLiteral = 11, - JsxText = 12, - JsxTextAllWhiteSpaces = 13, - RegularExpressionLiteral = 14, - NoSubstitutionTemplateLiteral = 15, - TemplateHead = 16, - TemplateMiddle = 17, - TemplateTail = 18, - OpenBraceToken = 19, - CloseBraceToken = 20, - OpenParenToken = 21, - CloseParenToken = 22, - OpenBracketToken = 23, - CloseBracketToken = 24, - DotToken = 25, - DotDotDotToken = 26, - SemicolonToken = 27, - CommaToken = 28, - QuestionDotToken = 29, - LessThanToken = 30, - LessThanSlashToken = 31, - GreaterThanToken = 32, - LessThanEqualsToken = 33, - GreaterThanEqualsToken = 34, - EqualsEqualsToken = 35, - ExclamationEqualsToken = 36, - EqualsEqualsEqualsToken = 37, - ExclamationEqualsEqualsToken = 38, - EqualsGreaterThanToken = 39, - PlusToken = 40, - MinusToken = 41, - AsteriskToken = 42, - AsteriskAsteriskToken = 43, - SlashToken = 44, - PercentToken = 45, - PlusPlusToken = 46, - MinusMinusToken = 47, - LessThanLessThanToken = 48, - GreaterThanGreaterThanToken = 49, - GreaterThanGreaterThanGreaterThanToken = 50, - AmpersandToken = 51, - BarToken = 52, - CaretToken = 53, - ExclamationToken = 54, - TildeToken = 55, - AmpersandAmpersandToken = 56, - BarBarToken = 57, - QuestionToken = 58, - ColonToken = 59, - AtToken = 60, - QuestionQuestionToken = 61, - /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */ - BacktickToken = 62, - /** Only the JSDoc scanner produces HashToken. The normal scanner produces PrivateIdentifier. */ - HashToken = 63, - EqualsToken = 64, - PlusEqualsToken = 65, - MinusEqualsToken = 66, - AsteriskEqualsToken = 67, - AsteriskAsteriskEqualsToken = 68, - SlashEqualsToken = 69, - PercentEqualsToken = 70, - LessThanLessThanEqualsToken = 71, - GreaterThanGreaterThanEqualsToken = 72, - GreaterThanGreaterThanGreaterThanEqualsToken = 73, - AmpersandEqualsToken = 74, - BarEqualsToken = 75, - BarBarEqualsToken = 76, - AmpersandAmpersandEqualsToken = 77, - QuestionQuestionEqualsToken = 78, - CaretEqualsToken = 79, - Identifier = 80, - PrivateIdentifier = 81, - BreakKeyword = 83, - CaseKeyword = 84, - CatchKeyword = 85, - ClassKeyword = 86, - ConstKeyword = 87, - ContinueKeyword = 88, - DebuggerKeyword = 89, - DefaultKeyword = 90, - DeleteKeyword = 91, - DoKeyword = 92, - ElseKeyword = 93, - EnumKeyword = 94, - ExportKeyword = 95, - ExtendsKeyword = 96, - FalseKeyword = 97, - FinallyKeyword = 98, - ForKeyword = 99, - FunctionKeyword = 100, - IfKeyword = 101, - ImportKeyword = 102, - InKeyword = 103, - InstanceOfKeyword = 104, - NewKeyword = 105, - NullKeyword = 106, - ReturnKeyword = 107, - SuperKeyword = 108, - SwitchKeyword = 109, - ThisKeyword = 110, - ThrowKeyword = 111, - TrueKeyword = 112, - TryKeyword = 113, - TypeOfKeyword = 114, - VarKeyword = 115, - VoidKeyword = 116, - WhileKeyword = 117, - WithKeyword = 118, - ImplementsKeyword = 119, - InterfaceKeyword = 120, - LetKeyword = 121, - PackageKeyword = 122, - PrivateKeyword = 123, - ProtectedKeyword = 124, - PublicKeyword = 125, - StaticKeyword = 126, - YieldKeyword = 127, - AbstractKeyword = 128, - AccessorKeyword = 129, - AsKeyword = 130, - AssertsKeyword = 131, - AssertKeyword = 132, - AnyKeyword = 133, - AsyncKeyword = 134, - AwaitKeyword = 135, - BooleanKeyword = 136, - ConstructorKeyword = 137, - DeclareKeyword = 138, - GetKeyword = 139, - InferKeyword = 140, - IntrinsicKeyword = 141, - IsKeyword = 142, - KeyOfKeyword = 143, - ModuleKeyword = 144, - NamespaceKeyword = 145, - NeverKeyword = 146, - OutKeyword = 147, - ReadonlyKeyword = 148, - RequireKeyword = 149, - NumberKeyword = 150, - ObjectKeyword = 151, - SatisfiesKeyword = 152, - SetKeyword = 153, - StringKeyword = 154, - SymbolKeyword = 155, - TypeKeyword = 156, - UndefinedKeyword = 157, - UniqueKeyword = 158, - UnknownKeyword = 159, - UsingKeyword = 160, - FromKeyword = 161, - GlobalKeyword = 162, - BigIntKeyword = 163, - OverrideKeyword = 164, - OfKeyword = 165, - QualifiedName = 166, - ComputedPropertyName = 167, - TypeParameter = 168, - Parameter = 169, - Decorator = 170, - PropertySignature = 171, - PropertyDeclaration = 172, - MethodSignature = 173, - MethodDeclaration = 174, - ClassStaticBlockDeclaration = 175, - Constructor = 176, - GetAccessor = 177, - SetAccessor = 178, - CallSignature = 179, - ConstructSignature = 180, - IndexSignature = 181, - TypePredicate = 182, - TypeReference = 183, - FunctionType = 184, - ConstructorType = 185, - TypeQuery = 186, - TypeLiteral = 187, - ArrayType = 188, - TupleType = 189, - OptionalType = 190, - RestType = 191, - UnionType = 192, - IntersectionType = 193, - ConditionalType = 194, - InferType = 195, - ParenthesizedType = 196, - ThisType = 197, - TypeOperator = 198, - IndexedAccessType = 199, - MappedType = 200, - LiteralType = 201, - NamedTupleMember = 202, - TemplateLiteralType = 203, - TemplateLiteralTypeSpan = 204, - ImportType = 205, - ObjectBindingPattern = 206, - ArrayBindingPattern = 207, - BindingElement = 208, - ArrayLiteralExpression = 209, - ObjectLiteralExpression = 210, - PropertyAccessExpression = 211, - ElementAccessExpression = 212, - CallExpression = 213, - NewExpression = 214, - TaggedTemplateExpression = 215, - TypeAssertionExpression = 216, - ParenthesizedExpression = 217, - FunctionExpression = 218, - ArrowFunction = 219, - DeleteExpression = 220, - TypeOfExpression = 221, - VoidExpression = 222, - AwaitExpression = 223, - PrefixUnaryExpression = 224, - PostfixUnaryExpression = 225, - BinaryExpression = 226, - ConditionalExpression = 227, - TemplateExpression = 228, - YieldExpression = 229, - SpreadElement = 230, - ClassExpression = 231, - OmittedExpression = 232, - ExpressionWithTypeArguments = 233, - AsExpression = 234, - NonNullExpression = 235, - MetaProperty = 236, - SyntheticExpression = 237, - SatisfiesExpression = 238, - TemplateSpan = 239, - SemicolonClassElement = 240, - Block = 241, - EmptyStatement = 242, - VariableStatement = 243, - ExpressionStatement = 244, - IfStatement = 245, - DoStatement = 246, - WhileStatement = 247, - ForStatement = 248, - ForInStatement = 249, - ForOfStatement = 250, - ContinueStatement = 251, - BreakStatement = 252, - ReturnStatement = 253, - WithStatement = 254, - SwitchStatement = 255, - LabeledStatement = 256, - ThrowStatement = 257, - TryStatement = 258, - DebuggerStatement = 259, - VariableDeclaration = 260, - VariableDeclarationList = 261, - FunctionDeclaration = 262, - ClassDeclaration = 263, - InterfaceDeclaration = 264, - TypeAliasDeclaration = 265, - EnumDeclaration = 266, - ModuleDeclaration = 267, - ModuleBlock = 268, - CaseBlock = 269, - NamespaceExportDeclaration = 270, - ImportEqualsDeclaration = 271, - ImportDeclaration = 272, - ImportClause = 273, - NamespaceImport = 274, - NamedImports = 275, - ImportSpecifier = 276, - ExportAssignment = 277, - ExportDeclaration = 278, - NamedExports = 279, - NamespaceExport = 280, - ExportSpecifier = 281, - MissingDeclaration = 282, - ExternalModuleReference = 283, - JsxElement = 284, - JsxSelfClosingElement = 285, - JsxOpeningElement = 286, - JsxClosingElement = 287, - JsxFragment = 288, - JsxOpeningFragment = 289, - JsxClosingFragment = 290, - JsxAttribute = 291, - JsxAttributes = 292, - JsxSpreadAttribute = 293, - JsxExpression = 294, - JsxNamespacedName = 295, - CaseClause = 296, - DefaultClause = 297, - HeritageClause = 298, - CatchClause = 299, - AssertClause = 300, - AssertEntry = 301, - ImportTypeAssertionContainer = 302, - PropertyAssignment = 303, - ShorthandPropertyAssignment = 304, - SpreadAssignment = 305, - EnumMember = 306, - /** @deprecated */ UnparsedPrologue = 307, - /** @deprecated */ UnparsedPrepend = 308, - /** @deprecated */ UnparsedText = 309, - /** @deprecated */ UnparsedInternalText = 310, - /** @deprecated */ UnparsedSyntheticReference = 311, - SourceFile = 312, - Bundle = 313, - /** @deprecated */ UnparsedSource = 314, - /** @deprecated */ InputFiles = 315, - JSDocTypeExpression = 316, - JSDocNameReference = 317, - JSDocMemberName = 318, - JSDocAllType = 319, - JSDocUnknownType = 320, - JSDocNullableType = 321, - JSDocNonNullableType = 322, - JSDocOptionalType = 323, - JSDocFunctionType = 324, - JSDocVariadicType = 325, - JSDocNamepathType = 326, - JSDoc = 327, - /** @deprecated Use SyntaxKind.JSDoc */ - JSDocComment = 327, - JSDocText = 328, - JSDocTypeLiteral = 329, - JSDocSignature = 330, - JSDocLink = 331, - JSDocLinkCode = 332, - JSDocLinkPlain = 333, - JSDocTag = 334, - JSDocAugmentsTag = 335, - JSDocImplementsTag = 336, - JSDocAuthorTag = 337, - JSDocDeprecatedTag = 338, - JSDocClassTag = 339, - JSDocPublicTag = 340, - JSDocPrivateTag = 341, - JSDocProtectedTag = 342, - JSDocReadonlyTag = 343, - JSDocOverrideTag = 344, - JSDocCallbackTag = 345, - JSDocOverloadTag = 346, - JSDocEnumTag = 347, - JSDocParameterTag = 348, - JSDocReturnTag = 349, - JSDocThisTag = 350, - JSDocTypeTag = 351, - JSDocTemplateTag = 352, - JSDocTypedefTag = 353, - JSDocSeeTag = 354, - JSDocPropertyTag = 355, - JSDocThrowsTag = 356, - JSDocSatisfiesTag = 357, - SyntaxList = 358, - NotEmittedStatement = 359, - PartiallyEmittedExpression = 360, - CommaListExpression = 361, - SyntheticReferenceExpression = 362, - Count = 363, - FirstAssignment = 64, - LastAssignment = 79, - FirstCompoundAssignment = 65, - LastCompoundAssignment = 79, - FirstReservedWord = 83, - LastReservedWord = 118, - FirstKeyword = 83, - LastKeyword = 165, - FirstFutureReservedWord = 119, - LastFutureReservedWord = 127, - FirstTypeNode = 182, - LastTypeNode = 205, - FirstPunctuation = 19, - LastPunctuation = 79, - FirstToken = 0, - LastToken = 165, - FirstTriviaToken = 2, - LastTriviaToken = 7, - FirstLiteralToken = 9, - LastLiteralToken = 15, - FirstTemplateToken = 15, - LastTemplateToken = 18, - FirstBinaryOperator = 30, - LastBinaryOperator = 79, - FirstStatement = 243, - LastStatement = 259, - FirstNode = 166, - FirstJSDocNode = 316, - LastJSDocNode = 357, - FirstJSDocTagNode = 334, - LastJSDocTagNode = 357 - } - type TriviaSyntaxKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia; - type LiteralSyntaxKind = SyntaxKind.NumericLiteral | SyntaxKind.BigIntLiteral | SyntaxKind.StringLiteral | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral; - type PseudoLiteralSyntaxKind = SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail; - type PunctuationSyntaxKind = SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.QuestionDotToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.AmpersandAmpersandEqualsToken | SyntaxKind.BarBarToken | SyntaxKind.BarBarEqualsToken | SyntaxKind.QuestionQuestionToken | SyntaxKind.QuestionQuestionEqualsToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken; - type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.AssertsKeyword | SyntaxKind.AssertKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InferKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.OfKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.RequireKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SatisfiesKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.UsingKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword; - type ModifierSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AccessorKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.ConstKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.ExportKeyword | SyntaxKind.InKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword | SyntaxKind.StaticKeyword; - type KeywordTypeSyntaxKind = SyntaxKind.AnyKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.IntrinsicKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VoidKeyword; - type TokenSyntaxKind = SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | TriviaSyntaxKind | LiteralSyntaxKind | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier | KeywordSyntaxKind; - type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; - type JSDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.GreaterThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.Unknown | KeywordSyntaxKind; - enum NodeFlags { - None = 0, - Let = 1, - Const = 2, - Using = 4, - AwaitUsing = 6, - NestedNamespace = 8, - Synthesized = 16, - Namespace = 32, - OptionalChain = 64, - ExportContext = 128, - ContainsThis = 256, - HasImplicitReturn = 512, - HasExplicitReturn = 1024, - GlobalAugmentation = 2048, - HasAsyncFunctions = 4096, - DisallowInContext = 8192, - YieldContext = 16384, - DecoratorContext = 32768, - AwaitContext = 65536, - DisallowConditionalTypesContext = 131072, - ThisNodeHasError = 262144, - JavaScriptFile = 524288, - ThisNodeOrAnySubNodesHasError = 1048576, - HasAggregatedChildData = 2097152, - JSDoc = 16777216, - JsonFile = 134217728, - BlockScoped = 7, - Constant = 6, - ReachabilityCheckFlags = 1536, - ReachabilityAndEmitFlags = 5632, - ContextFlags = 101441536, - TypeExcludesFlags = 81920 - } - enum ModifierFlags { - None = 0, - Export = 1, - Ambient = 2, - Public = 4, - Private = 8, - Protected = 16, - Static = 32, - Readonly = 64, - Accessor = 128, - Abstract = 256, - Async = 512, - Default = 1024, - Const = 2048, - HasComputedJSDocModifiers = 4096, - Deprecated = 8192, - Override = 16384, - In = 32768, - Out = 65536, - Decorator = 131072, - HasComputedFlags = 536870912, - AccessibilityModifier = 28, - ParameterPropertyModifier = 16476, - NonPublicAccessibilityModifier = 24, - TypeScriptModifier = 117086, - ExportDefault = 1025, - All = 258047, - Modifier = 126975 - } - enum JsxFlags { - None = 0, - /** An element from a named property of the JSX.IntrinsicElements interface */ - IntrinsicNamedElement = 1, - /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ - IntrinsicIndexedElement = 2, - IntrinsicElement = 3 - } - interface Node extends ReadonlyTextRange { - readonly kind: SyntaxKind; - readonly flags: NodeFlags; - readonly parent: Node; - } - interface Node { - getSourceFile(): SourceFile; - getChildCount(sourceFile?: SourceFile): number; - getChildAt(index: number, sourceFile?: SourceFile): Node; - getChildren(sourceFile?: SourceFile): Node[]; - getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; - getFullStart(): number; - getEnd(): number; - getWidth(sourceFile?: SourceFileLike): number; - getFullWidth(): number; - getLeadingTriviaWidth(sourceFile?: SourceFile): number; - getFullText(sourceFile?: SourceFile): string; - getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node | undefined; - getLastToken(sourceFile?: SourceFile): Node | undefined; - forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; - } - interface JSDocContainer extends Node { - _jsdocContainerBrand: any; - } - interface LocalsContainer extends Node { - _localsContainerBrand: any; - } - interface FlowContainer extends Node { - _flowContainerBrand: any; - } - type HasJSDoc = AccessorDeclaration | ArrowFunction | BinaryExpression | Block | BreakStatement | CallSignatureDeclaration | CaseClause | ClassLikeDeclaration | ClassStaticBlockDeclaration | ConstructorDeclaration | ConstructorTypeNode | ConstructSignatureDeclaration | ContinueStatement | DebuggerStatement | DoStatement | ElementAccessExpression | EmptyStatement | EndOfFileToken | EnumDeclaration | EnumMember | ExportAssignment | ExportDeclaration | ExportSpecifier | ExpressionStatement | ForInStatement | ForOfStatement | ForStatement | FunctionDeclaration | FunctionExpression | FunctionTypeNode | Identifier | IfStatement | ImportDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | InterfaceDeclaration | JSDocFunctionType | JSDocSignature | LabeledStatement | MethodDeclaration | MethodSignature | ModuleDeclaration | NamedTupleMember | NamespaceExportDeclaration | ObjectLiteralExpression | ParameterDeclaration | ParenthesizedExpression | PropertyAccessExpression | PropertyAssignment | PropertyDeclaration | PropertySignature | ReturnStatement | SemicolonClassElement | ShorthandPropertyAssignment | SpreadAssignment | SwitchStatement | ThrowStatement | TryStatement | TypeAliasDeclaration | TypeParameterDeclaration | VariableDeclaration | VariableStatement | WhileStatement | WithStatement; - type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; - type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; - type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; - type HasExpressionInitializer = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | EnumMember; - type HasDecorators = ParameterDeclaration | PropertyDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ClassExpression | ClassDeclaration; - type HasModifiers = TypeParameterDeclaration | ParameterDeclaration | ConstructorTypeNode | PropertySignature | PropertyDeclaration | MethodSignature | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | IndexSignatureDeclaration | FunctionExpression | ArrowFunction | ClassExpression | VariableStatement | FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | ExportAssignment | ExportDeclaration; - interface NodeArray extends ReadonlyArray, ReadonlyTextRange { - readonly hasTrailingComma: boolean; - } - interface Token extends Node { - readonly kind: TKind; - } - type EndOfFileToken = Token & JSDocContainer; - interface PunctuationToken extends Token { - } - type DotToken = PunctuationToken; - type DotDotDotToken = PunctuationToken; - type QuestionToken = PunctuationToken; - type ExclamationToken = PunctuationToken; - type ColonToken = PunctuationToken; - type EqualsToken = PunctuationToken; - type AmpersandAmpersandEqualsToken = PunctuationToken; - type BarBarEqualsToken = PunctuationToken; - type QuestionQuestionEqualsToken = PunctuationToken; - type AsteriskToken = PunctuationToken; - type EqualsGreaterThanToken = PunctuationToken; - type PlusToken = PunctuationToken; - type MinusToken = PunctuationToken; - type QuestionDotToken = PunctuationToken; - interface KeywordToken extends Token { - } - type AssertsKeyword = KeywordToken; - type AssertKeyword = KeywordToken; - type AwaitKeyword = KeywordToken; - type CaseKeyword = KeywordToken; - interface ModifierToken extends KeywordToken { - } - type AbstractKeyword = ModifierToken; - type AccessorKeyword = ModifierToken; - type AsyncKeyword = ModifierToken; - type ConstKeyword = ModifierToken; - type DeclareKeyword = ModifierToken; - type DefaultKeyword = ModifierToken; - type ExportKeyword = ModifierToken; - type InKeyword = ModifierToken; - type PrivateKeyword = ModifierToken; - type ProtectedKeyword = ModifierToken; - type PublicKeyword = ModifierToken; - type ReadonlyKeyword = ModifierToken; - type OutKeyword = ModifierToken; - type OverrideKeyword = ModifierToken; - type StaticKeyword = ModifierToken; - type Modifier = AbstractKeyword | AccessorKeyword | AsyncKeyword | ConstKeyword | DeclareKeyword | DefaultKeyword | ExportKeyword | InKeyword | PrivateKeyword | ProtectedKeyword | PublicKeyword | OutKeyword | OverrideKeyword | ReadonlyKeyword | StaticKeyword; - type ModifierLike = Modifier | Decorator; - type AccessibilityModifier = PublicKeyword | PrivateKeyword | ProtectedKeyword; - type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; - type ClassMemberModifier = AccessibilityModifier | ReadonlyKeyword | StaticKeyword | AccessorKeyword; - type ModifiersArray = NodeArray; - enum GeneratedIdentifierFlags { - None = 0, - ReservedInNestedScopes = 8, - Optimistic = 16, - FileLevel = 32, - AllowNameSubstitution = 64 - } - interface Identifier extends PrimaryExpression, Declaration, JSDocContainer, FlowContainer { - readonly kind: SyntaxKind.Identifier; - /** - * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) - * Text of identifier, but if the identifier begins with two underscores, this will begin with three. - */ - readonly escapedText: __String; - } - interface Identifier { - readonly text: string; - } - interface Identifier { - /** @deprecated Use `idKeyword(identifier)` instead. */ - readonly originalKeywordKind?: SyntaxKind; - /** @deprecated Use `.parent` or the surrounding context to determine this instead. */ - readonly isInJSDocNamespace?: boolean; - } - interface TransientIdentifier extends Identifier { - resolvedSymbol: Symbol; - } - interface QualifiedName extends Node, FlowContainer { - readonly kind: SyntaxKind.QualifiedName; - readonly left: EntityName; - readonly right: Identifier; - } - type EntityName = Identifier | QualifiedName; - type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; - type MemberName = Identifier | PrivateIdentifier; - type DeclarationName = PropertyName | JsxAttributeName | StringLiteralLike | ElementAccessExpression | BindingPattern | EntityNameExpression; - interface Declaration extends Node { - _declarationBrand: any; - } - interface NamedDeclaration extends Declaration { - readonly name?: DeclarationName; - } - interface DeclarationStatement extends NamedDeclaration, Statement { - readonly name?: Identifier | StringLiteral | NumericLiteral; - } - interface ComputedPropertyName extends Node { - readonly kind: SyntaxKind.ComputedPropertyName; - readonly parent: Declaration; - readonly expression: Expression; - } - interface PrivateIdentifier extends PrimaryExpression { - readonly kind: SyntaxKind.PrivateIdentifier; - readonly escapedText: __String; - } - interface PrivateIdentifier { - readonly text: string; - } - interface Decorator extends Node { - readonly kind: SyntaxKind.Decorator; - readonly parent: NamedDeclaration; - readonly expression: LeftHandSideExpression; - } - interface TypeParameterDeclaration extends NamedDeclaration, JSDocContainer { - readonly kind: SyntaxKind.TypeParameter; - readonly parent: DeclarationWithTypeParameterChildren | InferTypeNode; - readonly modifiers?: NodeArray; - readonly name: Identifier; - /** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */ - readonly constraint?: TypeNode; - readonly default?: TypeNode; - expression?: Expression; - } - interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { - readonly kind: SignatureDeclaration["kind"]; - readonly name?: PropertyName; - readonly typeParameters?: NodeArray | undefined; - readonly parameters: NodeArray; - readonly type?: TypeNode | undefined; - } - type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; - interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement, LocalsContainer { - readonly kind: SyntaxKind.CallSignature; - } - interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement, LocalsContainer { - readonly kind: SyntaxKind.ConstructSignature; - } - type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends NamedDeclaration, JSDocContainer { - readonly kind: SyntaxKind.VariableDeclaration; - readonly parent: VariableDeclarationList | CatchClause; - readonly name: BindingName; - readonly exclamationToken?: ExclamationToken; - readonly type?: TypeNode; - readonly initializer?: Expression; - } - interface VariableDeclarationList extends Node { - readonly kind: SyntaxKind.VariableDeclarationList; - readonly parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; - readonly declarations: NodeArray; - } - interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { - readonly kind: SyntaxKind.Parameter; - readonly parent: SignatureDeclaration; - readonly modifiers?: NodeArray; - readonly dotDotDotToken?: DotDotDotToken; - readonly name: BindingName; - readonly questionToken?: QuestionToken; - readonly type?: TypeNode; - readonly initializer?: Expression; - } - interface BindingElement extends NamedDeclaration, FlowContainer { - readonly kind: SyntaxKind.BindingElement; - readonly parent: BindingPattern; - readonly propertyName?: PropertyName; - readonly dotDotDotToken?: DotDotDotToken; - readonly name: BindingName; - readonly initializer?: Expression; - } - interface PropertySignature extends TypeElement, JSDocContainer { - readonly kind: SyntaxKind.PropertySignature; - readonly parent: TypeLiteralNode | InterfaceDeclaration; - readonly modifiers?: NodeArray; - readonly name: PropertyName; - readonly questionToken?: QuestionToken; - readonly type?: TypeNode; - } - interface PropertyDeclaration extends ClassElement, JSDocContainer { - readonly kind: SyntaxKind.PropertyDeclaration; - readonly parent: ClassLikeDeclaration; - readonly modifiers?: NodeArray; - readonly name: PropertyName; - readonly questionToken?: QuestionToken; - readonly exclamationToken?: ExclamationToken; - readonly type?: TypeNode; - readonly initializer?: Expression; - } - interface AutoAccessorPropertyDeclaration extends PropertyDeclaration { - _autoAccessorBrand: any; - } - interface ObjectLiteralElement extends NamedDeclaration { - _objectLiteralBrand: any; - readonly name?: PropertyName; - } - /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ - type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; - interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { - readonly kind: SyntaxKind.PropertyAssignment; - readonly parent: ObjectLiteralExpression; - readonly name: PropertyName; - readonly initializer: Expression; - } - interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { - readonly kind: SyntaxKind.ShorthandPropertyAssignment; - readonly parent: ObjectLiteralExpression; - readonly name: Identifier; - readonly equalsToken?: EqualsToken; - readonly objectAssignmentInitializer?: Expression; - } - interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer { - readonly kind: SyntaxKind.SpreadAssignment; - readonly parent: ObjectLiteralExpression; - readonly expression: Expression; - } - type VariableLikeDeclaration = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertyAssignment | PropertySignature | JsxAttribute | ShorthandPropertyAssignment | EnumMember | JSDocPropertyTag | JSDocParameterTag; - interface ObjectBindingPattern extends Node { - readonly kind: SyntaxKind.ObjectBindingPattern; - readonly parent: VariableDeclaration | ParameterDeclaration | BindingElement; - readonly elements: NodeArray; - } - interface ArrayBindingPattern extends Node { - readonly kind: SyntaxKind.ArrayBindingPattern; - readonly parent: VariableDeclaration | ParameterDeclaration | BindingElement; - readonly elements: NodeArray; - } - type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; - type ArrayBindingElement = BindingElement | OmittedExpression; - /** - * Several node kinds share function-like features such as a signature, - * a name, and a body. These nodes should extend FunctionLikeDeclarationBase. - * Examples: - * - FunctionDeclaration - * - MethodDeclaration - * - AccessorDeclaration - */ - interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { - _functionLikeDeclarationBrand: any; - readonly asteriskToken?: AsteriskToken | undefined; - readonly questionToken?: QuestionToken | undefined; - readonly exclamationToken?: ExclamationToken | undefined; - readonly body?: Block | Expression | undefined; - } - type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; - /** @deprecated Use SignatureDeclaration */ - type FunctionLike = SignatureDeclaration; - interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement, LocalsContainer { - readonly kind: SyntaxKind.FunctionDeclaration; - readonly modifiers?: NodeArray; - readonly name?: Identifier; - readonly body?: FunctionBody; - } - interface MethodSignature extends SignatureDeclarationBase, TypeElement, LocalsContainer { - readonly kind: SyntaxKind.MethodSignature; - readonly parent: TypeLiteralNode | InterfaceDeclaration; - readonly modifiers?: NodeArray; - readonly name: PropertyName; - } - interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer, LocalsContainer, FlowContainer { - readonly kind: SyntaxKind.MethodDeclaration; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; - readonly modifiers?: NodeArray | undefined; - readonly name: PropertyName; - readonly body?: FunctionBody | undefined; - } - interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer, LocalsContainer { - readonly kind: SyntaxKind.Constructor; - readonly parent: ClassLikeDeclaration; - readonly modifiers?: NodeArray | undefined; - readonly body?: FunctionBody | undefined; - } - /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ - interface SemicolonClassElement extends ClassElement, JSDocContainer { - readonly kind: SyntaxKind.SemicolonClassElement; - readonly parent: ClassLikeDeclaration; - } - interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer, LocalsContainer, FlowContainer { - readonly kind: SyntaxKind.GetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; - readonly modifiers?: NodeArray; - readonly name: PropertyName; - readonly body?: FunctionBody; - } - interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer, LocalsContainer, FlowContainer { - readonly kind: SyntaxKind.SetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; - readonly modifiers?: NodeArray; - readonly name: PropertyName; - readonly body?: FunctionBody; - } - type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; - interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement, LocalsContainer { - readonly kind: SyntaxKind.IndexSignature; - readonly parent: ObjectTypeDeclaration; - readonly modifiers?: NodeArray; - readonly type: TypeNode; - } - interface ClassStaticBlockDeclaration extends ClassElement, JSDocContainer, LocalsContainer { - readonly kind: SyntaxKind.ClassStaticBlockDeclaration; - readonly parent: ClassDeclaration | ClassExpression; - readonly body: Block; - } - interface TypeNode extends Node { - _typeNodeBrand: any; - } - interface KeywordTypeNode extends KeywordToken, TypeNode { - readonly kind: TKind; - } - interface ImportTypeAssertionContainer extends Node { - readonly kind: SyntaxKind.ImportTypeAssertionContainer; - readonly parent: ImportTypeNode; - readonly assertClause: AssertClause; - readonly multiLine?: boolean; - } - interface ImportTypeNode extends NodeWithTypeArguments { - readonly kind: SyntaxKind.ImportType; - readonly isTypeOf: boolean; - readonly argument: TypeNode; - readonly assertions?: ImportTypeAssertionContainer; - readonly qualifier?: EntityName; - } - interface ThisTypeNode extends TypeNode { - readonly kind: SyntaxKind.ThisType; - } - type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; - interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { - readonly kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; - readonly type: TypeNode; - } - interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase, LocalsContainer { - readonly kind: SyntaxKind.FunctionType; - } - interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase, LocalsContainer { - readonly kind: SyntaxKind.ConstructorType; - readonly modifiers?: NodeArray; - } - interface NodeWithTypeArguments extends TypeNode { - readonly typeArguments?: NodeArray; - } - type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; - interface TypeReferenceNode extends NodeWithTypeArguments { - readonly kind: SyntaxKind.TypeReference; - readonly typeName: EntityName; - } - interface TypePredicateNode extends TypeNode { - readonly kind: SyntaxKind.TypePredicate; - readonly parent: SignatureDeclaration | JSDocTypeExpression; - readonly assertsModifier?: AssertsKeyword; - readonly parameterName: Identifier | ThisTypeNode; - readonly type?: TypeNode; - } - interface TypeQueryNode extends NodeWithTypeArguments { - readonly kind: SyntaxKind.TypeQuery; - readonly exprName: EntityName; - } - interface TypeLiteralNode extends TypeNode, Declaration { - readonly kind: SyntaxKind.TypeLiteral; - readonly members: NodeArray; - } - interface ArrayTypeNode extends TypeNode { - readonly kind: SyntaxKind.ArrayType; - readonly elementType: TypeNode; - } - interface TupleTypeNode extends TypeNode { - readonly kind: SyntaxKind.TupleType; - readonly elements: NodeArray; - } - interface NamedTupleMember extends TypeNode, Declaration, JSDocContainer { - readonly kind: SyntaxKind.NamedTupleMember; - readonly dotDotDotToken?: Token; - readonly name: Identifier; - readonly questionToken?: Token; - readonly type: TypeNode; - } - interface OptionalTypeNode extends TypeNode { - readonly kind: SyntaxKind.OptionalType; - readonly type: TypeNode; - } - interface RestTypeNode extends TypeNode { - readonly kind: SyntaxKind.RestType; - readonly type: TypeNode; - } - type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode; - interface UnionTypeNode extends TypeNode { - readonly kind: SyntaxKind.UnionType; - readonly types: NodeArray; - } - interface IntersectionTypeNode extends TypeNode { - readonly kind: SyntaxKind.IntersectionType; - readonly types: NodeArray; - } - interface ConditionalTypeNode extends TypeNode, LocalsContainer { - readonly kind: SyntaxKind.ConditionalType; - readonly checkType: TypeNode; - readonly extendsType: TypeNode; - readonly trueType: TypeNode; - readonly falseType: TypeNode; - } - interface InferTypeNode extends TypeNode { - readonly kind: SyntaxKind.InferType; - readonly typeParameter: TypeParameterDeclaration; - } - interface ParenthesizedTypeNode extends TypeNode { - readonly kind: SyntaxKind.ParenthesizedType; - readonly type: TypeNode; - } - interface TypeOperatorNode extends TypeNode { - readonly kind: SyntaxKind.TypeOperator; - readonly operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword; - readonly type: TypeNode; - } - interface IndexedAccessTypeNode extends TypeNode { - readonly kind: SyntaxKind.IndexedAccessType; - readonly objectType: TypeNode; - readonly indexType: TypeNode; - } - interface MappedTypeNode extends TypeNode, Declaration, LocalsContainer { - readonly kind: SyntaxKind.MappedType; - readonly readonlyToken?: ReadonlyKeyword | PlusToken | MinusToken; - readonly typeParameter: TypeParameterDeclaration; - readonly nameType?: TypeNode; - readonly questionToken?: QuestionToken | PlusToken | MinusToken; - readonly type?: TypeNode; - /** Used only to produce grammar errors */ - readonly members?: NodeArray; - } - interface LiteralTypeNode extends TypeNode { - readonly kind: SyntaxKind.LiteralType; - readonly literal: NullLiteral | BooleanLiteral | LiteralExpression | PrefixUnaryExpression; - } - interface StringLiteral extends LiteralExpression, Declaration { - readonly kind: SyntaxKind.StringLiteral; - } - type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; - type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral | JsxNamespacedName; - interface TemplateLiteralTypeNode extends TypeNode { - kind: SyntaxKind.TemplateLiteralType; - readonly head: TemplateHead; - readonly templateSpans: NodeArray; - } - interface TemplateLiteralTypeSpan extends TypeNode { - readonly kind: SyntaxKind.TemplateLiteralTypeSpan; - readonly parent: TemplateLiteralTypeNode; - readonly type: TypeNode; - readonly literal: TemplateMiddle | TemplateTail; - } - interface Expression extends Node { - _expressionBrand: any; - } - interface OmittedExpression extends Expression { - readonly kind: SyntaxKind.OmittedExpression; - } - interface PartiallyEmittedExpression extends LeftHandSideExpression { - readonly kind: SyntaxKind.PartiallyEmittedExpression; - readonly expression: Expression; - } - interface UnaryExpression extends Expression { - _unaryExpressionBrand: any; - } - /** Deprecated, please use UpdateExpression */ - type IncrementExpression = UpdateExpression; - interface UpdateExpression extends UnaryExpression { - _updateExpressionBrand: any; - } - type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; - interface PrefixUnaryExpression extends UpdateExpression { - readonly kind: SyntaxKind.PrefixUnaryExpression; - readonly operator: PrefixUnaryOperator; - readonly operand: UnaryExpression; - } - type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; - interface PostfixUnaryExpression extends UpdateExpression { - readonly kind: SyntaxKind.PostfixUnaryExpression; - readonly operand: LeftHandSideExpression; - readonly operator: PostfixUnaryOperator; - } - interface LeftHandSideExpression extends UpdateExpression { - _leftHandSideExpressionBrand: any; - } - interface MemberExpression extends LeftHandSideExpression { - _memberExpressionBrand: any; - } - interface PrimaryExpression extends MemberExpression { - _primaryExpressionBrand: any; - } - interface NullLiteral extends PrimaryExpression { - readonly kind: SyntaxKind.NullKeyword; - } - interface TrueLiteral extends PrimaryExpression { - readonly kind: SyntaxKind.TrueKeyword; - } - interface FalseLiteral extends PrimaryExpression { - readonly kind: SyntaxKind.FalseKeyword; - } - type BooleanLiteral = TrueLiteral | FalseLiteral; - interface ThisExpression extends PrimaryExpression, FlowContainer { - readonly kind: SyntaxKind.ThisKeyword; - } - interface SuperExpression extends PrimaryExpression, FlowContainer { - readonly kind: SyntaxKind.SuperKeyword; - } - interface ImportExpression extends PrimaryExpression { - readonly kind: SyntaxKind.ImportKeyword; - } - interface DeleteExpression extends UnaryExpression { - readonly kind: SyntaxKind.DeleteExpression; - readonly expression: UnaryExpression; - } - interface TypeOfExpression extends UnaryExpression { - readonly kind: SyntaxKind.TypeOfExpression; - readonly expression: UnaryExpression; - } - interface VoidExpression extends UnaryExpression { - readonly kind: SyntaxKind.VoidExpression; - readonly expression: UnaryExpression; - } - interface AwaitExpression extends UnaryExpression { - readonly kind: SyntaxKind.AwaitExpression; - readonly expression: UnaryExpression; - } - interface YieldExpression extends Expression { - readonly kind: SyntaxKind.YieldExpression; - readonly asteriskToken?: AsteriskToken; - readonly expression?: Expression; - } - interface SyntheticExpression extends Expression { - readonly kind: SyntaxKind.SyntheticExpression; - readonly isSpread: boolean; - readonly type: Type; - readonly tupleNameSource?: ParameterDeclaration | NamedTupleMember; - } - type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; - type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; - type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; - type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; - type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; - type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; - type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; - type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; - type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; - type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; - type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; - type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; - type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; - type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; - type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; - type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.BarBarEqualsToken | SyntaxKind.AmpersandAmpersandEqualsToken | SyntaxKind.QuestionQuestionEqualsToken; - type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; - type AssignmentOperatorOrHigher = SyntaxKind.QuestionQuestionToken | LogicalOperatorOrHigher | AssignmentOperator; - type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; - type LogicalOrCoalescingAssignmentOperator = SyntaxKind.AmpersandAmpersandEqualsToken | SyntaxKind.BarBarEqualsToken | SyntaxKind.QuestionQuestionEqualsToken; - type BinaryOperatorToken = Token; - interface BinaryExpression extends Expression, Declaration, JSDocContainer { - readonly kind: SyntaxKind.BinaryExpression; - readonly left: Expression; - readonly operatorToken: BinaryOperatorToken; - readonly right: Expression; - } - type AssignmentOperatorToken = Token; - interface AssignmentExpression extends BinaryExpression { - readonly left: LeftHandSideExpression; - readonly operatorToken: TOperator; - } - interface ObjectDestructuringAssignment extends AssignmentExpression { - readonly left: ObjectLiteralExpression; - } - interface ArrayDestructuringAssignment extends AssignmentExpression { - readonly left: ArrayLiteralExpression; - } - type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; - type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | ObjectBindingOrAssignmentElement | ArrayBindingOrAssignmentElement; - type ObjectBindingOrAssignmentElement = BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment; - type ArrayBindingOrAssignmentElement = BindingElement | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; - type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; - type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; - type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; - type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; - type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; - type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; - interface ConditionalExpression extends Expression { - readonly kind: SyntaxKind.ConditionalExpression; - readonly condition: Expression; - readonly questionToken: QuestionToken; - readonly whenTrue: Expression; - readonly colonToken: ColonToken; - readonly whenFalse: Expression; - } - type FunctionBody = Block; - type ConciseBody = FunctionBody | Expression; - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer, LocalsContainer, FlowContainer { - readonly kind: SyntaxKind.FunctionExpression; - readonly modifiers?: NodeArray; - readonly name?: Identifier; - readonly body: FunctionBody; - } - interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer, LocalsContainer, FlowContainer { - readonly kind: SyntaxKind.ArrowFunction; - readonly modifiers?: NodeArray; - readonly equalsGreaterThanToken: EqualsGreaterThanToken; - readonly body: ConciseBody; - readonly name: never; - } - interface LiteralLikeNode extends Node { - text: string; - isUnterminated?: boolean; - hasExtendedUnicodeEscape?: boolean; - } - interface TemplateLiteralLikeNode extends LiteralLikeNode { - rawText?: string; - } - interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { - _literalExpressionBrand: any; - } - interface RegularExpressionLiteral extends LiteralExpression { - readonly kind: SyntaxKind.RegularExpressionLiteral; - } - interface NoSubstitutionTemplateLiteral extends LiteralExpression, TemplateLiteralLikeNode, Declaration { - readonly kind: SyntaxKind.NoSubstitutionTemplateLiteral; - } - enum TokenFlags { - None = 0, - Scientific = 16, - Octal = 32, - HexSpecifier = 64, - BinarySpecifier = 128, - OctalSpecifier = 256 - } - interface NumericLiteral extends LiteralExpression, Declaration { - readonly kind: SyntaxKind.NumericLiteral; - } - interface BigIntLiteral extends LiteralExpression { - readonly kind: SyntaxKind.BigIntLiteral; - } - type LiteralToken = NumericLiteral | BigIntLiteral | StringLiteral | JsxText | RegularExpressionLiteral | NoSubstitutionTemplateLiteral; - interface TemplateHead extends TemplateLiteralLikeNode { - readonly kind: SyntaxKind.TemplateHead; - readonly parent: TemplateExpression | TemplateLiteralTypeNode; - } - interface TemplateMiddle extends TemplateLiteralLikeNode { - readonly kind: SyntaxKind.TemplateMiddle; - readonly parent: TemplateSpan | TemplateLiteralTypeSpan; - } - interface TemplateTail extends TemplateLiteralLikeNode { - readonly kind: SyntaxKind.TemplateTail; - readonly parent: TemplateSpan | TemplateLiteralTypeSpan; - } - type PseudoLiteralToken = TemplateHead | TemplateMiddle | TemplateTail; - type TemplateLiteralToken = NoSubstitutionTemplateLiteral | PseudoLiteralToken; - interface TemplateExpression extends PrimaryExpression { - readonly kind: SyntaxKind.TemplateExpression; - readonly head: TemplateHead; - readonly templateSpans: NodeArray; - } - type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; - interface TemplateSpan extends Node { - readonly kind: SyntaxKind.TemplateSpan; - readonly parent: TemplateExpression; - readonly expression: Expression; - readonly literal: TemplateMiddle | TemplateTail; - } - interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer { - readonly kind: SyntaxKind.ParenthesizedExpression; - readonly expression: Expression; - } - interface ArrayLiteralExpression extends PrimaryExpression { - readonly kind: SyntaxKind.ArrayLiteralExpression; - readonly elements: NodeArray; - } - interface SpreadElement extends Expression { - readonly kind: SyntaxKind.SpreadElement; - readonly parent: ArrayLiteralExpression | CallExpression | NewExpression; - readonly expression: Expression; - } - /** - * This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to - * ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be - * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type - * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) - */ - interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { - readonly properties: NodeArray; - } - interface ObjectLiteralExpression extends ObjectLiteralExpressionBase, JSDocContainer { - readonly kind: SyntaxKind.ObjectLiteralExpression; - } - type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; - type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - type AccessExpression = PropertyAccessExpression | ElementAccessExpression; - interface PropertyAccessExpression extends MemberExpression, NamedDeclaration, JSDocContainer, FlowContainer { - readonly kind: SyntaxKind.PropertyAccessExpression; - readonly expression: LeftHandSideExpression; - readonly questionDotToken?: QuestionDotToken; - readonly name: MemberName; - } - interface PropertyAccessChain extends PropertyAccessExpression { - _optionalChainBrand: any; - readonly name: MemberName; - } - interface SuperPropertyAccessExpression extends PropertyAccessExpression { - readonly expression: SuperExpression; - } - /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ - interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { - _propertyAccessExpressionLikeQualifiedNameBrand?: any; - readonly expression: EntityNameExpression; - readonly name: Identifier; - } - interface ElementAccessExpression extends MemberExpression, Declaration, JSDocContainer, FlowContainer { - readonly kind: SyntaxKind.ElementAccessExpression; - readonly expression: LeftHandSideExpression; - readonly questionDotToken?: QuestionDotToken; - readonly argumentExpression: Expression; - } - interface ElementAccessChain extends ElementAccessExpression { - _optionalChainBrand: any; - } - interface SuperElementAccessExpression extends ElementAccessExpression { - readonly expression: SuperExpression; - } - type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; - interface CallExpression extends LeftHandSideExpression, Declaration { - readonly kind: SyntaxKind.CallExpression; - readonly expression: LeftHandSideExpression; - readonly questionDotToken?: QuestionDotToken; - readonly typeArguments?: NodeArray; - readonly arguments: NodeArray; - } - interface CallChain extends CallExpression { - _optionalChainBrand: any; - } - type OptionalChain = PropertyAccessChain | ElementAccessChain | CallChain | NonNullChain; - interface SuperCall extends CallExpression { - readonly expression: SuperExpression; - } - interface ImportCall extends CallExpression { - readonly expression: ImportExpression; - } - interface ExpressionWithTypeArguments extends MemberExpression, NodeWithTypeArguments { - readonly kind: SyntaxKind.ExpressionWithTypeArguments; - readonly expression: LeftHandSideExpression; - } - interface NewExpression extends PrimaryExpression, Declaration { - readonly kind: SyntaxKind.NewExpression; - readonly expression: LeftHandSideExpression; - readonly typeArguments?: NodeArray; - readonly arguments?: NodeArray; - } - interface TaggedTemplateExpression extends MemberExpression { - readonly kind: SyntaxKind.TaggedTemplateExpression; - readonly tag: LeftHandSideExpression; - readonly typeArguments?: NodeArray; - readonly template: TemplateLiteral; - } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement; - interface AsExpression extends Expression { - readonly kind: SyntaxKind.AsExpression; - readonly expression: Expression; - readonly type: TypeNode; - } - interface TypeAssertion extends UnaryExpression { - readonly kind: SyntaxKind.TypeAssertionExpression; - readonly type: TypeNode; - readonly expression: UnaryExpression; - } - interface SatisfiesExpression extends Expression { - readonly kind: SyntaxKind.SatisfiesExpression; - readonly expression: Expression; - readonly type: TypeNode; - } - type AssertionExpression = TypeAssertion | AsExpression; - interface NonNullExpression extends LeftHandSideExpression { - readonly kind: SyntaxKind.NonNullExpression; - readonly expression: Expression; - } - interface NonNullChain extends NonNullExpression { - _optionalChainBrand: any; - } - interface MetaProperty extends PrimaryExpression, FlowContainer { - readonly kind: SyntaxKind.MetaProperty; - readonly keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword; - readonly name: Identifier; - } - interface JsxElement extends PrimaryExpression { - readonly kind: SyntaxKind.JsxElement; - readonly openingElement: JsxOpeningElement; - readonly children: NodeArray; - readonly closingElement: JsxClosingElement; - } - type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; - type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; - type JsxAttributeName = Identifier | JsxNamespacedName; - type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess | JsxNamespacedName; - interface JsxTagNamePropertyAccess extends PropertyAccessExpression { - readonly expression: Identifier | ThisExpression | JsxTagNamePropertyAccess; - } - interface JsxAttributes extends PrimaryExpression, Declaration { - readonly properties: NodeArray; - readonly kind: SyntaxKind.JsxAttributes; - readonly parent: JsxOpeningLikeElement; - } - interface JsxNamespacedName extends Node { - readonly kind: SyntaxKind.JsxNamespacedName; - readonly name: Identifier; - readonly namespace: Identifier; - } - interface JsxOpeningElement extends Expression { - readonly kind: SyntaxKind.JsxOpeningElement; - readonly parent: JsxElement; - readonly tagName: JsxTagNameExpression; - readonly typeArguments?: NodeArray; - readonly attributes: JsxAttributes; - } - interface JsxSelfClosingElement extends PrimaryExpression { - readonly kind: SyntaxKind.JsxSelfClosingElement; - readonly tagName: JsxTagNameExpression; - readonly typeArguments?: NodeArray; - readonly attributes: JsxAttributes; - } - interface JsxFragment extends PrimaryExpression { - readonly kind: SyntaxKind.JsxFragment; - readonly openingFragment: JsxOpeningFragment; - readonly children: NodeArray; - readonly closingFragment: JsxClosingFragment; - } - interface JsxOpeningFragment extends Expression { - readonly kind: SyntaxKind.JsxOpeningFragment; - readonly parent: JsxFragment; - } - interface JsxClosingFragment extends Expression { - readonly kind: SyntaxKind.JsxClosingFragment; - readonly parent: JsxFragment; - } - interface JsxAttribute extends Declaration { - readonly kind: SyntaxKind.JsxAttribute; - readonly parent: JsxAttributes; - readonly name: JsxAttributeName; - readonly initializer?: JsxAttributeValue; - } - type JsxAttributeValue = StringLiteral | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - interface JsxSpreadAttribute extends ObjectLiteralElement { - readonly kind: SyntaxKind.JsxSpreadAttribute; - readonly parent: JsxAttributes; - readonly expression: Expression; - } - interface JsxClosingElement extends Node { - readonly kind: SyntaxKind.JsxClosingElement; - readonly parent: JsxElement; - readonly tagName: JsxTagNameExpression; - } - interface JsxExpression extends Expression { - readonly kind: SyntaxKind.JsxExpression; - readonly parent: JsxElement | JsxFragment | JsxAttributeLike; - readonly dotDotDotToken?: Token; - readonly expression?: Expression; - } - interface JsxText extends LiteralLikeNode { - readonly kind: SyntaxKind.JsxText; - readonly parent: JsxElement | JsxFragment; - readonly containsOnlyTriviaWhiteSpaces: boolean; - } - type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; - interface Statement extends Node, JSDocContainer { - _statementBrand: any; - } - interface NotEmittedStatement extends Statement { - readonly kind: SyntaxKind.NotEmittedStatement; - } - /** - * A list of comma-separated expressions. This node is only created by transformations. - */ - interface CommaListExpression extends Expression { - readonly kind: SyntaxKind.CommaListExpression; - readonly elements: NodeArray; - } - interface EmptyStatement extends Statement { - readonly kind: SyntaxKind.EmptyStatement; - } - interface DebuggerStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.DebuggerStatement; - } - interface MissingDeclaration extends DeclarationStatement, PrimaryExpression { - readonly kind: SyntaxKind.MissingDeclaration; - readonly name?: Identifier; - } - type BlockLike = SourceFile | Block | ModuleBlock | CaseOrDefaultClause; - interface Block extends Statement, LocalsContainer { - readonly kind: SyntaxKind.Block; - readonly statements: NodeArray; - } - interface VariableStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.VariableStatement; - readonly modifiers?: NodeArray; - readonly declarationList: VariableDeclarationList; - } - interface ExpressionStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.ExpressionStatement; - readonly expression: Expression; - } - interface IfStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.IfStatement; - readonly expression: Expression; - readonly thenStatement: Statement; - readonly elseStatement?: Statement; - } - interface IterationStatement extends Statement { - readonly statement: Statement; - } - interface DoStatement extends IterationStatement, FlowContainer { - readonly kind: SyntaxKind.DoStatement; - readonly expression: Expression; - } - interface WhileStatement extends IterationStatement, FlowContainer { - readonly kind: SyntaxKind.WhileStatement; - readonly expression: Expression; - } - type ForInitializer = VariableDeclarationList | Expression; - interface ForStatement extends IterationStatement, LocalsContainer, FlowContainer { - readonly kind: SyntaxKind.ForStatement; - readonly initializer?: ForInitializer; - readonly condition?: Expression; - readonly incrementor?: Expression; - } - type ForInOrOfStatement = ForInStatement | ForOfStatement; - interface ForInStatement extends IterationStatement, LocalsContainer, FlowContainer { - readonly kind: SyntaxKind.ForInStatement; - readonly initializer: ForInitializer; - readonly expression: Expression; - } - interface ForOfStatement extends IterationStatement, LocalsContainer, FlowContainer { - readonly kind: SyntaxKind.ForOfStatement; - readonly awaitModifier?: AwaitKeyword; - readonly initializer: ForInitializer; - readonly expression: Expression; - } - interface BreakStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.BreakStatement; - readonly label?: Identifier; - } - interface ContinueStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.ContinueStatement; - readonly label?: Identifier; - } - type BreakOrContinueStatement = BreakStatement | ContinueStatement; - interface ReturnStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.ReturnStatement; - readonly expression?: Expression; - } - interface WithStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.WithStatement; - readonly expression: Expression; - readonly statement: Statement; - } - interface SwitchStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.SwitchStatement; - readonly expression: Expression; - readonly caseBlock: CaseBlock; - possiblyExhaustive?: boolean; - } - interface CaseBlock extends Node, LocalsContainer { - readonly kind: SyntaxKind.CaseBlock; - readonly parent: SwitchStatement; - readonly clauses: NodeArray; - } - interface CaseClause extends Node, JSDocContainer { - readonly kind: SyntaxKind.CaseClause; - readonly parent: CaseBlock; - readonly expression: Expression; - readonly statements: NodeArray; - } - interface DefaultClause extends Node { - readonly kind: SyntaxKind.DefaultClause; - readonly parent: CaseBlock; - readonly statements: NodeArray; - } - type CaseOrDefaultClause = CaseClause | DefaultClause; - interface LabeledStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.LabeledStatement; - readonly label: Identifier; - readonly statement: Statement; - } - interface ThrowStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.ThrowStatement; - readonly expression: Expression; - } - interface TryStatement extends Statement, FlowContainer { - readonly kind: SyntaxKind.TryStatement; - readonly tryBlock: Block; - readonly catchClause?: CatchClause; - readonly finallyBlock?: Block; - } - interface CatchClause extends Node, LocalsContainer { - readonly kind: SyntaxKind.CatchClause; - readonly parent: TryStatement; - readonly variableDeclaration?: VariableDeclaration; - readonly block: Block; - } - type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; - type DeclarationWithTypeParameters = DeclarationWithTypeParameterChildren | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; - type DeclarationWithTypeParameterChildren = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; - interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { - readonly kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; - readonly name?: Identifier; - readonly typeParameters?: NodeArray; - readonly heritageClauses?: NodeArray; - readonly members: NodeArray; - } - interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { - readonly kind: SyntaxKind.ClassDeclaration; - readonly modifiers?: NodeArray; - /** May be undefined in `export default class { ... }`. */ - readonly name?: Identifier; - } - interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { - readonly kind: SyntaxKind.ClassExpression; - readonly modifiers?: NodeArray; - } - type ClassLikeDeclaration = ClassDeclaration | ClassExpression; - interface ClassElement extends NamedDeclaration { - _classElementBrand: any; - readonly name?: PropertyName; - } - interface TypeElement extends NamedDeclaration { - _typeElementBrand: any; - readonly name?: PropertyName; - readonly questionToken?: QuestionToken | undefined; - } - interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { - readonly kind: SyntaxKind.InterfaceDeclaration; - readonly modifiers?: NodeArray; - readonly name: Identifier; - readonly typeParameters?: NodeArray; - readonly heritageClauses?: NodeArray; - readonly members: NodeArray; - } - interface HeritageClause extends Node { - readonly kind: SyntaxKind.HeritageClause; - readonly parent: InterfaceDeclaration | ClassLikeDeclaration; - readonly token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; - readonly types: NodeArray; - } - interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer, LocalsContainer { - readonly kind: SyntaxKind.TypeAliasDeclaration; - readonly modifiers?: NodeArray; - readonly name: Identifier; - readonly typeParameters?: NodeArray; - readonly type: TypeNode; - } - interface EnumMember extends NamedDeclaration, JSDocContainer { - readonly kind: SyntaxKind.EnumMember; - readonly parent: EnumDeclaration; - readonly name: PropertyName; - readonly initializer?: Expression; - } - interface EnumDeclaration extends DeclarationStatement, JSDocContainer { - readonly kind: SyntaxKind.EnumDeclaration; - readonly modifiers?: NodeArray; - readonly name: Identifier; - readonly members: NodeArray; - } - type ModuleName = Identifier | StringLiteral; - type ModuleBody = NamespaceBody | JSDocNamespaceBody; - interface ModuleDeclaration extends DeclarationStatement, JSDocContainer, LocalsContainer { - readonly kind: SyntaxKind.ModuleDeclaration; - readonly parent: ModuleBody | SourceFile; - readonly modifiers?: NodeArray; - readonly name: ModuleName; - readonly body?: ModuleBody | JSDocNamespaceDeclaration; - } - type NamespaceBody = ModuleBlock | NamespaceDeclaration; - interface NamespaceDeclaration extends ModuleDeclaration { - readonly name: Identifier; - readonly body: NamespaceBody; - } - type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; - interface JSDocNamespaceDeclaration extends ModuleDeclaration { - readonly name: Identifier; - readonly body?: JSDocNamespaceBody; - } - interface ModuleBlock extends Node, Statement { - readonly kind: SyntaxKind.ModuleBlock; - readonly parent: ModuleDeclaration; - readonly statements: NodeArray; - } - type ModuleReference = EntityName | ExternalModuleReference; - /** - * One of: - * - import x = require("mod"); - * - import x = M.x; - */ - interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { - readonly kind: SyntaxKind.ImportEqualsDeclaration; - readonly parent: SourceFile | ModuleBlock; - readonly modifiers?: NodeArray; - readonly name: Identifier; - readonly isTypeOnly: boolean; - readonly moduleReference: ModuleReference; - } - interface ExternalModuleReference extends Node { - readonly kind: SyntaxKind.ExternalModuleReference; - readonly parent: ImportEqualsDeclaration; - readonly expression: Expression; - } - interface ImportDeclaration extends Statement { - readonly kind: SyntaxKind.ImportDeclaration; - readonly parent: SourceFile | ModuleBlock; - readonly modifiers?: NodeArray; - readonly importClause?: ImportClause; - /** If this is not a StringLiteral it will be a grammar error. */ - readonly moduleSpecifier: Expression; - readonly assertClause?: AssertClause; - } - type NamedImportBindings = NamespaceImport | NamedImports; - type NamedExportBindings = NamespaceExport | NamedExports; - interface ImportClause extends NamedDeclaration { - readonly kind: SyntaxKind.ImportClause; - readonly parent: ImportDeclaration; - readonly isTypeOnly: boolean; - readonly name?: Identifier; - readonly namedBindings?: NamedImportBindings; - } - type AssertionKey = Identifier | StringLiteral; - interface AssertEntry extends Node { - readonly kind: SyntaxKind.AssertEntry; - readonly parent: AssertClause; - readonly name: AssertionKey; - readonly value: Expression; - } - interface AssertClause extends Node { - readonly kind: SyntaxKind.AssertClause; - readonly parent: ImportDeclaration | ExportDeclaration; - readonly elements: NodeArray; - readonly multiLine?: boolean; - } - interface NamespaceImport extends NamedDeclaration { - readonly kind: SyntaxKind.NamespaceImport; - readonly parent: ImportClause; - readonly name: Identifier; - } - interface NamespaceExport extends NamedDeclaration { - readonly kind: SyntaxKind.NamespaceExport; - readonly parent: ExportDeclaration; - readonly name: Identifier; - } - interface NamespaceExportDeclaration extends DeclarationStatement, JSDocContainer { - readonly kind: SyntaxKind.NamespaceExportDeclaration; - readonly name: Identifier; - } - interface ExportDeclaration extends DeclarationStatement, JSDocContainer { - readonly kind: SyntaxKind.ExportDeclaration; - readonly parent: SourceFile | ModuleBlock; - readonly modifiers?: NodeArray; - readonly isTypeOnly: boolean; - /** Will not be assigned in the case of `export * from "foo";` */ - readonly exportClause?: NamedExportBindings; - /** If this is not a StringLiteral it will be a grammar error. */ - readonly moduleSpecifier?: Expression; - readonly assertClause?: AssertClause; - } - interface NamedImports extends Node { - readonly kind: SyntaxKind.NamedImports; - readonly parent: ImportClause; - readonly elements: NodeArray; - } - interface NamedExports extends Node { - readonly kind: SyntaxKind.NamedExports; - readonly parent: ExportDeclaration; - readonly elements: NodeArray; - } - type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends NamedDeclaration { - readonly kind: SyntaxKind.ImportSpecifier; - readonly parent: NamedImports; - readonly propertyName?: Identifier; - readonly name: Identifier; - readonly isTypeOnly: boolean; - } - interface ExportSpecifier extends NamedDeclaration, JSDocContainer { - readonly kind: SyntaxKind.ExportSpecifier; - readonly parent: NamedExports; - readonly isTypeOnly: boolean; - readonly propertyName?: Identifier; - readonly name: Identifier; - } - type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; - type TypeOnlyCompatibleAliasDeclaration = ImportClause | ImportEqualsDeclaration | NamespaceImport | ImportOrExportSpecifier | ExportDeclaration | NamespaceExport; - type TypeOnlyImportDeclaration = ImportClause & { - readonly isTypeOnly: true; - readonly name: Identifier; - } | ImportEqualsDeclaration & { - readonly isTypeOnly: true; - } | NamespaceImport & { - readonly parent: ImportClause & { - readonly isTypeOnly: true; - }; - } | ImportSpecifier & ({ - readonly isTypeOnly: true; - } | { - readonly parent: NamedImports & { - readonly parent: ImportClause & { - readonly isTypeOnly: true; - }; - }; - }); - type TypeOnlyExportDeclaration = ExportSpecifier & ({ - readonly isTypeOnly: true; - } | { - readonly parent: NamedExports & { - readonly parent: ExportDeclaration & { - readonly isTypeOnly: true; - }; - }; - }) | ExportDeclaration & { - readonly isTypeOnly: true; - readonly moduleSpecifier: Expression; - } | NamespaceExport & { - readonly parent: ExportDeclaration & { - readonly isTypeOnly: true; - readonly moduleSpecifier: Expression; - }; - }; - type TypeOnlyAliasDeclaration = TypeOnlyImportDeclaration | TypeOnlyExportDeclaration; - /** - * This is either an `export =` or an `export default` declaration. - * Unless `isExportEquals` is set, this node was parsed as an `export default`. - */ - interface ExportAssignment extends DeclarationStatement, JSDocContainer { - readonly kind: SyntaxKind.ExportAssignment; - readonly parent: SourceFile; - readonly modifiers?: NodeArray; - readonly isExportEquals?: boolean; - readonly expression: Expression; - } - interface FileReference extends TextRange { - fileName: string; - resolutionMode?: ResolutionMode; - } - interface CheckJsDirective extends TextRange { - enabled: boolean; - } - type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia; - interface CommentRange extends TextRange { - hasTrailingNewLine?: boolean; - kind: CommentKind; - } - interface SynthesizedComment extends CommentRange { - text: string; - pos: -1; - end: -1; - hasLeadingNewline?: boolean; - } - interface JSDocTypeExpression extends TypeNode { - readonly kind: SyntaxKind.JSDocTypeExpression; - readonly type: TypeNode; - } - interface JSDocNameReference extends Node { - readonly kind: SyntaxKind.JSDocNameReference; - readonly name: EntityName | JSDocMemberName; - } - /** Class#method reference in JSDoc */ - interface JSDocMemberName extends Node { - readonly kind: SyntaxKind.JSDocMemberName; - readonly left: EntityName | JSDocMemberName; - readonly right: Identifier; - } - interface JSDocType extends TypeNode { - _jsDocTypeBrand: any; - } - interface JSDocAllType extends JSDocType { - readonly kind: SyntaxKind.JSDocAllType; - } - interface JSDocUnknownType extends JSDocType { - readonly kind: SyntaxKind.JSDocUnknownType; - } - interface JSDocNonNullableType extends JSDocType { - readonly kind: SyntaxKind.JSDocNonNullableType; - readonly type: TypeNode; - readonly postfix: boolean; - } - interface JSDocNullableType extends JSDocType { - readonly kind: SyntaxKind.JSDocNullableType; - readonly type: TypeNode; - readonly postfix: boolean; - } - interface JSDocOptionalType extends JSDocType { - readonly kind: SyntaxKind.JSDocOptionalType; - readonly type: TypeNode; - } - interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase, LocalsContainer { - readonly kind: SyntaxKind.JSDocFunctionType; - } - interface JSDocVariadicType extends JSDocType { - readonly kind: SyntaxKind.JSDocVariadicType; - readonly type: TypeNode; - } - interface JSDocNamepathType extends JSDocType { - readonly kind: SyntaxKind.JSDocNamepathType; - readonly type: TypeNode; - } - type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; - interface JSDoc extends Node { - readonly kind: SyntaxKind.JSDoc; - readonly parent: HasJSDoc; - readonly tags?: NodeArray; - readonly comment?: string | NodeArray; - } - interface JSDocTag extends Node { - readonly parent: JSDoc | JSDocTypeLiteral; - readonly tagName: Identifier; - readonly comment?: string | NodeArray; - } - interface JSDocLink extends Node { - readonly kind: SyntaxKind.JSDocLink; - readonly name?: EntityName | JSDocMemberName; - text: string; - } - interface JSDocLinkCode extends Node { - readonly kind: SyntaxKind.JSDocLinkCode; - readonly name?: EntityName | JSDocMemberName; - text: string; - } - interface JSDocLinkPlain extends Node { - readonly kind: SyntaxKind.JSDocLinkPlain; - readonly name?: EntityName | JSDocMemberName; - text: string; - } - type JSDocComment = JSDocText | JSDocLink | JSDocLinkCode | JSDocLinkPlain; - interface JSDocText extends Node { - readonly kind: SyntaxKind.JSDocText; - text: string; - } - interface JSDocUnknownTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocTag; - } - /** - * Note that `@extends` is a synonym of `@augments`. - * Both tags are represented by this interface. - */ - interface JSDocAugmentsTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocAugmentsTag; - readonly class: ExpressionWithTypeArguments & { - readonly expression: Identifier | PropertyAccessEntityNameExpression; - }; - } - interface JSDocImplementsTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocImplementsTag; - readonly class: ExpressionWithTypeArguments & { - readonly expression: Identifier | PropertyAccessEntityNameExpression; - }; - } - interface JSDocAuthorTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocAuthorTag; - } - interface JSDocDeprecatedTag extends JSDocTag { - kind: SyntaxKind.JSDocDeprecatedTag; - } - interface JSDocClassTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocClassTag; - } - interface JSDocPublicTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocPublicTag; - } - interface JSDocPrivateTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocPrivateTag; - } - interface JSDocProtectedTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocProtectedTag; - } - interface JSDocReadonlyTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocReadonlyTag; - } - interface JSDocOverrideTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocOverrideTag; - } - interface JSDocEnumTag extends JSDocTag, Declaration, LocalsContainer { - readonly kind: SyntaxKind.JSDocEnumTag; - readonly parent: JSDoc; - readonly typeExpression: JSDocTypeExpression; - } - interface JSDocThisTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocThisTag; - readonly typeExpression: JSDocTypeExpression; - } - interface JSDocTemplateTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocTemplateTag; - readonly constraint: JSDocTypeExpression | undefined; - readonly typeParameters: NodeArray; - } - interface JSDocSeeTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocSeeTag; - readonly name?: JSDocNameReference; - } - interface JSDocReturnTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocReturnTag; - readonly typeExpression?: JSDocTypeExpression; - } - interface JSDocTypeTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocTypeTag; - readonly typeExpression: JSDocTypeExpression; - } - interface JSDocTypedefTag extends JSDocTag, NamedDeclaration, LocalsContainer { - readonly kind: SyntaxKind.JSDocTypedefTag; - readonly parent: JSDoc; - readonly fullName?: JSDocNamespaceDeclaration | Identifier; - readonly name?: Identifier; - readonly typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; - } - interface JSDocCallbackTag extends JSDocTag, NamedDeclaration, LocalsContainer { - readonly kind: SyntaxKind.JSDocCallbackTag; - readonly parent: JSDoc; - readonly fullName?: JSDocNamespaceDeclaration | Identifier; - readonly name?: Identifier; - readonly typeExpression: JSDocSignature; - } - interface JSDocOverloadTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocOverloadTag; - readonly parent: JSDoc; - readonly typeExpression: JSDocSignature; - } - interface JSDocThrowsTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocThrowsTag; - readonly typeExpression?: JSDocTypeExpression; - } - interface JSDocSignature extends JSDocType, Declaration, JSDocContainer, LocalsContainer { - readonly kind: SyntaxKind.JSDocSignature; - readonly typeParameters?: readonly JSDocTemplateTag[]; - readonly parameters: readonly JSDocParameterTag[]; - readonly type: JSDocReturnTag | undefined; - } - interface JSDocPropertyLikeTag extends JSDocTag, Declaration { - readonly parent: JSDoc; - readonly name: EntityName; - readonly typeExpression?: JSDocTypeExpression; - /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ - readonly isNameFirst: boolean; - readonly isBracketed: boolean; - } - interface JSDocPropertyTag extends JSDocPropertyLikeTag { - readonly kind: SyntaxKind.JSDocPropertyTag; - } - interface JSDocParameterTag extends JSDocPropertyLikeTag { - readonly kind: SyntaxKind.JSDocParameterTag; - } - interface JSDocTypeLiteral extends JSDocType, Declaration { - readonly kind: SyntaxKind.JSDocTypeLiteral; - readonly jsDocPropertyTags?: readonly JSDocPropertyLikeTag[]; - /** If true, then this type literal represents an *array* of its type. */ - readonly isArrayType: boolean; - } - interface JSDocSatisfiesTag extends JSDocTag { - readonly kind: SyntaxKind.JSDocSatisfiesTag; - readonly typeExpression: JSDocTypeExpression; - } - enum FlowFlags { - Unreachable = 1, - Start = 2, - BranchLabel = 4, - LoopLabel = 8, - Assignment = 16, - TrueCondition = 32, - FalseCondition = 64, - SwitchClause = 128, - ArrayMutation = 256, - Call = 512, - ReduceLabel = 1024, - Referenced = 2048, - Shared = 4096, - Label = 12, - Condition = 96 - } - type FlowNode = FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation | FlowCall | FlowReduceLabel; - interface FlowNodeBase { - flags: FlowFlags; - id?: number; - } - interface FlowStart extends FlowNodeBase { - node?: FunctionExpression | ArrowFunction | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration; - } - interface FlowLabel extends FlowNodeBase { - antecedents: FlowNode[] | undefined; - } - interface FlowAssignment extends FlowNodeBase { - node: Expression | VariableDeclaration | BindingElement; - antecedent: FlowNode; - } - interface FlowCall extends FlowNodeBase { - node: CallExpression; - antecedent: FlowNode; - } - interface FlowCondition extends FlowNodeBase { - node: Expression; - antecedent: FlowNode; - } - interface FlowSwitchClause extends FlowNodeBase { - switchStatement: SwitchStatement; - clauseStart: number; - clauseEnd: number; - antecedent: FlowNode; - } - interface FlowArrayMutation extends FlowNodeBase { - node: CallExpression | BinaryExpression; - antecedent: FlowNode; - } - interface FlowReduceLabel extends FlowNodeBase { - target: FlowLabel; - antecedents: FlowNode[]; - antecedent: FlowNode; - } - type FlowType = Type | IncompleteType; - interface IncompleteType { - flags: TypeFlags | 0; - type: Type; - } - interface AmdDependency { - path: string; - name?: string; - } - /** - * Subset of properties from SourceFile that are used in multiple utility functions - */ - interface SourceFileLike { - readonly text: string; - } - interface SourceFileLike { - getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - } - type ResolutionMode = ModuleKind.ESNext | ModuleKind.CommonJS | undefined; - interface SourceFile extends Declaration, LocalsContainer { - readonly kind: SyntaxKind.SourceFile; - readonly statements: NodeArray; - readonly endOfFileToken: Token; - fileName: string; - text: string; - amdDependencies: readonly AmdDependency[]; - moduleName?: string; - referencedFiles: readonly FileReference[]; - typeReferenceDirectives: readonly FileReference[]; - libReferenceDirectives: readonly FileReference[]; - languageVariant: LanguageVariant; - isDeclarationFile: boolean; - /** - * lib.d.ts should have a reference comment like - * - * /// - * - * If any other file has this comment, it signals not to include lib.d.ts - * because this containing file is intended to act as a default library. - */ - hasNoDefaultLib: boolean; - languageVersion: ScriptTarget; - /** - * When `module` is `Node16` or `NodeNext`, this field controls whether the - * source file in question is an ESNext-output-format file, or a CommonJS-output-format - * module. This is derived by the module resolver as it looks up the file, since - * it is derived from either the file extension of the module, or the containing - * `package.json` context, and affects both checking and emit. - * - * It is _public_ so that (pre)transformers can set this field, - * since it switches the builtin `node` module transform. Generally speaking, if unset, - * the field is treated as though it is `ModuleKind.CommonJS`. - * - * Note that this field is only set by the module resolution process when - * `moduleResolution` is `Node16` or `NodeNext`, which is implied by the `module` setting - * of `Node16` or `NodeNext`, respectively, but may be overriden (eg, by a `moduleResolution` - * of `node`). If so, this field will be unset and source files will be considered to be - * CommonJS-output-format by the node module transformer and type checker, regardless of extension or context. - */ - impliedNodeFormat?: ResolutionMode; - } - interface SourceFile { - getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - getLineEndOfPosition(pos: number): number; - getLineStarts(): readonly number[]; - getPositionOfLineAndCharacter(line: number, character: number): number; - update(newText: string, textChangeRange: TextChangeRange): SourceFile; - } - interface Bundle extends Node { - readonly kind: SyntaxKind.Bundle; - /** @deprecated */ readonly prepends: readonly (InputFiles | UnparsedSource)[]; - readonly sourceFiles: readonly SourceFile[]; - } - /** @deprecated */ - interface InputFiles extends Node { - readonly kind: SyntaxKind.InputFiles; - javascriptPath?: string; - javascriptText: string; - javascriptMapPath?: string; - javascriptMapText?: string; - declarationPath?: string; - declarationText: string; - declarationMapPath?: string; - declarationMapText?: string; - } - /** @deprecated */ - interface UnparsedSource extends Node { - readonly kind: SyntaxKind.UnparsedSource; - fileName: string; - text: string; - readonly prologues: readonly UnparsedPrologue[]; - helpers: readonly UnscopedEmitHelper[] | undefined; - referencedFiles: readonly FileReference[]; - typeReferenceDirectives: readonly FileReference[] | undefined; - libReferenceDirectives: readonly FileReference[]; - hasNoDefaultLib?: boolean; - sourceMapPath?: string; - sourceMapText?: string; - readonly syntheticReferences?: readonly UnparsedSyntheticReference[]; - readonly texts: readonly UnparsedSourceText[]; - } - /** @deprecated */ - type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike; - /** @deprecated */ - type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference; - /** @deprecated */ - interface UnparsedSection extends Node { - readonly kind: SyntaxKind; - readonly parent: UnparsedSource; - readonly data?: string; - } - /** @deprecated */ - interface UnparsedPrologue extends UnparsedSection { - readonly kind: SyntaxKind.UnparsedPrologue; - readonly parent: UnparsedSource; - readonly data: string; - } - /** @deprecated */ - interface UnparsedPrepend extends UnparsedSection { - readonly kind: SyntaxKind.UnparsedPrepend; - readonly parent: UnparsedSource; - readonly data: string; - readonly texts: readonly UnparsedTextLike[]; - } - /** @deprecated */ - interface UnparsedTextLike extends UnparsedSection { - readonly kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText; - readonly parent: UnparsedSource; - } - /** @deprecated */ - interface UnparsedSyntheticReference extends UnparsedSection { - readonly kind: SyntaxKind.UnparsedSyntheticReference; - readonly parent: UnparsedSource; - } - interface JsonSourceFile extends SourceFile { - readonly statements: NodeArray; - } - interface TsConfigSourceFile extends JsonSourceFile { - extendedSourceFiles?: string[]; - } - interface JsonMinusNumericLiteral extends PrefixUnaryExpression { - readonly kind: SyntaxKind.PrefixUnaryExpression; - readonly operator: SyntaxKind.MinusToken; - readonly operand: NumericLiteral; - } - type JsonObjectExpression = ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral; - interface JsonObjectExpressionStatement extends ExpressionStatement { - readonly expression: JsonObjectExpression; - } - interface ScriptReferenceHost { - getCompilerOptions(): CompilerOptions; - getSourceFile(fileName: string): SourceFile | undefined; - getSourceFileByPath(path: Path): SourceFile | undefined; - getCurrentDirectory(): string; - } - interface ParseConfigHost extends ModuleResolutionHost { - useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): readonly string[]; - /** - * Gets a value indicating whether the specified path exists and is a file. - * @param path The path to test. - */ - fileExists(path: string): boolean; - readFile(path: string): string | undefined; - trace?(s: string): void; - } - /** - * Branded string for keeping track of when we've turned an ambiguous path - * specified like "./blah" to an absolute path to an actual - * tsconfig file, e.g. "/root/blah/tsconfig.json" - */ - type ResolvedConfigFileName = string & { - _isResolvedConfigFileName: never; - }; - interface WriteFileCallbackData { - } - type WriteFileCallback = (fileName: string, text: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: readonly SourceFile[], data?: WriteFileCallbackData) => void; - class OperationCanceledException { - } - interface CancellationToken { - isCancellationRequested(): boolean; - /** @throws OperationCanceledException if isCancellationRequested is true */ - throwIfCancellationRequested(): void; - } - interface Program extends ScriptReferenceHost { - getCurrentDirectory(): string; - /** - * Get a list of root file names that were passed to a 'createProgram' - */ - getRootFileNames(): readonly string[]; - /** - * Get a list of files in the program - */ - getSourceFiles(): readonly SourceFile[]; - /** - * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then - * the JavaScript and declaration files will be produced for all the files in this program. - * If targetSourceFile is specified, then only the JavaScript and declaration for that - * specific file will be generated. - * - * If writeFile is not specified then the writeFile callback from the compiler host will be - * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter - * will be invoked when writing the JavaScript and declaration files. - */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; - /** The first time this is called, it will return global diagnostics (no location). */ - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; - getConfigFileParsingDiagnostics(): readonly Diagnostic[]; - /** - * Gets a type checker that can be used to semantically analyze source files in the program. - */ - getTypeChecker(): TypeChecker; - getNodeCount(): number; - getIdentifierCount(): number; - getSymbolCount(): number; - getTypeCount(): number; - getInstantiationCount(): number; - getRelationCacheSizes(): { - assignable: number; - identity: number; - subtype: number; - strictSubtype: number; - }; - isSourceFileFromExternalLibrary(file: SourceFile): boolean; - isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): readonly ProjectReference[] | undefined; - getResolvedProjectReferences(): readonly (ResolvedProjectReference | undefined)[] | undefined; - } - interface ResolvedProjectReference { - commandLine: ParsedCommandLine; - sourceFile: SourceFile; - references?: readonly (ResolvedProjectReference | undefined)[]; - } - type CustomTransformerFactory = (context: TransformationContext) => CustomTransformer; - interface CustomTransformer { - transformSourceFile(node: SourceFile): SourceFile; - transformBundle(node: Bundle): Bundle; - } - interface CustomTransformers { - /** Custom transformers to evaluate before built-in .js transformations. */ - before?: (TransformerFactory | CustomTransformerFactory)[]; - /** Custom transformers to evaluate after built-in .js transformations. */ - after?: (TransformerFactory | CustomTransformerFactory)[]; - /** Custom transformers to evaluate after built-in .d.ts transformations. */ - afterDeclarations?: (TransformerFactory | CustomTransformerFactory)[]; - } - interface SourceMapSpan { - /** Line number in the .js file. */ - emittedLine: number; - /** Column number in the .js file. */ - emittedColumn: number; - /** Line number in the .ts file. */ - sourceLine: number; - /** Column number in the .ts file. */ - sourceColumn: number; - /** Optional name (index into names array) associated with this span. */ - nameIndex?: number; - /** .ts file (index into sources array) associated with this span */ - sourceIndex: number; - } - /** Return code used by getEmitOutput function to indicate status of the function */ - enum ExitStatus { - Success = 0, - DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, - InvalidProject_OutputsSkipped = 3, - ProjectReferenceCycle_OutputsSkipped = 4 - } - interface EmitResult { - emitSkipped: boolean; - /** Contains declaration emit diagnostics */ - diagnostics: readonly Diagnostic[]; - emittedFiles?: string[]; - } - interface TypeChecker { - getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; - getTypeOfSymbol(symbol: Symbol): Type; - getDeclaredTypeOfSymbol(symbol: Symbol): Type; - getPropertiesOfType(type: Type): Symbol[]; - getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; - getPrivateIdentifierPropertyOfType(leftType: Type, name: string, location: Node): Symbol | undefined; - getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; - getIndexInfosOfType(type: Type): readonly IndexInfo[]; - getIndexInfosOfIndexSymbol: (indexSymbol: Symbol) => IndexInfo[]; - getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[]; - getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; - getBaseTypes(type: InterfaceType): BaseType[]; - getBaseTypeOfLiteralType(type: Type): Type; - getWidenedType(type: Type): Type; - getReturnTypeOfSignature(signature: Signature): Type; - getNullableType(type: Type, flags: TypeFlags): Type; - getNonNullableType(type: Type): Type; - getTypeArguments(type: TypeReference): readonly Type[]; - /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; - /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): SignatureDeclaration & { - typeArguments?: NodeArray; - } | undefined; - /** Note that the resulting nodes cannot be checked. */ - indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; - /** Note that the resulting nodes cannot be checked. */ - symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined; - /** Note that the resulting nodes cannot be checked. */ - symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined; - /** Note that the resulting nodes cannot be checked. */ - symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray | undefined; - /** Note that the resulting nodes cannot be checked. */ - symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined; - /** Note that the resulting nodes cannot be checked. */ - typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined; - getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol | undefined; - getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; - /** - * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. - * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. - */ - getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined; - /** - * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. - * Otherwise returns its input. - * For example, at `export type T = number;`: - * - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`. - * - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol. - * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol. - */ - getExportSymbolOfSymbol(symbol: Symbol): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; - getTypeOfAssignmentPattern(pattern: AssignmentPattern): Type; - getTypeAtLocation(node: Node): Type; - getTypeFromTypeNode(node: TypeNode): Type; - signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; - typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; - typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - getFullyQualifiedName(symbol: Symbol): string; - getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): readonly Symbol[]; - getSymbolOfExpando(node: Node, allowDeclaration: boolean): Symbol | undefined; - getContextualType(node: Expression): Type | undefined; - /** - * returns unknownSignature in the case of an error. - * returns undefined if the node is not valid. - * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. - */ - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; - isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; - isUndefinedSymbol(symbol: Symbol): boolean; - isArgumentsSymbol(symbol: Symbol): boolean; - isUnknownSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; - isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; - /** Follow all aliases to get the original symbol. */ - getAliasedSymbol(symbol: Symbol): Symbol; - /** Follow a *single* alias to get the immediately aliased symbol. */ - getImmediateAliasedSymbol(symbol: Symbol): Symbol | undefined; - getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; - isOptionalParameter(node: ParameterDeclaration): boolean; - getAmbientModules(): Symbol[]; - tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; - getApparentType(type: Type): Type; - getBaseConstraintOfType(type: Type): Type | undefined; - getDefaultFromTypeParameter(type: Type): Type | undefined; - /** - * Gets the intrinsic `any` type. There are multiple types that act as `any` used internally in the compiler, - * so the type returned by this function should not be used in equality checks to determine if another type - * is `any`. Instead, use `type.flags & TypeFlags.Any`. - */ - getAnyType(): Type; - getStringType(): Type; - getStringLiteralType(value: string): StringLiteralType; - getNumberType(): Type; - getNumberLiteralType(value: number): NumberLiteralType; - getBigIntType(): Type; - getBooleanType(): Type; - getFalseType(): Type; - getTrueType(): Type; - getVoidType(): Type; - /** - * Gets the intrinsic `undefined` type. There are multiple types that act as `undefined` used internally in the compiler - * depending on compiler options, so the type returned by this function should not be used in equality checks to determine - * if another type is `undefined`. Instead, use `type.flags & TypeFlags.Undefined`. - */ - getUndefinedType(): Type; - /** - * Gets the intrinsic `null` type. There are multiple types that act as `null` used internally in the compiler, - * so the type returned by this function should not be used in equality checks to determine if another type - * is `null`. Instead, use `type.flags & TypeFlags.Null`. - */ - getNullType(): Type; - getESSymbolType(): Type; - /** - * Gets the intrinsic `never` type. There are multiple types that act as `never` used internally in the compiler, - * so the type returned by this function should not be used in equality checks to determine if another type - * is `never`. Instead, use `type.flags & TypeFlags.Never`. - */ - getNeverType(): Type; - /** - * True if this type is the `Array` or `ReadonlyArray` type from lib.d.ts. - * This function will _not_ return true if passed a type which - * extends `Array` (for example, the TypeScript AST's `NodeArray` type). - */ - isArrayType(type: Type): boolean; - /** - * True if this type is a tuple type. This function will _not_ return true if - * passed a type which extends from a tuple. - */ - isTupleType(type: Type): boolean; - /** - * True if this type is assignable to `ReadonlyArray`. - */ - isArrayLikeType(type: Type): boolean; - getTypePredicateOfSignature(signature: Signature): TypePredicate | undefined; - /** - * Depending on the operation performed, it may be appropriate to throw away the checker - * if the cancellation token is triggered. Typically, if it is used for error checking - * and the operation is cancelled, then it should be discarded, otherwise it is safe to keep. - */ - runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T; - } - enum NodeBuilderFlags { - None = 0, - NoTruncation = 1, - WriteArrayAsGenericType = 2, - GenerateNamesForShadowedTypeParams = 4, - UseStructuralFallback = 8, - ForbidIndexedAccessSymbolReferences = 16, - WriteTypeArgumentsOfSignature = 32, - UseFullyQualifiedType = 64, - UseOnlyExternalAliasing = 128, - SuppressAnyReturnType = 256, - WriteTypeParametersInQualifiedName = 512, - MultilineObjectLiterals = 1024, - WriteClassExpressionAsTypeLiteral = 2048, - UseTypeOfFunction = 4096, - OmitParameterModifiers = 8192, - UseAliasDefinedOutsideCurrentScope = 16384, - UseSingleQuotesForStringLiteralType = 268435456, - NoTypeReduction = 536870912, - OmitThisParameter = 33554432, - AllowThisInObjectLiteral = 32768, - AllowQualifiedNameInPlaceOfIdentifier = 65536, - AllowAnonymousIdentifier = 131072, - AllowEmptyUnionOrIntersection = 262144, - AllowEmptyTuple = 524288, - AllowUniqueESSymbolType = 1048576, - AllowEmptyIndexInfoType = 2097152, - AllowNodeModulesRelativePaths = 67108864, - IgnoreErrors = 70221824, - InObjectTypeLiteral = 4194304, - InTypeAlias = 8388608, - InInitialEntityName = 16777216 - } - enum TypeFormatFlags { - None = 0, - NoTruncation = 1, - WriteArrayAsGenericType = 2, - UseStructuralFallback = 8, - WriteTypeArgumentsOfSignature = 32, - UseFullyQualifiedType = 64, - SuppressAnyReturnType = 256, - MultilineObjectLiterals = 1024, - WriteClassExpressionAsTypeLiteral = 2048, - UseTypeOfFunction = 4096, - OmitParameterModifiers = 8192, - UseAliasDefinedOutsideCurrentScope = 16384, - UseSingleQuotesForStringLiteralType = 268435456, - NoTypeReduction = 536870912, - OmitThisParameter = 33554432, - AllowUniqueESSymbolType = 1048576, - AddUndefined = 131072, - WriteArrowStyleSignature = 262144, - InArrayType = 524288, - InElementType = 2097152, - InFirstTypeArgument = 4194304, - InTypeAlias = 8388608, - NodeBuilderFlagsMask = 848330091 - } - enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, - AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8 - } - enum TypePredicateKind { - This = 0, - Identifier = 1, - AssertsThis = 2, - AssertsIdentifier = 3 - } - interface TypePredicateBase { - kind: TypePredicateKind; - type: Type | undefined; - } - interface ThisTypePredicate extends TypePredicateBase { - kind: TypePredicateKind.This; - parameterName: undefined; - parameterIndex: undefined; - type: Type; - } - interface IdentifierTypePredicate extends TypePredicateBase { - kind: TypePredicateKind.Identifier; - parameterName: string; - parameterIndex: number; - type: Type; - } - interface AssertsThisTypePredicate extends TypePredicateBase { - kind: TypePredicateKind.AssertsThis; - parameterName: undefined; - parameterIndex: undefined; - type: Type | undefined; - } - interface AssertsIdentifierTypePredicate extends TypePredicateBase { - kind: TypePredicateKind.AssertsIdentifier; - parameterName: string; - parameterIndex: number; - type: Type | undefined; - } - type TypePredicate = ThisTypePredicate | IdentifierTypePredicate | AssertsThisTypePredicate | AssertsIdentifierTypePredicate; - enum SymbolFlags { - None = 0, - FunctionScopedVariable = 1, - BlockScopedVariable = 2, - Property = 4, - EnumMember = 8, - Function = 16, - Class = 32, - Interface = 64, - ConstEnum = 128, - RegularEnum = 256, - ValueModule = 512, - NamespaceModule = 1024, - TypeLiteral = 2048, - ObjectLiteral = 4096, - Method = 8192, - Constructor = 16384, - GetAccessor = 32768, - SetAccessor = 65536, - Signature = 131072, - TypeParameter = 262144, - TypeAlias = 524288, - ExportValue = 1048576, - Alias = 2097152, - Prototype = 4194304, - ExportStar = 8388608, - Optional = 16777216, - Transient = 33554432, - Assignment = 67108864, - ModuleExports = 134217728, - Enum = 384, - Variable = 3, - Value = 111551, - Type = 788968, - Namespace = 1920, - Module = 1536, - Accessor = 98304, - FunctionScopedVariableExcludes = 111550, - BlockScopedVariableExcludes = 111551, - ParameterExcludes = 111551, - PropertyExcludes = 0, - EnumMemberExcludes = 900095, - FunctionExcludes = 110991, - ClassExcludes = 899503, - InterfaceExcludes = 788872, - RegularEnumExcludes = 899327, - ConstEnumExcludes = 899967, - ValueModuleExcludes = 110735, - NamespaceModuleExcludes = 0, - MethodExcludes = 103359, - GetAccessorExcludes = 46015, - SetAccessorExcludes = 78783, - AccessorExcludes = 13247, - TypeParameterExcludes = 526824, - TypeAliasExcludes = 788968, - AliasExcludes = 2097152, - ModuleMember = 2623475, - ExportHasLocal = 944, - BlockScoped = 418, - PropertyOrAccessor = 98308, - ClassMember = 106500 - } - interface Symbol { - flags: SymbolFlags; - escapedName: __String; - declarations?: Declaration[]; - valueDeclaration?: Declaration; - members?: SymbolTable; - exports?: SymbolTable; - globalExports?: SymbolTable; - } - interface Symbol { - readonly name: string; - getFlags(): SymbolFlags; - getEscapedName(): __String; - getName(): string; - getDeclarations(): Declaration[] | undefined; - getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; - getJsDocTags(checker?: TypeChecker): JSDocTagInfo[]; - } - enum InternalSymbolName { - Call = "__call", - Constructor = "__constructor", - New = "__new", - Index = "__index", - ExportStar = "__export", - Global = "__global", - Missing = "__missing", - Type = "__type", - Object = "__object", - JSXAttributes = "__jsxAttributes", - Class = "__class", - Function = "__function", - Computed = "__computed", - Resolving = "__resolving__", - ExportEquals = "export=", - Default = "default", - This = "this" - } - /** - * This represents a string whose leading underscore have been escaped by adding extra leading underscores. - * The shape of this brand is rather unique compared to others we've used. - * Instead of just an intersection of a string and an object, it is that union-ed - * with an intersection of void and an object. This makes it wholly incompatible - * with a normal string (which is good, it cannot be misused on assignment or on usage), - * while still being comparable with a normal string via === (also good) and castable from a string. - */ - type __String = (string & { - __escapedIdentifier: void; - }) | (void & { - __escapedIdentifier: void; - }) | InternalSymbolName; - /** @deprecated Use ReadonlyMap<__String, T> instead. */ - type ReadonlyUnderscoreEscapedMap = ReadonlyMap<__String, T>; - /** @deprecated Use Map<__String, T> instead. */ - type UnderscoreEscapedMap = Map<__String, T>; - /** SymbolTable based on ES6 Map interface. */ - type SymbolTable = Map<__String, Symbol>; - enum TypeFlags { - Any = 1, - Unknown = 2, - String = 4, - Number = 8, - Boolean = 16, - Enum = 32, - BigInt = 64, - StringLiteral = 128, - NumberLiteral = 256, - BooleanLiteral = 512, - EnumLiteral = 1024, - BigIntLiteral = 2048, - ESSymbol = 4096, - UniqueESSymbol = 8192, - Void = 16384, - Undefined = 32768, - Null = 65536, - Never = 131072, - TypeParameter = 262144, - Object = 524288, - Union = 1048576, - Intersection = 2097152, - Index = 4194304, - IndexedAccess = 8388608, - Conditional = 16777216, - Substitution = 33554432, - NonPrimitive = 67108864, - TemplateLiteral = 134217728, - StringMapping = 268435456, - Literal = 2944, - Unit = 109472, - Freshable = 2976, - StringOrNumberLiteral = 384, - PossiblyFalsy = 117724, - StringLike = 402653316, - NumberLike = 296, - BigIntLike = 2112, - BooleanLike = 528, - EnumLike = 1056, - ESSymbolLike = 12288, - VoidLike = 49152, - UnionOrIntersection = 3145728, - StructuredType = 3670016, - TypeVariable = 8650752, - InstantiableNonPrimitive = 58982400, - InstantiablePrimitive = 406847488, - Instantiable = 465829888, - StructuredOrInstantiable = 469499904, - Narrowable = 536624127 - } - type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; - interface Type { - flags: TypeFlags; - symbol: Symbol; - pattern?: DestructuringPattern; - aliasSymbol?: Symbol; - aliasTypeArguments?: readonly Type[]; - } - interface Type { - getFlags(): TypeFlags; - getSymbol(): Symbol | undefined; - getProperties(): Symbol[]; - getProperty(propertyName: string): Symbol | undefined; - getApparentProperties(): Symbol[]; - getCallSignatures(): readonly Signature[]; - getConstructSignatures(): readonly Signature[]; - getStringIndexType(): Type | undefined; - getNumberIndexType(): Type | undefined; - getBaseTypes(): BaseType[] | undefined; - getNonNullableType(): Type; - getConstraint(): Type | undefined; - getDefault(): Type | undefined; - isUnion(): this is UnionType; - isIntersection(): this is IntersectionType; - isUnionOrIntersection(): this is UnionOrIntersectionType; - isLiteral(): this is LiteralType; - isStringLiteral(): this is StringLiteralType; - isNumberLiteral(): this is NumberLiteralType; - isTypeParameter(): this is TypeParameter; - isClassOrInterface(): this is InterfaceType; - isClass(): this is InterfaceType; - isIndexType(): this is IndexType; - } - interface FreshableType extends Type { - freshType: FreshableType; - regularType: FreshableType; - } - interface LiteralType extends FreshableType { - value: string | number | PseudoBigInt; - } - interface UniqueESSymbolType extends Type { - symbol: Symbol; - escapedName: __String; - } - interface StringLiteralType extends LiteralType { - value: string; - } - interface NumberLiteralType extends LiteralType { - value: number; - } - interface BigIntLiteralType extends LiteralType { - value: PseudoBigInt; - } - interface EnumType extends FreshableType { - } - enum ObjectFlags { - None = 0, - Class = 1, - Interface = 2, - Reference = 4, - Tuple = 8, - Anonymous = 16, - Mapped = 32, - Instantiated = 64, - ObjectLiteral = 128, - EvolvingArray = 256, - ObjectLiteralPatternWithComputedProperties = 512, - ReverseMapped = 1024, - JsxAttributes = 2048, - JSLiteral = 4096, - FreshLiteral = 8192, - ArrayLiteral = 16384, - ClassOrInterface = 3, - ContainsSpread = 2097152, - ObjectRestType = 4194304, - InstantiationExpressionType = 8388608 - } - interface ObjectType extends Type { - objectFlags: ObjectFlags; - } - /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ - interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[] | undefined; - outerTypeParameters: TypeParameter[] | undefined; - localTypeParameters: TypeParameter[] | undefined; - thisType: TypeParameter | undefined; - } - type BaseType = ObjectType | IntersectionType | TypeVariable; - interface InterfaceTypeWithDeclaredMembers extends InterfaceType { - declaredProperties: Symbol[]; - declaredCallSignatures: Signature[]; - declaredConstructSignatures: Signature[]; - declaredIndexInfos: IndexInfo[]; - } - /** - * Type references (ObjectFlags.Reference). When a class or interface has type parameters or - * a "this" type, references to the class or interface are made using type references. The - * typeArguments property specifies the types to substitute for the type parameters of the - * class or interface and optionally includes an extra element that specifies the type to - * substitute for "this" in the resulting instantiation. When no extra argument is present, - * the type reference itself is substituted for "this". The typeArguments property is undefined - * if the class or interface has no type parameters and the reference isn't specifying an - * explicit "this" argument. - */ - interface TypeReference extends ObjectType { - target: GenericType; - node?: TypeReferenceNode | ArrayTypeNode | TupleTypeNode; - } - interface TypeReference { - typeArguments?: readonly Type[]; - } - interface DeferredTypeReference extends TypeReference { - } - interface GenericType extends InterfaceType, TypeReference { - } - enum ElementFlags { - Required = 1, - Optional = 2, - Rest = 4, - Variadic = 8, - Fixed = 3, - Variable = 12, - NonRequired = 14, - NonRest = 11 - } - interface TupleType extends GenericType { - elementFlags: readonly ElementFlags[]; - /** Number of required or variadic elements */ - minLength: number; - /** Number of initial required or optional elements */ - fixedLength: number; - /** True if tuple has any rest or variadic elements */ - hasRestElement: boolean; - combinedFlags: ElementFlags; - readonly: boolean; - labeledElementDeclarations?: readonly (NamedTupleMember | ParameterDeclaration | undefined)[]; - } - interface TupleTypeReference extends TypeReference { - target: TupleType; - } - interface UnionOrIntersectionType extends Type { - types: Type[]; - } - interface UnionType extends UnionOrIntersectionType { - } - interface IntersectionType extends UnionOrIntersectionType { - } - type StructuredType = ObjectType | UnionType | IntersectionType; - interface EvolvingArrayType extends ObjectType { - elementType: Type; - finalArrayType?: Type; - } - interface InstantiableType extends Type { - } - interface TypeParameter extends InstantiableType { - } - interface IndexedAccessType extends InstantiableType { - objectType: Type; - indexType: Type; - constraint?: Type; - simplifiedForReading?: Type; - simplifiedForWriting?: Type; - } - type TypeVariable = TypeParameter | IndexedAccessType; - interface IndexType extends InstantiableType { - type: InstantiableType | UnionOrIntersectionType; - } - interface ConditionalRoot { - node: ConditionalTypeNode; - checkType: Type; - extendsType: Type; - isDistributive: boolean; - inferTypeParameters?: TypeParameter[]; - outerTypeParameters?: TypeParameter[]; - instantiations?: Map; - aliasSymbol?: Symbol; - aliasTypeArguments?: Type[]; - } - interface ConditionalType extends InstantiableType { - root: ConditionalRoot; - checkType: Type; - extendsType: Type; - resolvedTrueType?: Type; - resolvedFalseType?: Type; - } - interface TemplateLiteralType extends InstantiableType { - texts: readonly string[]; - types: readonly Type[]; - } - interface StringMappingType extends InstantiableType { - symbol: Symbol; - type: Type; - } - interface SubstitutionType extends InstantiableType { - objectFlags: ObjectFlags; - baseType: Type; - constraint: Type; - } - enum SignatureKind { - Call = 0, - Construct = 1 - } - interface Signature { - declaration?: SignatureDeclaration | JSDocSignature; - typeParameters?: readonly TypeParameter[]; - parameters: readonly Symbol[]; - } - interface Signature { - getDeclaration(): SignatureDeclaration; - getTypeParameters(): TypeParameter[] | undefined; - getParameters(): Symbol[]; - getTypeParameterAtPosition(pos: number): Type; - getReturnType(): Type; - getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; - getJsDocTags(): JSDocTagInfo[]; - } - enum IndexKind { - String = 0, - Number = 1 - } - interface IndexInfo { - keyType: Type; - type: Type; - isReadonly: boolean; - declaration?: IndexSignatureDeclaration; - } - enum InferencePriority { - None = 0, - NakedTypeVariable = 1, - SpeculativeTuple = 2, - SubstituteSource = 4, - HomomorphicMappedType = 8, - PartialHomomorphicMappedType = 16, - MappedTypeConstraint = 32, - ContravariantConditional = 64, - ReturnType = 128, - LiteralKeyof = 256, - NoConstraints = 512, - AlwaysStrict = 1024, - MaxValue = 2048, - PriorityImpliesCombination = 416, - Circularity = -1 - } - interface FileExtensionInfo { - extension: string; - isMixedContent: boolean; - scriptKind?: ScriptKind; - } - interface DiagnosticMessage { - key: string; - category: DiagnosticCategory; - code: number; - message: string; - reportsUnnecessary?: {}; - reportsDeprecated?: {}; - } - /** - * A linked list of formatted diagnostic messages to be used as part of a multiline message. - * It is built from the bottom up, leaving the head to be the "main" diagnostic. - * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, - * the difference is that messages are all preformatted in DMC. - */ - interface DiagnosticMessageChain { - messageText: string; - category: DiagnosticCategory; - code: number; - next?: DiagnosticMessageChain[]; - } - interface Diagnostic extends DiagnosticRelatedInformation { - /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ - reportsUnnecessary?: {}; - reportsDeprecated?: {}; - source?: string; - relatedInformation?: DiagnosticRelatedInformation[]; - } - interface DiagnosticRelatedInformation { - category: DiagnosticCategory; - code: number; - file: SourceFile | undefined; - start: number | undefined; - length: number | undefined; - messageText: string | DiagnosticMessageChain; - } - interface DiagnosticWithLocation extends Diagnostic { - file: SourceFile; - start: number; - length: number; - } - enum DiagnosticCategory { - Warning = 0, - Error = 1, - Suggestion = 2, - Message = 3 - } - enum ModuleResolutionKind { - Classic = 1, - /** - * @deprecated - * `NodeJs` was renamed to `Node10` to better reflect the version of Node that it targets. - * Use the new name or consider switching to a modern module resolution target. - */ - NodeJs = 2, - Node10 = 2, - Node16 = 3, - NodeNext = 99, - Bundler = 100 - } - enum ModuleDetectionKind { - /** - * Files with imports, exports and/or import.meta are considered modules - */ - Legacy = 1, - /** - * Legacy, but also files with jsx under react-jsx or react-jsxdev and esm mode files under moduleResolution: node16+ - */ - Auto = 2, - /** - * Consider all non-declaration files modules, regardless of present syntax - */ - Force = 3 - } - interface PluginImport { - name: string; - } - interface ProjectReference { - /** A normalized path on disk */ - path: string; - /** The path as the user originally wrote it */ - originalPath?: string; - /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ - prepend?: boolean; - /** True if it is intended that this reference form a circularity */ - circular?: boolean; - } - enum WatchFileKind { - FixedPollingInterval = 0, - PriorityPollingInterval = 1, - DynamicPriorityPolling = 2, - FixedChunkSizePolling = 3, - UseFsEvents = 4, - UseFsEventsOnParentDirectory = 5 - } - enum WatchDirectoryKind { - UseFsEvents = 0, - FixedPollingInterval = 1, - DynamicPriorityPolling = 2, - FixedChunkSizePolling = 3 - } - enum PollingWatchKind { - FixedInterval = 0, - PriorityInterval = 1, - DynamicPriority = 2, - FixedChunkSize = 3 - } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; - interface CompilerOptions { - allowImportingTsExtensions?: boolean; - allowJs?: boolean; - allowArbitraryExtensions?: boolean; - allowSyntheticDefaultImports?: boolean; - allowUmdGlobalAccess?: boolean; - allowUnreachableCode?: boolean; - allowUnusedLabels?: boolean; - alwaysStrict?: boolean; - baseUrl?: string; - charset?: string; - checkJs?: boolean; - customConditions?: string[]; - declaration?: boolean; - declarationMap?: boolean; - emitDeclarationOnly?: boolean; - declarationDir?: string; - disableSizeLimit?: boolean; - disableSourceOfProjectReferenceRedirect?: boolean; - disableSolutionSearching?: boolean; - disableReferencedProjectLoad?: boolean; - downlevelIteration?: boolean; - emitBOM?: boolean; - emitDecoratorMetadata?: boolean; - exactOptionalPropertyTypes?: boolean; - experimentalDecorators?: boolean; - forceConsistentCasingInFileNames?: boolean; - ignoreDeprecations?: string; - importHelpers?: boolean; - importsNotUsedAsValues?: ImportsNotUsedAsValues; - inlineSourceMap?: boolean; - inlineSources?: boolean; - isolatedModules?: boolean; - jsx?: JsxEmit; - keyofStringsOnly?: boolean; - lib?: string[]; - locale?: string; - mapRoot?: string; - maxNodeModuleJsDepth?: number; - module?: ModuleKind; - moduleResolution?: ModuleResolutionKind; - moduleSuffixes?: string[]; - moduleDetection?: ModuleDetectionKind; - newLine?: NewLineKind; - noEmit?: boolean; - noEmitHelpers?: boolean; - noEmitOnError?: boolean; - noErrorTruncation?: boolean; - noFallthroughCasesInSwitch?: boolean; - noImplicitAny?: boolean; - noImplicitReturns?: boolean; - noImplicitThis?: boolean; - noStrictGenericChecks?: boolean; - noUnusedLocals?: boolean; - noUnusedParameters?: boolean; - noImplicitUseStrict?: boolean; - noPropertyAccessFromIndexSignature?: boolean; - assumeChangesOnlyAffectDirectDependencies?: boolean; - noLib?: boolean; - noResolve?: boolean; - noUncheckedIndexedAccess?: boolean; - out?: string; - outDir?: string; - outFile?: string; - paths?: MapLike; - preserveConstEnums?: boolean; - noImplicitOverride?: boolean; - preserveSymlinks?: boolean; - preserveValueImports?: boolean; - project?: string; - reactNamespace?: string; - jsxFactory?: string; - jsxFragmentFactory?: string; - jsxImportSource?: string; - composite?: boolean; - incremental?: boolean; - tsBuildInfoFile?: string; - removeComments?: boolean; - resolvePackageJsonExports?: boolean; - resolvePackageJsonImports?: boolean; - rootDir?: string; - rootDirs?: string[]; - skipLibCheck?: boolean; - skipDefaultLibCheck?: boolean; - sourceMap?: boolean; - sourceRoot?: string; - strict?: boolean; - strictFunctionTypes?: boolean; - strictBindCallApply?: boolean; - strictNullChecks?: boolean; - strictPropertyInitialization?: boolean; - stripInternal?: boolean; - suppressExcessPropertyErrors?: boolean; - suppressImplicitAnyIndexErrors?: boolean; - target?: ScriptTarget; - traceResolution?: boolean; - useUnknownInCatchVariables?: boolean; - resolveJsonModule?: boolean; - types?: string[]; - /** Paths used to compute primary types search locations */ - typeRoots?: string[]; - verbatimModuleSyntax?: boolean; - esModuleInterop?: boolean; - useDefineForClassFields?: boolean; - [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; - } - interface WatchOptions { - watchFile?: WatchFileKind; - watchDirectory?: WatchDirectoryKind; - fallbackPolling?: PollingWatchKind; - synchronousWatchDirectory?: boolean; - excludeDirectories?: string[]; - excludeFiles?: string[]; - [option: string]: CompilerOptionsValue | undefined; - } - interface TypeAcquisition { - enable?: boolean; - include?: string[]; - exclude?: string[]; - disableFilenameBasedTypeAcquisition?: boolean; - [option: string]: CompilerOptionsValue | undefined; - } - enum ModuleKind { - None = 0, - CommonJS = 1, - AMD = 2, - UMD = 3, - System = 4, - ES2015 = 5, - ES2020 = 6, - ES2022 = 7, - ESNext = 99, - Node16 = 100, - NodeNext = 199 - } - enum JsxEmit { - None = 0, - Preserve = 1, - React = 2, - ReactNative = 3, - ReactJSX = 4, - ReactJSXDev = 5 - } - enum ImportsNotUsedAsValues { - Remove = 0, - Preserve = 1, - Error = 2 - } - enum NewLineKind { - CarriageReturnLineFeed = 0, - LineFeed = 1 - } - interface LineAndCharacter { - /** 0-based. */ - line: number; - character: number; - } - enum ScriptKind { - Unknown = 0, - JS = 1, - JSX = 2, - TS = 3, - TSX = 4, - External = 5, - JSON = 6, - /** - * Used on extensions that doesn't define the ScriptKind but the content defines it. - * Deferred extensions are going to be included in all project contexts. - */ - Deferred = 7 - } - enum ScriptTarget { - ES3 = 0, - ES5 = 1, - ES2015 = 2, - ES2016 = 3, - ES2017 = 4, - ES2018 = 5, - ES2019 = 6, - ES2020 = 7, - ES2021 = 8, - ES2022 = 9, - ESNext = 99, - JSON = 100, - Latest = 99 - } - enum LanguageVariant { - Standard = 0, - JSX = 1 - } - /** Either a parsed command line or a parsed tsconfig.json */ - interface ParsedCommandLine { - options: CompilerOptions; - typeAcquisition?: TypeAcquisition; - fileNames: string[]; - projectReferences?: readonly ProjectReference[]; - watchOptions?: WatchOptions; - raw?: any; - errors: Diagnostic[]; - wildcardDirectories?: MapLike; - compileOnSave?: boolean; - } - enum WatchDirectoryFlags { - None = 0, - Recursive = 1 - } - interface CreateProgramOptions { - rootNames: readonly string[]; - options: CompilerOptions; - projectReferences?: readonly ProjectReference[]; - host?: CompilerHost; - oldProgram?: Program; - configFileParsingDiagnostics?: readonly Diagnostic[]; - } - interface ModuleResolutionHost { - fileExists(fileName: string): boolean; - readFile(fileName: string): string | undefined; - trace?(s: string): void; - directoryExists?(directoryName: string): boolean; - /** - * Resolve a symbolic link. - * @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options - */ - realpath?(path: string): string; - getCurrentDirectory?(): string; - getDirectories?(path: string): string[]; - useCaseSensitiveFileNames?: boolean | (() => boolean) | undefined; - } - /** - * Used by services to specify the minimum host area required to set up source files under any compilation settings - */ - interface MinimalResolutionCacheHost extends ModuleResolutionHost { - getCompilationSettings(): CompilerOptions; - getCompilerHost?(): CompilerHost | undefined; - } - /** - * Represents the result of module resolution. - * Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off. - * The Program will then filter results based on these flags. - * - * Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred. - */ - interface ResolvedModule { - /** Path of the file the module was resolved to. */ - resolvedFileName: string; - /** True if `resolvedFileName` comes from `node_modules`. */ - isExternalLibraryImport?: boolean; - /** - * True if the original module reference used a .ts extension to refer directly to a .ts file, - * which should produce an error during checking if emit is enabled. - */ - resolvedUsingTsExtension?: boolean; - } - /** - * ResolvedModule with an explicitly provided `extension` property. - * Prefer this over `ResolvedModule`. - * If changing this, remember to change `moduleResolutionIsEqualTo`. - */ - interface ResolvedModuleFull extends ResolvedModule { - /** - * Extension of resolvedFileName. This must match what's at the end of resolvedFileName. - * This is optional for backwards-compatibility, but will be added if not provided. - */ - extension: string; - packageId?: PackageId; - } - /** - * Unique identifier with a package name and version. - * If changing this, remember to change `packageIdIsEqual`. - */ - interface PackageId { - /** - * Name of the package. - * Should not include `@types`. - * If accessing a non-index file, this should include its name e.g. "foo/bar". - */ - name: string; - /** - * Name of a submodule within this package. - * May be "". - */ - subModuleName: string; - /** Version of the package, e.g. "1.2.3" */ - version: string; - } - enum Extension { - Ts = ".ts", - Tsx = ".tsx", - Dts = ".d.ts", - Js = ".js", - Jsx = ".jsx", - Json = ".json", - TsBuildInfo = ".tsbuildinfo", - Mjs = ".mjs", - Mts = ".mts", - Dmts = ".d.mts", - Cjs = ".cjs", - Cts = ".cts", - Dcts = ".d.cts" - } - interface ResolvedModuleWithFailedLookupLocations { - readonly resolvedModule: ResolvedModuleFull | undefined; - } - interface ResolvedTypeReferenceDirective { - primary: boolean; - resolvedFileName: string | undefined; - packageId?: PackageId; - /** True if `resolvedFileName` comes from `node_modules`. */ - isExternalLibraryImport?: boolean; - } - interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; - } - interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; - getSourceFileByPath?(fileName: string, path: Path, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; - getCancellationToken?(): CancellationToken; - getDefaultLibFileName(options: CompilerOptions): string; - getDefaultLibLocation?(): string; - writeFile: WriteFileCallback; - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - useCaseSensitiveFileNames(): boolean; - getNewLine(): string; - readDirectory?(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): string[]; - /** @deprecated supply resolveModuleNameLiterals instead for resolution that can handle newer resolution modes like nodenext */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[]; - /** - * Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it - */ - getModuleResolutionCache?(): ModuleResolutionCache | undefined; - /** - * @deprecated supply resolveTypeReferenceDirectiveReferences instead for resolution that can handle newer resolution modes like nodenext - * - * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files - */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: ResolutionMode): (ResolvedTypeReferenceDirective | undefined)[]; - resolveModuleNameLiterals?(moduleLiterals: readonly StringLiteralLike[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile, reusedNames: readonly StringLiteralLike[] | undefined): readonly ResolvedModuleWithFailedLookupLocations[]; - resolveTypeReferenceDirectiveReferences?(typeDirectiveReferences: readonly T[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile | undefined, reusedNames: readonly T[] | undefined): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[]; - getEnvironmentVariable?(name: string): string | undefined; - /** If provided along with custom resolveModuleNames or resolveTypeReferenceDirectives, used to determine if unchanged file path needs to re-resolve modules/type reference directives */ - hasInvalidatedResolutions?(filePath: Path): boolean; - createHash?(data: string): string; - getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; - } - interface SourceMapRange extends TextRange { - source?: SourceMapSource; - } - interface SourceMapSource { - fileName: string; - text: string; - skipTrivia?: (pos: number) => number; - } - interface SourceMapSource { - getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - } - enum EmitFlags { - None = 0, - SingleLine = 1, - MultiLine = 2, - AdviseOnEmitNode = 4, - NoSubstitution = 8, - CapturesThis = 16, - NoLeadingSourceMap = 32, - NoTrailingSourceMap = 64, - NoSourceMap = 96, - NoNestedSourceMaps = 128, - NoTokenLeadingSourceMaps = 256, - NoTokenTrailingSourceMaps = 512, - NoTokenSourceMaps = 768, - NoLeadingComments = 1024, - NoTrailingComments = 2048, - NoComments = 3072, - NoNestedComments = 4096, - HelperName = 8192, - ExportName = 16384, - LocalName = 32768, - InternalName = 65536, - Indented = 131072, - NoIndentation = 262144, - AsyncFunctionBody = 524288, - ReuseTempVariableScope = 1048576, - CustomPrologue = 2097152, - NoHoisting = 4194304, - Iterator = 8388608, - NoAsciiEscaping = 16777216 - } - interface EmitHelperBase { - readonly name: string; - readonly scoped: boolean; - readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); - readonly priority?: number; - readonly dependencies?: EmitHelper[]; - } - interface ScopedEmitHelper extends EmitHelperBase { - readonly scoped: true; - } - interface UnscopedEmitHelper extends EmitHelperBase { - readonly scoped: false; - readonly text: string; - } - type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper; - type EmitHelperUniqueNameCallback = (name: string) => string; - enum EmitHint { - SourceFile = 0, - Expression = 1, - IdentifierName = 2, - MappedTypeParameter = 3, - Unspecified = 4, - EmbeddedStatement = 5, - JsxAttributeValue = 6 - } - enum OuterExpressionKinds { - Parentheses = 1, - TypeAssertions = 2, - NonNullAssertions = 4, - PartiallyEmittedExpressions = 8, - Assertions = 6, - All = 15, - ExcludeJSDocTypeAssertion = 16 - } - type ImmediatelyInvokedFunctionExpression = CallExpression & { - readonly expression: FunctionExpression; - }; - type ImmediatelyInvokedArrowFunction = CallExpression & { - readonly expression: ParenthesizedExpression & { - readonly expression: ArrowFunction; - }; - }; - interface NodeFactory { - createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray; - createNumericLiteral(value: string | number, numericLiteralFlags?: TokenFlags): NumericLiteral; - createBigIntLiteral(value: string | PseudoBigInt): BigIntLiteral; - createStringLiteral(text: string, isSingleQuote?: boolean): StringLiteral; - createStringLiteralFromNode(sourceNode: PropertyNameLiteral | PrivateIdentifier, isSingleQuote?: boolean): StringLiteral; - createRegularExpressionLiteral(text: string): RegularExpressionLiteral; - createIdentifier(text: string): Identifier; - /** - * Create a unique temporary variable. - * @param recordTempVariable An optional callback used to record the temporary variable name. This - * should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but - * can be `undefined` if you plan to record the temporary variable manually. - * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes - * during emit so that the variable can be referenced in a nested function body. This is an alternative to - * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. - */ - createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; - /** - * Create a unique temporary variable for use in a loop. - * @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes - * during emit so that the variable can be referenced in a nested function body. This is an alternative to - * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. - */ - createLoopVariable(reservedInNestedScopes?: boolean): Identifier; - /** Create a unique name based on the supplied text. */ - createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier; - /** Create a unique name generated for a node. */ - getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; - createPrivateIdentifier(text: string): PrivateIdentifier; - createUniquePrivateName(text?: string): PrivateIdentifier; - getGeneratedPrivateNameForNode(node: Node): PrivateIdentifier; - createToken(token: SyntaxKind.SuperKeyword): SuperExpression; - createToken(token: SyntaxKind.ThisKeyword): ThisExpression; - createToken(token: SyntaxKind.NullKeyword): NullLiteral; - createToken(token: SyntaxKind.TrueKeyword): TrueLiteral; - createToken(token: SyntaxKind.FalseKeyword): FalseLiteral; - createToken(token: SyntaxKind.EndOfFileToken): EndOfFileToken; - createToken(token: SyntaxKind.Unknown): Token; - createToken(token: TKind): PunctuationToken; - createToken(token: TKind): KeywordTypeNode; - createToken(token: TKind): ModifierToken; - createToken(token: TKind): KeywordToken; - createSuper(): SuperExpression; - createThis(): ThisExpression; - createNull(): NullLiteral; - createTrue(): TrueLiteral; - createFalse(): FalseLiteral; - createModifier(kind: T): ModifierToken; - createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[] | undefined; - createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; - updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; - createComputedPropertyName(expression: Expression): ComputedPropertyName; - updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; - createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; - updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - createParameterDeclaration(modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; - updateParameterDeclaration(node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; - createDecorator(expression: Expression): Decorator; - updateDecorator(node: Decorator, expression: Expression): Decorator; - createPropertySignature(modifiers: readonly Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; - updatePropertySignature(node: PropertySignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; - createPropertyDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; - updatePropertyDeclaration(node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; - createMethodSignature(modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): MethodSignature; - updateMethodSignature(node: MethodSignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): MethodSignature; - createMethodDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - updateMethodDeclaration(node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - createConstructorDeclaration(modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - updateConstructorDeclaration(node: ConstructorDeclaration, modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - createGetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - updateGetAccessorDeclaration(node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - createSetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; - updateSetAccessorDeclaration(node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; - createCallSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - createConstructSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - createIndexSignature(modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - updateIndexSignature(node: IndexSignatureDeclaration, modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - createTemplateLiteralTypeSpan(type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; - updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; - createClassStaticBlockDeclaration(body: Block): ClassStaticBlockDeclaration; - updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, body: Block): ClassStaticBlockDeclaration; - createKeywordTypeNode(kind: TKind): KeywordTypeNode; - createTypePredicateNode(assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode | string, type: TypeNode | undefined): TypePredicateNode; - updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined): TypePredicateNode; - createTypeReferenceNode(typeName: string | EntityName, typeArguments?: readonly TypeNode[]): TypeReferenceNode; - updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - createFunctionTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): FunctionTypeNode; - updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): FunctionTypeNode; - createConstructorTypeNode(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; - updateConstructorTypeNode(node: ConstructorTypeNode, modifiers: readonly Modifier[] | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; - createTypeQueryNode(exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; - updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; - createTypeLiteralNode(members: readonly TypeElement[] | undefined): TypeLiteralNode; - updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; - createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - createTupleTypeNode(elements: readonly (TypeNode | NamedTupleMember)[]): TupleTypeNode; - updateTupleTypeNode(node: TupleTypeNode, elements: readonly (TypeNode | NamedTupleMember)[]): TupleTypeNode; - createNamedTupleMember(dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode): NamedTupleMember; - updateNamedTupleMember(node: NamedTupleMember, dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode): NamedTupleMember; - createOptionalTypeNode(type: TypeNode): OptionalTypeNode; - updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode; - createRestTypeNode(type: TypeNode): RestTypeNode; - updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode; - createUnionTypeNode(types: readonly TypeNode[]): UnionTypeNode; - updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; - createIntersectionTypeNode(types: readonly TypeNode[]): IntersectionTypeNode; - updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; - createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; - updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; - createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; - updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; - createImportTypeNode(argument: TypeNode, assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; - updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; - createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; - createThisTypeNode(): ThisTypeNode; - createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode; - updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; - updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; - createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; - updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; - createTemplateLiteralType(head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode; - updateTemplateLiteralType(node: TemplateLiteralTypeNode, head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode; - createObjectBindingPattern(elements: readonly BindingElement[]): ObjectBindingPattern; - updateObjectBindingPattern(node: ObjectBindingPattern, elements: readonly BindingElement[]): ObjectBindingPattern; - createArrayBindingPattern(elements: readonly ArrayBindingElement[]): ArrayBindingPattern; - updateArrayBindingPattern(node: ArrayBindingPattern, elements: readonly ArrayBindingElement[]): ArrayBindingPattern; - createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement; - updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement; - createArrayLiteralExpression(elements?: readonly Expression[], multiLine?: boolean): ArrayLiteralExpression; - updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression; - createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; - updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression; - createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; - createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain; - updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain; - createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression; - updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain; - updateElementAccessChain(node: ElementAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, argumentExpression: Expression): ElementAccessChain; - createCallExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): CallExpression; - updateCallExpression(node: CallExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]): CallExpression; - createCallChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): CallChain; - updateCallChain(node: CallChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]): CallChain; - createNewExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): NewExpression; - updateNewExpression(node: NewExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): NewExpression; - createTaggedTemplateExpression(tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression; - updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression; - createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; - updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; - createParenthesizedExpression(expression: Expression): ParenthesizedExpression; - updateParenthesizedExpression(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - createFunctionExpression(modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[] | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; - updateFunctionExpression(node: FunctionExpression, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression; - createArrowFunction(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; - updateArrowFunction(node: ArrowFunction, modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody): ArrowFunction; - createDeleteExpression(expression: Expression): DeleteExpression; - updateDeleteExpression(node: DeleteExpression, expression: Expression): DeleteExpression; - createTypeOfExpression(expression: Expression): TypeOfExpression; - updateTypeOfExpression(node: TypeOfExpression, expression: Expression): TypeOfExpression; - createVoidExpression(expression: Expression): VoidExpression; - updateVoidExpression(node: VoidExpression, expression: Expression): VoidExpression; - createAwaitExpression(expression: Expression): AwaitExpression; - updateAwaitExpression(node: AwaitExpression, expression: Expression): AwaitExpression; - createPrefixUnaryExpression(operator: PrefixUnaryOperator, operand: Expression): PrefixUnaryExpression; - updatePrefixUnaryExpression(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; - createPostfixUnaryExpression(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; - updatePostfixUnaryExpression(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; - createBinaryExpression(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - updateBinaryExpression(node: BinaryExpression, left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - createConditionalExpression(condition: Expression, questionToken: QuestionToken | undefined, whenTrue: Expression, colonToken: ColonToken | undefined, whenFalse: Expression): ConditionalExpression; - updateConditionalExpression(node: ConditionalExpression, condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; - createTemplateExpression(head: TemplateHead, templateSpans: readonly TemplateSpan[]): TemplateExpression; - updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: readonly TemplateSpan[]): TemplateExpression; - createTemplateHead(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateHead; - createTemplateHead(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateHead; - createTemplateMiddle(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateMiddle; - createTemplateMiddle(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateMiddle; - createTemplateTail(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateTail; - createTemplateTail(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateTail; - createNoSubstitutionTemplateLiteral(text: string, rawText?: string): NoSubstitutionTemplateLiteral; - createNoSubstitutionTemplateLiteral(text: string | undefined, rawText: string): NoSubstitutionTemplateLiteral; - createYieldExpression(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; - createYieldExpression(asteriskToken: undefined, expression: Expression | undefined): YieldExpression; - updateYieldExpression(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression; - createSpreadElement(expression: Expression): SpreadElement; - updateSpreadElement(node: SpreadElement, expression: Expression): SpreadElement; - createClassExpression(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; - updateClassExpression(node: ClassExpression, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; - createOmittedExpression(): OmittedExpression; - createExpressionWithTypeArguments(expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; - updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; - createAsExpression(expression: Expression, type: TypeNode): AsExpression; - updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; - createNonNullExpression(expression: Expression): NonNullExpression; - updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; - createNonNullChain(expression: Expression): NonNullChain; - updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain; - createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; - updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; - createSatisfiesExpression(expression: Expression, type: TypeNode): SatisfiesExpression; - updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode): SatisfiesExpression; - createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; - updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; - createSemicolonClassElement(): SemicolonClassElement; - createBlock(statements: readonly Statement[], multiLine?: boolean): Block; - updateBlock(node: Block, statements: readonly Statement[]): Block; - createVariableStatement(modifiers: readonly ModifierLike[] | undefined, declarationList: VariableDeclarationList | readonly VariableDeclaration[]): VariableStatement; - updateVariableStatement(node: VariableStatement, modifiers: readonly ModifierLike[] | undefined, declarationList: VariableDeclarationList): VariableStatement; - createEmptyStatement(): EmptyStatement; - createExpressionStatement(expression: Expression): ExpressionStatement; - updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; - createIfStatement(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement; - updateIfStatement(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined): IfStatement; - createDoStatement(statement: Statement, expression: Expression): DoStatement; - updateDoStatement(node: DoStatement, statement: Statement, expression: Expression): DoStatement; - createWhileStatement(expression: Expression, statement: Statement): WhileStatement; - updateWhileStatement(node: WhileStatement, expression: Expression, statement: Statement): WhileStatement; - createForStatement(initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; - updateForStatement(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; - createForInStatement(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - updateForInStatement(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - createForOfStatement(awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; - updateForOfStatement(node: ForOfStatement, awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; - createContinueStatement(label?: string | Identifier): ContinueStatement; - updateContinueStatement(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; - createBreakStatement(label?: string | Identifier): BreakStatement; - updateBreakStatement(node: BreakStatement, label: Identifier | undefined): BreakStatement; - createReturnStatement(expression?: Expression): ReturnStatement; - updateReturnStatement(node: ReturnStatement, expression: Expression | undefined): ReturnStatement; - createWithStatement(expression: Expression, statement: Statement): WithStatement; - updateWithStatement(node: WithStatement, expression: Expression, statement: Statement): WithStatement; - createSwitchStatement(expression: Expression, caseBlock: CaseBlock): SwitchStatement; - updateSwitchStatement(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock): SwitchStatement; - createLabeledStatement(label: string | Identifier, statement: Statement): LabeledStatement; - updateLabeledStatement(node: LabeledStatement, label: Identifier, statement: Statement): LabeledStatement; - createThrowStatement(expression: Expression): ThrowStatement; - updateThrowStatement(node: ThrowStatement, expression: Expression): ThrowStatement; - createTryStatement(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; - updateTryStatement(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; - createDebuggerStatement(): DebuggerStatement; - createVariableDeclaration(name: string | BindingName, exclamationToken?: ExclamationToken, type?: TypeNode, initializer?: Expression): VariableDeclaration; - updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; - createVariableDeclarationList(declarations: readonly VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]): VariableDeclarationList; - createFunctionDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - updateFunctionDeclaration(node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - createClassDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - updateClassDeclaration(node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - createInterfaceDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - updateInterfaceDeclaration(node: InterfaceDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - createTypeAliasDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - updateTypeAliasDeclaration(node: TypeAliasDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - createEnumDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; - updateEnumDeclaration(node: EnumDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; - createModuleDeclaration(modifiers: readonly ModifierLike[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; - updateModuleDeclaration(node: ModuleDeclaration, modifiers: readonly ModifierLike[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; - createModuleBlock(statements: readonly Statement[]): ModuleBlock; - updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]): ModuleBlock; - createCaseBlock(clauses: readonly CaseOrDefaultClause[]): CaseBlock; - updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]): CaseBlock; - createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; - updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; - createImportEqualsDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - createImportDeclaration(modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration; - updateImportDeclaration(node: ImportDeclaration, modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration; - createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; - updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; - createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; - updateAssertClause(node: AssertClause, elements: NodeArray, multiLine?: boolean): AssertClause; - createAssertEntry(name: AssertionKey, value: Expression): AssertEntry; - updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry; - createImportTypeAssertionContainer(clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer; - updateImportTypeAssertionContainer(node: ImportTypeAssertionContainer, clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer; - createNamespaceImport(name: Identifier): NamespaceImport; - updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; - createNamespaceExport(name: Identifier): NamespaceExport; - updateNamespaceExport(node: NamespaceExport, name: Identifier): NamespaceExport; - createNamedImports(elements: readonly ImportSpecifier[]): NamedImports; - updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports; - createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - createExportAssignment(modifiers: readonly ModifierLike[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; - updateExportAssignment(node: ExportAssignment, modifiers: readonly ModifierLike[] | undefined, expression: Expression): ExportAssignment; - createExportDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration; - updateExportDeclaration(node: ExportDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration; - createNamedExports(elements: readonly ExportSpecifier[]): NamedExports; - updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports; - createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; - updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; - createExternalModuleReference(expression: Expression): ExternalModuleReference; - updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; - createJSDocAllType(): JSDocAllType; - createJSDocUnknownType(): JSDocUnknownType; - createJSDocNonNullableType(type: TypeNode, postfix?: boolean): JSDocNonNullableType; - updateJSDocNonNullableType(node: JSDocNonNullableType, type: TypeNode): JSDocNonNullableType; - createJSDocNullableType(type: TypeNode, postfix?: boolean): JSDocNullableType; - updateJSDocNullableType(node: JSDocNullableType, type: TypeNode): JSDocNullableType; - createJSDocOptionalType(type: TypeNode): JSDocOptionalType; - updateJSDocOptionalType(node: JSDocOptionalType, type: TypeNode): JSDocOptionalType; - createJSDocFunctionType(parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType; - updateJSDocFunctionType(node: JSDocFunctionType, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType; - createJSDocVariadicType(type: TypeNode): JSDocVariadicType; - updateJSDocVariadicType(node: JSDocVariadicType, type: TypeNode): JSDocVariadicType; - createJSDocNamepathType(type: TypeNode): JSDocNamepathType; - updateJSDocNamepathType(node: JSDocNamepathType, type: TypeNode): JSDocNamepathType; - createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression; - updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression; - createJSDocNameReference(name: EntityName | JSDocMemberName): JSDocNameReference; - updateJSDocNameReference(node: JSDocNameReference, name: EntityName | JSDocMemberName): JSDocNameReference; - createJSDocMemberName(left: EntityName | JSDocMemberName, right: Identifier): JSDocMemberName; - updateJSDocMemberName(node: JSDocMemberName, left: EntityName | JSDocMemberName, right: Identifier): JSDocMemberName; - createJSDocLink(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink; - updateJSDocLink(node: JSDocLink, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink; - createJSDocLinkCode(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode; - updateJSDocLinkCode(node: JSDocLinkCode, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode; - createJSDocLinkPlain(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain; - updateJSDocLinkPlain(node: JSDocLinkPlain, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain; - createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; - updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral; - createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; - updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature; - createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag; - updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag; - createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag; - updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag; - createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag; - updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag; - createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag; - updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag; - createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocTypeTag; - updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocTypeTag; - createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; - updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; - createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray): JSDocReturnTag; - updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocReturnTag; - createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocThisTag; - updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocThisTag; - createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocEnumTag; - updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocEnumTag; - createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag; - updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag; - createJSDocOverloadTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, comment?: string | NodeArray): JSDocOverloadTag; - updateJSDocOverloadTag(node: JSDocOverloadTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, comment: string | NodeArray | undefined): JSDocOverloadTag; - createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag; - updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag; - createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag; - updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag; - createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocAuthorTag; - updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocAuthorTag; - createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocClassTag; - updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocClassTag; - createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPublicTag; - updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPublicTag; - createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPrivateTag; - updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPrivateTag; - createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocProtectedTag; - updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocProtectedTag; - createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocReadonlyTag; - updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocReadonlyTag; - createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag; - updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag; - createJSDocDeprecatedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocDeprecatedTag; - updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier | undefined, comment?: string | NodeArray): JSDocDeprecatedTag; - createJSDocOverrideTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocOverrideTag; - updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier | undefined, comment?: string | NodeArray): JSDocOverrideTag; - createJSDocThrowsTag(tagName: Identifier, typeExpression: JSDocTypeExpression | undefined, comment?: string | NodeArray): JSDocThrowsTag; - updateJSDocThrowsTag(node: JSDocThrowsTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment?: string | NodeArray | undefined): JSDocThrowsTag; - createJSDocSatisfiesTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocSatisfiesTag; - updateJSDocSatisfiesTag(node: JSDocSatisfiesTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocSatisfiesTag; - createJSDocText(text: string): JSDocText; - updateJSDocText(node: JSDocText, text: string): JSDocText; - createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; - updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; - createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; - updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; - createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; - updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; - createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxOpeningElement; - updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxOpeningElement; - createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; - updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - createJsxFragment(openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment; - createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText; - updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText; - createJsxOpeningFragment(): JsxOpeningFragment; - createJsxJsxClosingFragment(): JsxClosingFragment; - updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment; - createJsxAttribute(name: JsxAttributeName, initializer: JsxAttributeValue | undefined): JsxAttribute; - updateJsxAttribute(node: JsxAttribute, name: JsxAttributeName, initializer: JsxAttributeValue | undefined): JsxAttribute; - createJsxAttributes(properties: readonly JsxAttributeLike[]): JsxAttributes; - updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]): JsxAttributes; - createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; - updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; - createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; - updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - createJsxNamespacedName(namespace: Identifier, name: Identifier): JsxNamespacedName; - updateJsxNamespacedName(node: JsxNamespacedName, namespace: Identifier, name: Identifier): JsxNamespacedName; - createCaseClause(expression: Expression, statements: readonly Statement[]): CaseClause; - updateCaseClause(node: CaseClause, expression: Expression, statements: readonly Statement[]): CaseClause; - createDefaultClause(statements: readonly Statement[]): DefaultClause; - updateDefaultClause(node: DefaultClause, statements: readonly Statement[]): DefaultClause; - createHeritageClause(token: HeritageClause["token"], types: readonly ExpressionWithTypeArguments[]): HeritageClause; - updateHeritageClause(node: HeritageClause, types: readonly ExpressionWithTypeArguments[]): HeritageClause; - createCatchClause(variableDeclaration: string | BindingName | VariableDeclaration | undefined, block: Block): CatchClause; - updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause; - createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; - updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; - createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment; - updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined): ShorthandPropertyAssignment; - createSpreadAssignment(expression: Expression): SpreadAssignment; - updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; - createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; - updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - createSourceFile(statements: readonly Statement[], endOfFileToken: EndOfFileToken, flags: NodeFlags): SourceFile; - updateSourceFile(node: SourceFile, statements: readonly Statement[], isDeclarationFile?: boolean, referencedFiles?: readonly FileReference[], typeReferences?: readonly FileReference[], hasNoDefaultLib?: boolean, libReferences?: readonly FileReference[]): SourceFile; - createNotEmittedStatement(original: Node): NotEmittedStatement; - createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; - updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; - createCommaListExpression(elements: readonly Expression[]): CommaListExpression; - updateCommaListExpression(node: CommaListExpression, elements: readonly Expression[]): CommaListExpression; - createBundle(sourceFiles: readonly SourceFile[]): Bundle; - /** @deprecated*/ createBundle(sourceFiles: readonly SourceFile[], prepends?: readonly (UnparsedSource | InputFiles)[]): Bundle; - updateBundle(node: Bundle, sourceFiles: readonly SourceFile[]): Bundle; - /** @deprecated*/ updateBundle(node: Bundle, sourceFiles: readonly SourceFile[], prepends?: readonly (UnparsedSource | InputFiles)[]): Bundle; - createComma(left: Expression, right: Expression): BinaryExpression; - createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; - createAssignment(left: Expression, right: Expression): AssignmentExpression; - createLogicalOr(left: Expression, right: Expression): BinaryExpression; - createLogicalAnd(left: Expression, right: Expression): BinaryExpression; - createBitwiseOr(left: Expression, right: Expression): BinaryExpression; - createBitwiseXor(left: Expression, right: Expression): BinaryExpression; - createBitwiseAnd(left: Expression, right: Expression): BinaryExpression; - createStrictEquality(left: Expression, right: Expression): BinaryExpression; - createStrictInequality(left: Expression, right: Expression): BinaryExpression; - createEquality(left: Expression, right: Expression): BinaryExpression; - createInequality(left: Expression, right: Expression): BinaryExpression; - createLessThan(left: Expression, right: Expression): BinaryExpression; - createLessThanEquals(left: Expression, right: Expression): BinaryExpression; - createGreaterThan(left: Expression, right: Expression): BinaryExpression; - createGreaterThanEquals(left: Expression, right: Expression): BinaryExpression; - createLeftShift(left: Expression, right: Expression): BinaryExpression; - createRightShift(left: Expression, right: Expression): BinaryExpression; - createUnsignedRightShift(left: Expression, right: Expression): BinaryExpression; - createAdd(left: Expression, right: Expression): BinaryExpression; - createSubtract(left: Expression, right: Expression): BinaryExpression; - createMultiply(left: Expression, right: Expression): BinaryExpression; - createDivide(left: Expression, right: Expression): BinaryExpression; - createModulo(left: Expression, right: Expression): BinaryExpression; - createExponent(left: Expression, right: Expression): BinaryExpression; - createPrefixPlus(operand: Expression): PrefixUnaryExpression; - createPrefixMinus(operand: Expression): PrefixUnaryExpression; - createPrefixIncrement(operand: Expression): PrefixUnaryExpression; - createPrefixDecrement(operand: Expression): PrefixUnaryExpression; - createBitwiseNot(operand: Expression): PrefixUnaryExpression; - createLogicalNot(operand: Expression): PrefixUnaryExpression; - createPostfixIncrement(operand: Expression): PostfixUnaryExpression; - createPostfixDecrement(operand: Expression): PostfixUnaryExpression; - createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; - createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; - createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; - createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; - createVoidZero(): VoidExpression; - createExportDefault(expression: Expression): ExportAssignment; - createExternalModuleExport(exportName: Identifier): ExportDeclaration; - restoreOuterExpressions(outerExpression: Expression | undefined, innerExpression: Expression, kinds?: OuterExpressionKinds): Expression; - } - interface CoreTransformationContext { - readonly factory: NodeFactory; - /** Gets the compiler options supplied to the transformer. */ - getCompilerOptions(): CompilerOptions; - /** Starts a new lexical environment. */ - startLexicalEnvironment(): void; - /** Suspends the current lexical environment, usually after visiting a parameter list. */ - suspendLexicalEnvironment(): void; - /** Resumes a suspended lexical environment, usually before visiting a function body. */ - resumeLexicalEnvironment(): void; - /** Ends a lexical environment, returning any declarations. */ - endLexicalEnvironment(): Statement[] | undefined; - /** Hoists a function declaration to the containing scope. */ - hoistFunctionDeclaration(node: FunctionDeclaration): void; - /** Hoists a variable declaration to the containing scope. */ - hoistVariableDeclaration(node: Identifier): void; - } - interface TransformationContext extends CoreTransformationContext { - /** Records a request for a non-scoped emit helper in the current context. */ - requestEmitHelper(helper: EmitHelper): void; - /** Gets and resets the requested non-scoped emit helpers. */ - readEmitHelpers(): EmitHelper[] | undefined; - /** Enables expression substitutions in the pretty printer for the provided SyntaxKind. */ - enableSubstitution(kind: SyntaxKind): void; - /** Determines whether expression substitutions are enabled for the provided node. */ - isSubstitutionEnabled(node: Node): boolean; - /** - * Hook used by transformers to substitute expressions just before they - * are emitted by the pretty printer. - * - * NOTE: Transformation hooks should only be modified during `Transformer` initialization, - * before returning the `NodeTransformer` callback. - */ - onSubstituteNode: (hint: EmitHint, node: Node) => Node; - /** - * Enables before/after emit notifications in the pretty printer for the provided - * SyntaxKind. - */ - enableEmitNotification(kind: SyntaxKind): void; - /** - * Determines whether before/after emit notifications should be raised in the pretty - * printer when it emits a node. - */ - isEmitNotificationEnabled(node: Node): boolean; - /** - * Hook used to allow transformers to capture state before or after - * the printer emits a node. - * - * NOTE: Transformation hooks should only be modified during `Transformer` initialization, - * before returning the `NodeTransformer` callback. - */ - onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; - } - interface TransformationResult { - /** Gets the transformed source files. */ - transformed: T[]; - /** Gets diagnostics for the transformation. */ - diagnostics?: DiagnosticWithLocation[]; - /** - * Gets a substitute for a node, if one is available; otherwise, returns the original node. - * - * @param hint A hint as to the intended usage of the node. - * @param node The node to substitute. - */ - substituteNode(hint: EmitHint, node: Node): Node; - /** - * Emits a node with possible notification. - * - * @param hint A hint as to the intended usage of the node. - * @param node The node to emit. - * @param emitCallback A callback used to emit the node. - */ - emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; - /** - * Indicates if a given node needs an emit notification - * - * @param node The node to emit. - */ - isEmitNotificationEnabled?(node: Node): boolean; - /** - * Clean up EmitNode entries on any parse-tree nodes. - */ - dispose(): void; - } - /** - * A function that is used to initialize and return a `Transformer` callback, which in turn - * will be used to transform one or more nodes. - */ - type TransformerFactory = (context: TransformationContext) => Transformer; - /** - * A function that transforms a node. - */ - type Transformer = (node: T) => T; - /** - * A function that accepts and possibly transforms a node. - */ - type Visitor = (node: TIn) => VisitResult; - /** - * A function that walks a node using the given visitor, lifting node arrays into single nodes, - * returning an node which satisfies the test. - * - * - If the input node is undefined, then the output is undefined. - * - If the visitor returns undefined, then the output is undefined. - * - If the output node is not undefined, then it will satisfy the test function. - * - In order to obtain a return type that is more specific than `Node`, a test - * function _must_ be provided, and that function must be a type predicate. - * - * For the canonical implementation of this type, @see {visitNode}. - */ - interface NodeVisitor { - (node: TIn, visitor: Visitor, TVisited>, test: (node: Node) => node is TOut, lift?: (node: readonly Node[]) => Node): TOut | (TIn & undefined) | (TVisited & undefined); - (node: TIn, visitor: Visitor, TVisited>, test?: (node: Node) => boolean, lift?: (node: readonly Node[]) => Node): Node | (TIn & undefined) | (TVisited & undefined); - } - /** - * A function that walks a node array using the given visitor, returning an array whose contents satisfy the test. - * - * - If the input node array is undefined, the output is undefined. - * - If the visitor can return undefined, the node it visits in the array will be reused. - * - If the output node array is not undefined, then its contents will satisfy the test. - * - In order to obtain a return type that is more specific than `NodeArray`, a test - * function _must_ be provided, and that function must be a type predicate. - * - * For the canonical implementation of this type, @see {visitNodes}. - */ - interface NodesVisitor { - | undefined, TOut extends Node>(nodes: TInArray, visitor: Visitor, test: (node: Node) => node is TOut, start?: number, count?: number): NodeArray | (TInArray & undefined); - | undefined>(nodes: TInArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray | (TInArray & undefined); - } - type VisitResult = T | readonly Node[]; - interface Printer { - /** - * Print a node and its subtree as-is, without any emit transformations. - * @param hint A value indicating the purpose of a node. This is primarily used to - * distinguish between an `Identifier` used in an expression position, versus an - * `Identifier` used as an `IdentifierName` as part of a declaration. For most nodes you - * should just pass `Unspecified`. - * @param node The node to print. The node and its subtree are printed as-is, without any - * emit transformations. - * @param sourceFile A source file that provides context for the node. The source text of - * the file is used to emit the original source content for literals and identifiers, while - * the identifiers of the source file are used when generating unique names to avoid - * collisions. - */ - printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; - /** - * Prints a list of nodes using the given format flags - */ - printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; - /** - * Prints a source file as-is, without any emit transformations. - */ - printFile(sourceFile: SourceFile): string; - /** - * Prints a bundle of source files as-is, without any emit transformations. - */ - printBundle(bundle: Bundle): string; - } - interface PrintHandlers { - /** - * A hook used by the Printer when generating unique names to avoid collisions with - * globally defined names that exist outside of the current source file. - */ - hasGlobalName?(name: string): boolean; - /** - * A hook used by the Printer to provide notifications prior to emitting a node. A - * compatible implementation **must** invoke `emitCallback` with the provided `hint` and - * `node` values. - * @param hint A hint indicating the intended purpose of the node. - * @param node The node to emit. - * @param emitCallback A callback that, when invoked, will emit the node. - * @example - * ```ts - * var printer = createPrinter(printerOptions, { - * onEmitNode(hint, node, emitCallback) { - * // set up or track state prior to emitting the node... - * emitCallback(hint, node); - * // restore state after emitting the node... - * } - * }); - * ``` - */ - onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; - /** - * A hook used to check if an emit notification is required for a node. - * @param node The node to emit. - */ - isEmitNotificationEnabled?(node: Node): boolean; - /** - * A hook used by the Printer to perform just-in-time substitution of a node. This is - * primarily used by node transformations that need to substitute one node for another, - * such as replacing `myExportedVar` with `exports.myExportedVar`. - * @param hint A hint indicating the intended purpose of the node. - * @param node The node to emit. - * @example - * ```ts - * var printer = createPrinter(printerOptions, { - * substituteNode(hint, node) { - * // perform substitution if necessary... - * return node; - * } - * }); - * ``` - */ - substituteNode?(hint: EmitHint, node: Node): Node; - } - interface PrinterOptions { - removeComments?: boolean; - newLine?: NewLineKind; - omitTrailingSemicolon?: boolean; - noEmitHelpers?: boolean; - } - interface GetEffectiveTypeRootsHost { - getCurrentDirectory?(): string; - } - interface TextSpan { - start: number; - length: number; - } - interface TextChangeRange { - span: TextSpan; - newLength: number; - } - interface SyntaxList extends Node { - kind: SyntaxKind.SyntaxList; - _children: Node[]; - } - enum ListFormat { - None = 0, - SingleLine = 0, - MultiLine = 1, - PreserveLines = 2, - LinesMask = 3, - NotDelimited = 0, - BarDelimited = 4, - AmpersandDelimited = 8, - CommaDelimited = 16, - AsteriskDelimited = 32, - DelimitersMask = 60, - AllowTrailingComma = 64, - Indented = 128, - SpaceBetweenBraces = 256, - SpaceBetweenSiblings = 512, - Braces = 1024, - Parenthesis = 2048, - AngleBrackets = 4096, - SquareBrackets = 8192, - BracketsMask = 15360, - OptionalIfUndefined = 16384, - OptionalIfEmpty = 32768, - Optional = 49152, - PreferNewLine = 65536, - NoTrailingNewLine = 131072, - NoInterveningComments = 262144, - NoSpaceIfEmpty = 524288, - SingleElement = 1048576, - SpaceAfterList = 2097152, - Modifiers = 2359808, - HeritageClauses = 512, - SingleLineTypeLiteralMembers = 768, - MultiLineTypeLiteralMembers = 32897, - SingleLineTupleTypeElements = 528, - MultiLineTupleTypeElements = 657, - UnionTypeConstituents = 516, - IntersectionTypeConstituents = 520, - ObjectBindingPatternElements = 525136, - ArrayBindingPatternElements = 524880, - ObjectLiteralExpressionProperties = 526226, - ImportClauseEntries = 526226, - ArrayLiteralExpressionElements = 8914, - CommaListElements = 528, - CallExpressionArguments = 2576, - NewExpressionArguments = 18960, - TemplateExpressionSpans = 262144, - SingleLineBlockStatements = 768, - MultiLineBlockStatements = 129, - VariableDeclarationList = 528, - SingleLineFunctionBodyStatements = 768, - MultiLineFunctionBodyStatements = 1, - ClassHeritageClauses = 0, - ClassMembers = 129, - InterfaceMembers = 129, - EnumMembers = 145, - CaseBlockClauses = 129, - NamedImportsOrExportsElements = 525136, - JsxElementOrFragmentChildren = 262144, - JsxElementAttributes = 262656, - CaseOrDefaultClauseStatements = 163969, - HeritageClauseTypes = 528, - SourceFileStatements = 131073, - Decorators = 2146305, - TypeArguments = 53776, - TypeParameters = 53776, - Parameters = 2576, - IndexSignatureParameters = 8848, - JSDocComment = 33 - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "auto" | "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsForImportStatements?: boolean; - readonly includeCompletionsWithSnippetText?: boolean; - readonly includeAutomaticOptionalChainCompletions?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly includeCompletionsWithClassMemberSnippets?: boolean; - readonly includeCompletionsWithObjectLiteralMethodSnippets?: boolean; - readonly useLabelDetailsInCompletionEntries?: boolean; - readonly allowIncompleteCompletions?: boolean; - readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; - /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ - readonly importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js"; - readonly allowTextChangesInNewFiles?: boolean; - readonly providePrefixAndSuffixTextForRename?: boolean; - readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; - readonly provideRefactorNotApplicableReason?: boolean; - readonly jsxAttributeCompletionStyle?: "auto" | "braces" | "none"; - readonly includeInlayParameterNameHints?: "none" | "literals" | "all"; - readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; - readonly includeInlayFunctionParameterTypeHints?: boolean; - readonly includeInlayVariableTypeHints?: boolean; - readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; - readonly includeInlayPropertyDeclarationTypeHints?: boolean; - readonly includeInlayFunctionLikeReturnTypeHints?: boolean; - readonly includeInlayEnumMemberValueHints?: boolean; - readonly interactiveInlayHints?: boolean; - readonly allowRenameOfImportPath?: boolean; - readonly autoImportFileExcludePatterns?: string[]; - readonly organizeImportsIgnoreCase?: "auto" | boolean; - readonly organizeImportsCollation?: "ordinal" | "unicode"; - readonly organizeImportsLocale?: string; - readonly organizeImportsNumericCollation?: boolean; - readonly organizeImportsAccentCollation?: boolean; - readonly organizeImportsCaseFirst?: "upper" | "lower" | false; - } - /** Represents a bigint literal value without requiring bigint support */ - interface PseudoBigInt { - negative: boolean; - base10Value: string; - } - enum FileWatcherEventKind { - Created = 0, - Changed = 1, - Deleted = 2 - } - type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, modifiedTime?: Date) => void; - type DirectoryWatcherCallback = (fileName: string) => void; - type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; - interface System { - args: string[]; - newLine: string; - useCaseSensitiveFileNames: boolean; - write(s: string): void; - writeOutputIsTTY?(): boolean; - getWidthOfTerminal?(): number; - readFile(path: string, encoding?: string): string | undefined; - getFileSize?(path: string): number; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - /** - * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that - * use native OS file watching - */ - watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; - watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; - resolvePath(path: string): string; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getExecutingFilePath(): string; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; - getModifiedTime?(path: string): Date | undefined; - setModifiedTime?(path: string, time: Date): void; - deleteFile?(path: string): void; - /** - * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) - */ - createHash?(data: string): string; - /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */ - createSHA256Hash?(data: string): string; - getMemoryUsage?(): number; - exit(exitCode?: number): void; - realpath?(path: string): string; - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - clearTimeout?(timeoutId: any): void; - clearScreen?(): void; - base64decode?(input: string): string; - base64encode?(input: string): string; - } - interface FileWatcher { - close(): void; - } - let sys: System; - function tokenToString(t: SyntaxKind): string | undefined; - function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number; - function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; - function isWhiteSpaceLike(ch: number): boolean; - /** Does not include line breaks. For that, see isWhiteSpaceLike. */ - function isWhiteSpaceSingleLine(ch: number): boolean; - function isLineBreak(ch: number): boolean; - function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; - function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U): U | undefined; - function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U): U | undefined; - function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; - function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; - /** Optionally, get the shebang */ - function getShebang(text: string): string | undefined; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined, identifierVariant?: LanguageVariant): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; - type ErrorCallback = (message: DiagnosticMessage, length: number, arg0?: any) => void; - interface Scanner { - /** @deprecated use {@link getTokenFullStart} */ - getStartPos(): number; - getToken(): SyntaxKind; - getTokenFullStart(): number; - getTokenStart(): number; - getTokenEnd(): number; - /** @deprecated use {@link getTokenEnd} */ - getTextPos(): number; - /** @deprecated use {@link getTokenStart} */ - getTokenPos(): number; - getTokenText(): string; - getTokenValue(): string; - hasUnicodeEscape(): boolean; - hasExtendedUnicodeEscape(): boolean; - hasPrecedingLineBreak(): boolean; - isIdentifier(): boolean; - isReservedWord(): boolean; - isUnterminated(): boolean; - reScanGreaterToken(): SyntaxKind; - reScanSlashToken(): SyntaxKind; - reScanAsteriskEqualsToken(): SyntaxKind; - reScanTemplateToken(isTaggedTemplate: boolean): SyntaxKind; - /** @deprecated use {@link reScanTemplateToken}(false) */ - reScanTemplateHeadOrNoSubstitutionTemplate(): SyntaxKind; - scanJsxIdentifier(): SyntaxKind; - scanJsxAttributeValue(): SyntaxKind; - reScanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind; - reScanLessThanToken(): SyntaxKind; - reScanHashToken(): SyntaxKind; - reScanQuestionToken(): SyntaxKind; - reScanInvalidIdentifier(): SyntaxKind; - scanJsxToken(): JsxTokenSyntaxKind; - scanJsDocToken(): JSDocSyntaxKind; - scan(): SyntaxKind; - getText(): string; - setText(text: string | undefined, start?: number, length?: number): void; - setOnError(onError: ErrorCallback | undefined): void; - setScriptTarget(scriptTarget: ScriptTarget): void; - setLanguageVariant(variant: LanguageVariant): void; - /** @deprecated use {@link resetTokenState} */ - setTextPos(textPos: number): void; - resetTokenState(pos: number): void; - lookAhead(callback: () => T): T; - scanRange(start: number, length: number, callback: () => T): T; - tryScan(callback: () => T): T; - } - function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: readonly T[]): SortedReadonlyArray; - function getDefaultLibFileName(options: CompilerOptions): string; - function textSpanEnd(span: TextSpan): number; - function textSpanIsEmpty(span: TextSpan): boolean; - function textSpanContainsPosition(span: TextSpan, position: number): boolean; - function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; - function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; - function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; - function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; - function createTextSpan(start: number, length: number): TextSpan; - function createTextSpanFromBounds(start: number, end: number): TextSpan; - function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; - function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; - function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; - /** - * Called to merge all the changes that occurred across several versions of a script snapshot - * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * - * This function will then merge those changes into a single change range valid between V1 and - * Vn. - */ - function collapseTextChangeRangesAcrossMultipleVersions(changes: readonly TextChangeRange[]): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration | undefined; - function isParameterPropertyDeclaration(node: Node, parent: Node): node is ParameterPropertyDeclaration; - function isEmptyBindingPattern(node: BindingName): node is BindingPattern; - function isEmptyBindingElement(node: BindingElement | ArrayBindingElement): boolean; - function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration; - function getCombinedModifierFlags(node: Declaration): ModifierFlags; - function getCombinedNodeFlags(node: Node): NodeFlags; - /** - * Checks to see if the locale is in the appropriate format, - * and if it is, attempts to set the appropriate language. - */ - function validateLocaleAndSetLanguage(locale: string, sys: { - getExecutingFilePath(): string; - resolvePath(path: string): string; - fileExists(fileName: string): boolean; - readFile(fileName: string): string | undefined; - }, errors?: Diagnostic[]): void; - function getOriginalNode(node: Node): Node; - function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; - function getOriginalNode(node: Node | undefined): Node | undefined; - function getOriginalNode(node: Node | undefined, nodeTest: (node: Node) => node is T): T | undefined; - /** - * Iterates through the parent chain of a node and performs the callback on each parent until the callback - * returns a truthy value, then returns that value. - * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" - * At that point findAncestor returns undefined. - */ - function findAncestor(node: Node | undefined, callback: (element: Node) => element is T): T | undefined; - function findAncestor(node: Node | undefined, callback: (element: Node) => boolean | "quit"): Node | undefined; - /** - * Gets a value indicating whether a node originated in the parse tree. - * - * @param node The node to test. - */ - function isParseTreeNode(node: Node): boolean; - /** - * Gets the original parse tree node for a node. - * - * @param node The original node. - * @returns The original parse tree node if found; otherwise, undefined. - */ - function getParseTreeNode(node: Node | undefined): Node | undefined; - /** - * Gets the original parse tree node for a node. - * - * @param node The original node. - * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. - * @returns The original parse tree node if found; otherwise, undefined. - */ - function getParseTreeNode(node: T | undefined, nodeTest?: (node: Node) => node is T): T | undefined; - /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ - function escapeLeadingUnderscores(identifier: string): __String; - /** - * Remove extra underscore from escaped identifier text content. - * - * @param identifier The escaped identifier text. - * @returns The unescaped identifier text. - */ - function unescapeLeadingUnderscores(identifier: __String): string; - function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string; - /** - * If the text of an Identifier matches a keyword (including contextual and TypeScript-specific keywords), returns the - * SyntaxKind for the matching keyword. - */ - function identifierToKeywordKind(node: Identifier): KeywordSyntaxKind | undefined; - function symbolName(symbol: Symbol): string; - function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined; - function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined; - function getDecorators(node: HasDecorators): readonly Decorator[] | undefined; - function getModifiers(node: HasModifiers): readonly Modifier[] | undefined; - /** - * Gets the JSDoc parameter tags for the node if present. - * - * @remarks Returns any JSDoc param tag whose name matches the provided - * parameter, whether a param tag on a containing function - * expression, or a param tag on a variable declaration whose - * initializer is the containing function. The tags closest to the - * node are returned first, so in the previous example, the param - * tag on the containing function expression would be first. - * - * For binding patterns, parameter tags are matched by position. - */ - function getJSDocParameterTags(param: ParameterDeclaration): readonly JSDocParameterTag[]; - /** - * Gets the JSDoc type parameter tags for the node if present. - * - * @remarks Returns any JSDoc template tag whose names match the provided - * parameter, whether a template tag on a containing function - * expression, or a template tag on a variable declaration whose - * initializer is the containing function. The tags closest to the - * node are returned first, so in the previous example, the template - * tag on the containing function expression would be first. - */ - function getJSDocTypeParameterTags(param: TypeParameterDeclaration): readonly JSDocTemplateTag[]; - /** - * Return true if the node has JSDoc parameter tags. - * - * @remarks Includes parameter tags that are not directly on the node, - * for example on a variable declaration whose initializer is a function expression. - */ - function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; - /** Gets the JSDoc augments tag for the node if present */ - function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; - /** Gets the JSDoc implements tags for the node if present */ - function getJSDocImplementsTags(node: Node): readonly JSDocImplementsTag[]; - /** Gets the JSDoc class tag for the node if present */ - function getJSDocClassTag(node: Node): JSDocClassTag | undefined; - /** Gets the JSDoc public tag for the node if present */ - function getJSDocPublicTag(node: Node): JSDocPublicTag | undefined; - /** Gets the JSDoc private tag for the node if present */ - function getJSDocPrivateTag(node: Node): JSDocPrivateTag | undefined; - /** Gets the JSDoc protected tag for the node if present */ - function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined; - /** Gets the JSDoc protected tag for the node if present */ - function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined; - function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined; - /** Gets the JSDoc deprecated tag for the node if present */ - function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined; - /** Gets the JSDoc enum tag for the node if present */ - function getJSDocEnumTag(node: Node): JSDocEnumTag | undefined; - /** Gets the JSDoc this tag for the node if present */ - function getJSDocThisTag(node: Node): JSDocThisTag | undefined; - /** Gets the JSDoc return tag for the node if present */ - function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; - /** Gets the JSDoc template tag for the node if present */ - function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined; - function getJSDocSatisfiesTag(node: Node): JSDocSatisfiesTag | undefined; - /** Gets the JSDoc type tag for the node if present and valid */ - function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined; - /** - * Gets the type node for the node if provided via JSDoc. - * - * @remarks The search includes any JSDoc param tag that relates - * to the provided parameter, for example a type tag on the - * parameter itself, or a param tag on a containing function - * expression, or a param tag on a variable declaration whose - * initializer is the containing function. The tags closest to the - * node are examined first, so in the previous example, the type - * tag directly on the node would be returned. - */ - function getJSDocType(node: Node): TypeNode | undefined; - /** - * Gets the return type node for the node if provided via JSDoc return tag or type tag. - * - * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces, after the fat arrow, etc. - */ - function getJSDocReturnType(node: Node): TypeNode | undefined; - /** Get all JSDoc tags related to a node, including those on parent nodes. */ - function getJSDocTags(node: Node): readonly JSDocTag[]; - /** Gets all JSDoc tags that match a specified predicate */ - function getAllJSDocTags(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[]; - /** Gets all JSDoc tags of a specified kind */ - function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[]; - /** Gets the text of a jsdoc comment, flattening links to their text. */ - function getTextOfJSDocComment(comment?: string | NodeArray): string | undefined; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - * - * This does *not* return type parameters from a jsdoc reference to a generic type, eg - * - * type Id = (x: T) => T - * /** @type {Id} / - * function id(x) { return x } - */ - function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[]; - function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined; - function isMemberName(node: Node): node is MemberName; - function isPropertyAccessChain(node: Node): node is PropertyAccessChain; - function isElementAccessChain(node: Node): node is ElementAccessChain; - function isCallChain(node: Node): node is CallChain; - function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain | NonNullChain; - function isNullishCoalesce(node: Node): boolean; - function isConstTypeReference(node: Node): boolean; - function skipPartiallyEmittedExpressions(node: Expression): Expression; - function skipPartiallyEmittedExpressions(node: Node): Node; - function isNonNullChain(node: Node): node is NonNullChain; - function isBreakOrContinueStatement(node: Node): node is BreakOrContinueStatement; - function isNamedExportBindings(node: Node): node is NamedExportBindings; - /** @deprecated */ - function isUnparsedTextLike(node: Node): node is UnparsedTextLike; - /** @deprecated */ - function isUnparsedNode(node: Node): node is UnparsedNode; - function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; - /** - * True if kind is of some token syntax kind. - * For example, this is true for an IfKeyword but not for an IfStatement. - * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. - */ - function isTokenKind(kind: SyntaxKind): boolean; - /** - * True if node is of some token syntax kind. - * For example, this is true for an IfKeyword but not for an IfStatement. - * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. - */ - function isToken(n: Node): boolean; - function isLiteralExpression(node: Node): node is LiteralExpression; - function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; - function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; - function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier; - function isTypeOnlyImportDeclaration(node: Node): node is TypeOnlyImportDeclaration; - function isTypeOnlyExportDeclaration(node: Node): node is TypeOnlyExportDeclaration; - function isTypeOnlyImportOrExportDeclaration(node: Node): node is TypeOnlyAliasDeclaration; - function isAssertionKey(node: Node): node is AssertionKey; - function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; - function isModifier(node: Node): node is Modifier; - function isEntityName(node: Node): node is EntityName; - function isPropertyName(node: Node): node is PropertyName; - function isBindingName(node: Node): node is BindingName; - function isFunctionLike(node: Node | undefined): node is SignatureDeclaration; - function isClassElement(node: Node): node is ClassElement; - function isClassLike(node: Node): node is ClassLikeDeclaration; - function isAccessor(node: Node): node is AccessorDeclaration; - function isAutoAccessorPropertyDeclaration(node: Node): node is AutoAccessorPropertyDeclaration; - function isModifierLike(node: Node): node is ModifierLike; - function isTypeElement(node: Node): node is TypeElement; - function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; - function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; - /** - * Node test that determines whether a node is a valid type node. - * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* - * of a TypeNode. - */ - function isTypeNode(node: Node): node is TypeNode; - function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; - function isArrayBindingElement(node: Node): node is ArrayBindingElement; - function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; - function isCallLikeExpression(node: Node): node is CallLikeExpression; - function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; - function isTemplateLiteral(node: Node): node is TemplateLiteral; - function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression; - function isLiteralTypeLiteral(node: Node): node is NullLiteral | BooleanLiteral | LiteralExpression | PrefixUnaryExpression; - /** - * Determines whether a node is an expression based only on its kind. - */ - function isExpression(node: Node): node is Expression; - function isAssertionExpression(node: Node): node is AssertionExpression; - function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; - function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; - function isConciseBody(node: Node): node is ConciseBody; - function isForInitializer(node: Node): node is ForInitializer; - function isModuleBody(node: Node): node is ModuleBody; - function isNamedImportBindings(node: Node): node is NamedImportBindings; - function isStatement(node: Node): node is Statement; - function isModuleReference(node: Node): node is ModuleReference; - function isJsxTagNameExpression(node: Node): node is JsxTagNameExpression; - function isJsxChild(node: Node): node is JsxChild; - function isJsxAttributeLike(node: Node): node is JsxAttributeLike; - function isStringLiteralOrJsxExpression(node: Node): node is StringLiteral | JsxExpression; - function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; - function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; - /** True if node is of a kind that may contain comment text. */ - function isJSDocCommentContainingNode(node: Node): boolean; - function isSetAccessor(node: Node): node is SetAccessorDeclaration; - function isGetAccessor(node: Node): node is GetAccessorDeclaration; - /** True if has initializer node attached to it. */ - function hasOnlyExpressionInitializer(node: Node): node is HasExpressionInitializer; - function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; - function isStringLiteralLike(node: Node | FileReference): node is StringLiteralLike; - function isJSDocLinkLike(node: Node): node is JSDocLink | JSDocLinkCode | JSDocLinkPlain; - function hasRestParameter(s: SignatureDeclaration | JSDocSignature): boolean; - function isRestParameter(node: ParameterDeclaration | JSDocParameterTag): boolean; - let unchangedTextChangeRange: TextChangeRange; - type ParameterPropertyDeclaration = ParameterDeclaration & { - parent: ConstructorDeclaration; - name: Identifier; - }; - /** - * This function checks multiple locations for JSDoc comments that apply to a host node. - * At each location, the whole comment may apply to the node, or only a specific tag in - * the comment. In the first case, location adds the entire {@link JSDoc} object. In the - * second case, it adds the applicable {@link JSDocTag}. - * - * For example, a JSDoc comment before a parameter adds the entire {@link JSDoc}. But a - * `@param` tag on the parent function only adds the {@link JSDocTag} for the `@param`. - * - * ```ts - * /** JSDoc will be returned for `a` *\/ - * const a = 0 - * /** - * * Entire JSDoc will be returned for `b` - * * @param c JSDocTag will be returned for `c` - * *\/ - * function b(/** JSDoc will be returned for `c` *\/ c) {} - * ``` - */ - function getJSDocCommentsAndTags(hostNode: Node): readonly (JSDoc | JSDocTag)[]; - /** @deprecated */ - function createUnparsedSourceFile(text: string): UnparsedSource; - /** @deprecated */ - function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource; - /** @deprecated */ - function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource; - /** @deprecated */ - function createInputFiles(javascriptText: string, declarationText: string): InputFiles; - /** @deprecated */ - function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles; - /** @deprecated */ - function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, buildInfoPath: string | undefined): InputFiles; - /** - * Create an external source map source file reference - */ - function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource; - function setOriginalNode(node: T, original: Node | undefined): T; - const factory: NodeFactory; - /** - * Clears any `EmitNode` entries from parse-tree nodes. - * @param sourceFile A source file. - */ - function disposeEmitNodes(sourceFile: SourceFile | undefined): void; - /** - * Sets flags that control emit behavior of a node. - */ - function setEmitFlags(node: T, emitFlags: EmitFlags): T; - /** - * Gets a custom text range to use when emitting source maps. - */ - function getSourceMapRange(node: Node): SourceMapRange; - /** - * Sets a custom text range to use when emitting source maps. - */ - function setSourceMapRange(node: T, range: SourceMapRange | undefined): T; - /** - * Gets the TextRange to use for source maps for a token of a node. - */ - function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined; - /** - * Sets the TextRange to use for source maps for a token of a node. - */ - function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; - /** - * Gets a custom text range to use when emitting comments. - */ - function getCommentRange(node: Node): TextRange; - /** - * Sets a custom text range to use when emitting comments. - */ - function setCommentRange(node: T, range: TextRange): T; - function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T; - function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; - function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T; - function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; - function moveSyntheticComments(node: T, original: Node): T; - /** - * Gets the constant value to emit for an expression representing an enum. - */ - function getConstantValue(node: AccessExpression): string | number | undefined; - /** - * Sets the constant value to emit for an expression. - */ - function setConstantValue(node: AccessExpression, value: string | number): AccessExpression; - /** - * Adds an EmitHelper to a node. - */ - function addEmitHelper(node: T, helper: EmitHelper): T; - /** - * Add EmitHelpers to a node. - */ - function addEmitHelpers(node: T, helpers: EmitHelper[] | undefined): T; - /** - * Removes an EmitHelper from a node. - */ - function removeEmitHelper(node: Node, helper: EmitHelper): boolean; - /** - * Gets the EmitHelpers of a node. - */ - function getEmitHelpers(node: Node): EmitHelper[] | undefined; - /** - * Moves matching emit helpers from a source node to a target node. - */ - function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; - function isNumericLiteral(node: Node): node is NumericLiteral; - function isBigIntLiteral(node: Node): node is BigIntLiteral; - function isStringLiteral(node: Node): node is StringLiteral; - function isJsxText(node: Node): node is JsxText; - function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; - function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral; - function isTemplateHead(node: Node): node is TemplateHead; - function isTemplateMiddle(node: Node): node is TemplateMiddle; - function isTemplateTail(node: Node): node is TemplateTail; - function isDotDotDotToken(node: Node): node is DotDotDotToken; - function isPlusToken(node: Node): node is PlusToken; - function isMinusToken(node: Node): node is MinusToken; - function isAsteriskToken(node: Node): node is AsteriskToken; - function isExclamationToken(node: Node): node is ExclamationToken; - function isQuestionToken(node: Node): node is QuestionToken; - function isColonToken(node: Node): node is ColonToken; - function isQuestionDotToken(node: Node): node is QuestionDotToken; - function isEqualsGreaterThanToken(node: Node): node is EqualsGreaterThanToken; - function isIdentifier(node: Node): node is Identifier; - function isPrivateIdentifier(node: Node): node is PrivateIdentifier; - function isAssertsKeyword(node: Node): node is AssertsKeyword; - function isAwaitKeyword(node: Node): node is AwaitKeyword; - function isQualifiedName(node: Node): node is QualifiedName; - function isComputedPropertyName(node: Node): node is ComputedPropertyName; - function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; - function isParameter(node: Node): node is ParameterDeclaration; - function isDecorator(node: Node): node is Decorator; - function isPropertySignature(node: Node): node is PropertySignature; - function isPropertyDeclaration(node: Node): node is PropertyDeclaration; - function isMethodSignature(node: Node): node is MethodSignature; - function isMethodDeclaration(node: Node): node is MethodDeclaration; - function isClassStaticBlockDeclaration(node: Node): node is ClassStaticBlockDeclaration; - function isConstructorDeclaration(node: Node): node is ConstructorDeclaration; - function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration; - function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration; - function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration; - function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration; - function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration; - function isTypePredicateNode(node: Node): node is TypePredicateNode; - function isTypeReferenceNode(node: Node): node is TypeReferenceNode; - function isFunctionTypeNode(node: Node): node is FunctionTypeNode; - function isConstructorTypeNode(node: Node): node is ConstructorTypeNode; - function isTypeQueryNode(node: Node): node is TypeQueryNode; - function isTypeLiteralNode(node: Node): node is TypeLiteralNode; - function isArrayTypeNode(node: Node): node is ArrayTypeNode; - function isTupleTypeNode(node: Node): node is TupleTypeNode; - function isNamedTupleMember(node: Node): node is NamedTupleMember; - function isOptionalTypeNode(node: Node): node is OptionalTypeNode; - function isRestTypeNode(node: Node): node is RestTypeNode; - function isUnionTypeNode(node: Node): node is UnionTypeNode; - function isIntersectionTypeNode(node: Node): node is IntersectionTypeNode; - function isConditionalTypeNode(node: Node): node is ConditionalTypeNode; - function isInferTypeNode(node: Node): node is InferTypeNode; - function isParenthesizedTypeNode(node: Node): node is ParenthesizedTypeNode; - function isThisTypeNode(node: Node): node is ThisTypeNode; - function isTypeOperatorNode(node: Node): node is TypeOperatorNode; - function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode; - function isMappedTypeNode(node: Node): node is MappedTypeNode; - function isLiteralTypeNode(node: Node): node is LiteralTypeNode; - function isImportTypeNode(node: Node): node is ImportTypeNode; - function isTemplateLiteralTypeSpan(node: Node): node is TemplateLiteralTypeSpan; - function isTemplateLiteralTypeNode(node: Node): node is TemplateLiteralTypeNode; - function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; - function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; - function isBindingElement(node: Node): node is BindingElement; - function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression; - function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression; - function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; - function isElementAccessExpression(node: Node): node is ElementAccessExpression; - function isCallExpression(node: Node): node is CallExpression; - function isNewExpression(node: Node): node is NewExpression; - function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; - function isTypeAssertionExpression(node: Node): node is TypeAssertion; - function isParenthesizedExpression(node: Node): node is ParenthesizedExpression; - function isFunctionExpression(node: Node): node is FunctionExpression; - function isArrowFunction(node: Node): node is ArrowFunction; - function isDeleteExpression(node: Node): node is DeleteExpression; - function isTypeOfExpression(node: Node): node is TypeOfExpression; - function isVoidExpression(node: Node): node is VoidExpression; - function isAwaitExpression(node: Node): node is AwaitExpression; - function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression; - function isPostfixUnaryExpression(node: Node): node is PostfixUnaryExpression; - function isBinaryExpression(node: Node): node is BinaryExpression; - function isConditionalExpression(node: Node): node is ConditionalExpression; - function isTemplateExpression(node: Node): node is TemplateExpression; - function isYieldExpression(node: Node): node is YieldExpression; - function isSpreadElement(node: Node): node is SpreadElement; - function isClassExpression(node: Node): node is ClassExpression; - function isOmittedExpression(node: Node): node is OmittedExpression; - function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; - function isAsExpression(node: Node): node is AsExpression; - function isSatisfiesExpression(node: Node): node is SatisfiesExpression; - function isNonNullExpression(node: Node): node is NonNullExpression; - function isMetaProperty(node: Node): node is MetaProperty; - function isSyntheticExpression(node: Node): node is SyntheticExpression; - function isPartiallyEmittedExpression(node: Node): node is PartiallyEmittedExpression; - function isCommaListExpression(node: Node): node is CommaListExpression; - function isTemplateSpan(node: Node): node is TemplateSpan; - function isSemicolonClassElement(node: Node): node is SemicolonClassElement; - function isBlock(node: Node): node is Block; - function isVariableStatement(node: Node): node is VariableStatement; - function isEmptyStatement(node: Node): node is EmptyStatement; - function isExpressionStatement(node: Node): node is ExpressionStatement; - function isIfStatement(node: Node): node is IfStatement; - function isDoStatement(node: Node): node is DoStatement; - function isWhileStatement(node: Node): node is WhileStatement; - function isForStatement(node: Node): node is ForStatement; - function isForInStatement(node: Node): node is ForInStatement; - function isForOfStatement(node: Node): node is ForOfStatement; - function isContinueStatement(node: Node): node is ContinueStatement; - function isBreakStatement(node: Node): node is BreakStatement; - function isReturnStatement(node: Node): node is ReturnStatement; - function isWithStatement(node: Node): node is WithStatement; - function isSwitchStatement(node: Node): node is SwitchStatement; - function isLabeledStatement(node: Node): node is LabeledStatement; - function isThrowStatement(node: Node): node is ThrowStatement; - function isTryStatement(node: Node): node is TryStatement; - function isDebuggerStatement(node: Node): node is DebuggerStatement; - function isVariableDeclaration(node: Node): node is VariableDeclaration; - function isVariableDeclarationList(node: Node): node is VariableDeclarationList; - function isFunctionDeclaration(node: Node): node is FunctionDeclaration; - function isClassDeclaration(node: Node): node is ClassDeclaration; - function isInterfaceDeclaration(node: Node): node is InterfaceDeclaration; - function isTypeAliasDeclaration(node: Node): node is TypeAliasDeclaration; - function isEnumDeclaration(node: Node): node is EnumDeclaration; - function isModuleDeclaration(node: Node): node is ModuleDeclaration; - function isModuleBlock(node: Node): node is ModuleBlock; - function isCaseBlock(node: Node): node is CaseBlock; - function isNamespaceExportDeclaration(node: Node): node is NamespaceExportDeclaration; - function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; - function isImportDeclaration(node: Node): node is ImportDeclaration; - function isImportClause(node: Node): node is ImportClause; - function isImportTypeAssertionContainer(node: Node): node is ImportTypeAssertionContainer; - function isAssertClause(node: Node): node is AssertClause; - function isAssertEntry(node: Node): node is AssertEntry; - function isNamespaceImport(node: Node): node is NamespaceImport; - function isNamespaceExport(node: Node): node is NamespaceExport; - function isNamedImports(node: Node): node is NamedImports; - function isImportSpecifier(node: Node): node is ImportSpecifier; - function isExportAssignment(node: Node): node is ExportAssignment; - function isExportDeclaration(node: Node): node is ExportDeclaration; - function isNamedExports(node: Node): node is NamedExports; - function isExportSpecifier(node: Node): node is ExportSpecifier; - function isMissingDeclaration(node: Node): node is MissingDeclaration; - function isNotEmittedStatement(node: Node): node is NotEmittedStatement; - function isExternalModuleReference(node: Node): node is ExternalModuleReference; - function isJsxElement(node: Node): node is JsxElement; - function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; - function isJsxOpeningElement(node: Node): node is JsxOpeningElement; - function isJsxClosingElement(node: Node): node is JsxClosingElement; - function isJsxFragment(node: Node): node is JsxFragment; - function isJsxOpeningFragment(node: Node): node is JsxOpeningFragment; - function isJsxClosingFragment(node: Node): node is JsxClosingFragment; - function isJsxAttribute(node: Node): node is JsxAttribute; - function isJsxAttributes(node: Node): node is JsxAttributes; - function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; - function isJsxExpression(node: Node): node is JsxExpression; - function isJsxNamespacedName(node: Node): node is JsxNamespacedName; - function isCaseClause(node: Node): node is CaseClause; - function isDefaultClause(node: Node): node is DefaultClause; - function isHeritageClause(node: Node): node is HeritageClause; - function isCatchClause(node: Node): node is CatchClause; - function isPropertyAssignment(node: Node): node is PropertyAssignment; - function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment; - function isSpreadAssignment(node: Node): node is SpreadAssignment; - function isEnumMember(node: Node): node is EnumMember; - /** @deprecated */ - function isUnparsedPrepend(node: Node): node is UnparsedPrepend; - function isSourceFile(node: Node): node is SourceFile; - function isBundle(node: Node): node is Bundle; - /** @deprecated */ - function isUnparsedSource(node: Node): node is UnparsedSource; - function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; - function isJSDocNameReference(node: Node): node is JSDocNameReference; - function isJSDocMemberName(node: Node): node is JSDocMemberName; - function isJSDocLink(node: Node): node is JSDocLink; - function isJSDocLinkCode(node: Node): node is JSDocLinkCode; - function isJSDocLinkPlain(node: Node): node is JSDocLinkPlain; - function isJSDocAllType(node: Node): node is JSDocAllType; - function isJSDocUnknownType(node: Node): node is JSDocUnknownType; - function isJSDocNullableType(node: Node): node is JSDocNullableType; - function isJSDocNonNullableType(node: Node): node is JSDocNonNullableType; - function isJSDocOptionalType(node: Node): node is JSDocOptionalType; - function isJSDocFunctionType(node: Node): node is JSDocFunctionType; - function isJSDocVariadicType(node: Node): node is JSDocVariadicType; - function isJSDocNamepathType(node: Node): node is JSDocNamepathType; - function isJSDoc(node: Node): node is JSDoc; - function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; - function isJSDocSignature(node: Node): node is JSDocSignature; - function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; - function isJSDocAuthorTag(node: Node): node is JSDocAuthorTag; - function isJSDocClassTag(node: Node): node is JSDocClassTag; - function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag; - function isJSDocPublicTag(node: Node): node is JSDocPublicTag; - function isJSDocPrivateTag(node: Node): node is JSDocPrivateTag; - function isJSDocProtectedTag(node: Node): node is JSDocProtectedTag; - function isJSDocReadonlyTag(node: Node): node is JSDocReadonlyTag; - function isJSDocOverrideTag(node: Node): node is JSDocOverrideTag; - function isJSDocOverloadTag(node: Node): node is JSDocOverloadTag; - function isJSDocDeprecatedTag(node: Node): node is JSDocDeprecatedTag; - function isJSDocSeeTag(node: Node): node is JSDocSeeTag; - function isJSDocEnumTag(node: Node): node is JSDocEnumTag; - function isJSDocParameterTag(node: Node): node is JSDocParameterTag; - function isJSDocReturnTag(node: Node): node is JSDocReturnTag; - function isJSDocThisTag(node: Node): node is JSDocThisTag; - function isJSDocTypeTag(node: Node): node is JSDocTypeTag; - function isJSDocTemplateTag(node: Node): node is JSDocTemplateTag; - function isJSDocTypedefTag(node: Node): node is JSDocTypedefTag; - function isJSDocUnknownTag(node: Node): node is JSDocUnknownTag; - function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; - function isJSDocImplementsTag(node: Node): node is JSDocImplementsTag; - function isJSDocSatisfiesTag(node: Node): node is JSDocSatisfiesTag; - function isJSDocThrowsTag(node: Node): node is JSDocThrowsTag; - function isQuestionOrExclamationToken(node: Node): node is QuestionToken | ExclamationToken; - function isIdentifierOrThisTypeNode(node: Node): node is Identifier | ThisTypeNode; - function isReadonlyKeywordOrPlusOrMinusToken(node: Node): node is ReadonlyKeyword | PlusToken | MinusToken; - function isQuestionOrPlusOrMinusToken(node: Node): node is QuestionToken | PlusToken | MinusToken; - function isModuleName(node: Node): node is ModuleName; - function isBinaryOperatorToken(node: Node): node is BinaryOperatorToken; - function setTextRange(range: T, location: TextRange | undefined): T; - function canHaveModifiers(node: Node): node is HasModifiers; - function canHaveDecorators(node: Node): node is HasDecorators; - /** - * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes - * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, - * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns - * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. - * - * @param node a given node to visit its children - * @param cbNode a callback to be invoked for all child nodes - * @param cbNodes a callback to be invoked for embedded array - * - * @remarks `forEachChild` must visit the children of a node in the order - * that they appear in the source code. The language service depends on this property to locate nodes by position. - */ - function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; - function createSourceFile(fileName: string, sourceText: string, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; - function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined; - /** - * Parse json text into SyntaxTree and return node and parse errors if any - * @param fileName - * @param sourceText - */ - function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; - function isExternalModule(file: SourceFile): boolean; - function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - interface CreateSourceFileOptions { - languageVersion: ScriptTarget; - /** - * Controls the format the file is detected as - this can be derived from only the path - * and files on disk, but needs to be done with a module resolution cache in scope to be performant. - * This is usually `undefined` for compilations that do not have `moduleResolution` values of `node16` or `nodenext`. - */ - impliedNodeFormat?: ResolutionMode; - /** - * Controls how module-y-ness is set for the given file. Usually the result of calling - * `getSetExternalModuleIndicator` on a valid `CompilerOptions` object. If not present, the default - * check specified by `isFileProbablyExternalModule` will be used to set the field. - */ - setExternalModuleIndicator?: (file: SourceFile) => void; - } - function parseCommandLine(commandLine: readonly string[], readFile?: (path: string) => string | undefined): ParsedCommandLine; - /** - * Reads the config file, reports errors if any and exits if the config file cannot be found - */ - function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions | undefined, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the text of the tsconfig.json file - * @param fileName The path to the config file - * @param jsonText The text of the config file - */ - function parseConfigFileTextToJson(fileName: string, jsonText: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; - /** - * Convert the json syntax tree into the json value - */ - function convertToObject(sourceFile: JsonSourceFile, errors: Diagnostic[]): any; - /** - * Parse the contents of a config file (tsconfig.json). - * @param json The contents of the config file to parse - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine; - /** - * Parse the contents of a config file (tsconfig.json). - * @param jsonNode The contents of the config file to parse - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: readonly FileExtensionInfo[], extendedConfigCache?: Map, existingWatchOptions?: WatchOptions): ParsedCommandLine; - function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; - errors: Diagnostic[]; - }; - function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: TypeAcquisition; - errors: Diagnostic[]; - }; - type DiagnosticReporter = (diagnostic: Diagnostic) => void; - /** - * Reports config file diagnostics - */ - interface ConfigFileDiagnosticsReporter { - /** - * Reports unrecoverable error when parsing config file - */ - onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; - } - /** - * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors - */ - interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { - getCurrentDirectory(): string; - } - interface ParsedTsconfig { - raw: any; - options?: CompilerOptions; - watchOptions?: WatchOptions; - typeAcquisition?: TypeAcquisition; - /** - * Note that the case of the config path has not yet been normalized, as no files have been imported into the project yet - */ - extendedConfigPath?: string | string[]; - } - interface ExtendedConfigCacheEntry { - extendedResult: TsConfigSourceFile; - extendedConfig: ParsedTsconfig | undefined; - } - function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache, resolutionMode?: ResolutionMode): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): ModuleResolutionCache; - function createTypeReferenceDirectiveResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache): TypeReferenceDirectiveResolutionCache; - function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache, mode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations; - function bundlerModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; - interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache, NonRelativeNameResolutionCache, PackageJsonInfoCache { - } - interface ModeAwareCache { - get(key: string, mode: ResolutionMode): T | undefined; - set(key: string, mode: ResolutionMode, value: T): this; - delete(key: string, mode: ResolutionMode): this; - has(key: string, mode: ResolutionMode): boolean; - forEach(cb: (elem: T, key: string, mode: ResolutionMode) => void): void; - size(): number; - } - /** - * Cached resolutions per containing directory. - * This assumes that any module id will have the same resolution for sibling files located in the same folder. - */ - interface PerDirectoryResolutionCache { - getFromDirectoryCache(name: string, mode: ResolutionMode, directoryName: string, redirectedReference: ResolvedProjectReference | undefined): T | undefined; - getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): ModeAwareCache; - clear(): void; - /** - * Updates with the current compilerOptions the cache will operate with. - * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects - */ - update(options: CompilerOptions): void; - } - interface NonRelativeNameResolutionCache { - getFromNonRelativeNameCache(nonRelativeName: string, mode: ResolutionMode, directoryName: string, redirectedReference: ResolvedProjectReference | undefined): T | undefined; - getOrCreateCacheForNonRelativeName(nonRelativeName: string, mode: ResolutionMode, redirectedReference?: ResolvedProjectReference): PerNonRelativeNameCache; - clear(): void; - /** - * Updates with the current compilerOptions the cache will operate with. - * This updates the redirects map as well if needed so module resolutions are cached if they can across the projects - */ - update(options: CompilerOptions): void; - } - interface PerNonRelativeNameCache { - get(directory: string): T | undefined; - set(directory: string, result: T): void; - } - interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { - getPackageJsonInfoCache(): PackageJsonInfoCache; - } - /** - * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory - * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. - */ - interface NonRelativeModuleNameResolutionCache extends NonRelativeNameResolutionCache, PackageJsonInfoCache { - /** @deprecated Use getOrCreateCacheForNonRelativeName */ - getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ResolutionMode, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; - } - interface PackageJsonInfoCache { - clear(): void; - } - type PerModuleNameCache = PerNonRelativeNameCache; - /** - * Visits a Node using the supplied visitor, possibly returning a new Node in its place. - * - * - If the input node is undefined, then the output is undefined. - * - If the visitor returns undefined, then the output is undefined. - * - If the output node is not undefined, then it will satisfy the test function. - * - In order to obtain a return type that is more specific than `Node`, a test - * function _must_ be provided, and that function must be a type predicate. - * - * @param node The Node to visit. - * @param visitor The callback used to visit the Node. - * @param test A callback to execute to verify the Node is valid. - * @param lift An optional callback to execute to lift a NodeArray into a valid Node. - */ - function visitNode(node: TIn, visitor: Visitor, TVisited>, test: (node: Node) => node is TOut, lift?: (node: readonly Node[]) => Node): TOut | (TIn & undefined) | (TVisited & undefined); - /** - * Visits a Node using the supplied visitor, possibly returning a new Node in its place. - * - * - If the input node is undefined, then the output is undefined. - * - If the visitor returns undefined, then the output is undefined. - * - If the output node is not undefined, then it will satisfy the test function. - * - In order to obtain a return type that is more specific than `Node`, a test - * function _must_ be provided, and that function must be a type predicate. - * - * @param node The Node to visit. - * @param visitor The callback used to visit the Node. - * @param test A callback to execute to verify the Node is valid. - * @param lift An optional callback to execute to lift a NodeArray into a valid Node. - */ - function visitNode(node: TIn, visitor: Visitor, TVisited>, test?: (node: Node) => boolean, lift?: (node: readonly Node[]) => Node): Node | (TIn & undefined) | (TVisited & undefined); - /** - * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. - * - * - If the input node array is undefined, the output is undefined. - * - If the visitor can return undefined, the node it visits in the array will be reused. - * - If the output node array is not undefined, then its contents will satisfy the test. - * - In order to obtain a return type that is more specific than `NodeArray`, a test - * function _must_ be provided, and that function must be a type predicate. - * - * @param nodes The NodeArray to visit. - * @param visitor The callback used to visit a Node. - * @param test A node test to execute for each node. - * @param start An optional value indicating the starting offset at which to start visiting. - * @param count An optional value indicating the maximum number of nodes to visit. - */ - function visitNodes | undefined, TOut extends Node>(nodes: TInArray, visitor: Visitor, test: (node: Node) => node is TOut, start?: number, count?: number): NodeArray | (TInArray & undefined); - /** - * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. - * - * - If the input node array is undefined, the output is undefined. - * - If the visitor can return undefined, the node it visits in the array will be reused. - * - If the output node array is not undefined, then its contents will satisfy the test. - * - In order to obtain a return type that is more specific than `NodeArray`, a test - * function _must_ be provided, and that function must be a type predicate. - * - * @param nodes The NodeArray to visit. - * @param visitor The callback used to visit a Node. - * @param test A node test to execute for each node. - * @param start An optional value indicating the starting offset at which to start visiting. - * @param count An optional value indicating the maximum number of nodes to visit. - */ - function visitNodes | undefined>(nodes: TInArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray | (TInArray & undefined); - /** - * Starts a new lexical environment and visits a statement list, ending the lexical environment - * and merging hoisted declarations upon completion. - */ - function visitLexicalEnvironment(statements: NodeArray, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean, nodesVisitor?: NodesVisitor): NodeArray; - /** - * Starts a new lexical environment and visits a parameter list, suspending the lexical - * environment upon completion. - */ - function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: NodesVisitor): NodeArray; - function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: NodesVisitor): NodeArray | undefined; - /** - * Resumes a suspended lexical environment and visits a function body, ending the lexical - * environment and merging hoisted declarations upon completion. - */ - function visitFunctionBody(node: FunctionBody, visitor: Visitor, context: TransformationContext): FunctionBody; - /** - * Resumes a suspended lexical environment and visits a function body, ending the lexical - * environment and merging hoisted declarations upon completion. - */ - function visitFunctionBody(node: FunctionBody | undefined, visitor: Visitor, context: TransformationContext): FunctionBody | undefined; - /** - * Resumes a suspended lexical environment and visits a concise body, ending the lexical - * environment and merging hoisted declarations upon completion. - */ - function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody; - /** - * Visits an iteration body, adding any block-scoped variables required by the transformation. - */ - function visitIterationBody(body: Statement, visitor: Visitor, context: TransformationContext): Statement; - /** - * Visits the elements of a {@link CommaListExpression}. - * @param visitor The visitor to use when visiting expressions whose result will not be discarded at runtime. - * @param discardVisitor The visitor to use when visiting expressions whose result will be discarded at runtime. Defaults to {@link visitor}. - */ - function visitCommaListElements(elements: NodeArray, visitor: Visitor, discardVisitor?: Visitor): NodeArray; - /** - * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. - * - * @param node The Node whose children will be visited. - * @param visitor The callback used to visit each child. - * @param context A lexical environment context for the visitor. - */ - function visitEachChild(node: T, visitor: Visitor, context: TransformationContext): T; - /** - * Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place. - * - * @param node The Node whose children will be visited. - * @param visitor The callback used to visit each child. - * @param context A lexical environment context for the visitor. - */ - function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined; - function getTsBuildInfoEmitOutputFilePath(options: CompilerOptions): string | undefined; - function getOutputFileNames(commandLine: ParsedCommandLine, inputFileName: string, ignoreCase: boolean): readonly string[]; - function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; - function formatDiagnostics(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string; - function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; - function formatDiagnosticsWithColorAndContext(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(diag: string | DiagnosticMessageChain | undefined, newLine: string, indent?: number): string; - /** - * Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly - * provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file. - */ - function getModeForFileReference(ref: FileReference | string, containingFileMode: ResolutionMode): ResolutionMode; - /** - * Calculates the final resolution mode for an import at some index within a file's imports list. This is generally the explicitly - * defined mode of the import if provided, or, if not, the mode of the containing file (with some exceptions: import=require is always commonjs, dynamic import is always esm). - * If you have an actual import node, prefer using getModeForUsageLocation on the reference string node. - * @param file File to fetch the resolution mode within - * @param index Index into the file's complete resolution list to get the resolution of - this is a concatenation of the file's imports and module augmentations - */ - function getModeForResolutionAtIndex(file: SourceFile, index: number): ResolutionMode; - /** - * Calculates the final resolution mode for a given module reference node. This is generally the explicitly provided resolution mode, if - * one exists, or the mode of the containing source file. (Excepting import=require, which is always commonjs, and dynamic import, which is always esm). - * Notably, this function always returns `undefined` if the containing file has an `undefined` `impliedNodeFormat` - this field is only set when - * `moduleResolution` is `node16`+. - * @param file The file the import or import-like reference is contained within - * @param usage The module reference string - * @returns The final resolution mode of the import - */ - function getModeForUsageLocation(file: { - impliedNodeFormat?: ResolutionMode; - }, usage: StringLiteralLike): ModuleKind.CommonJS | ModuleKind.ESNext | undefined; - function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): readonly Diagnostic[]; - /** - * A function for determining if a given file is esm or cjs format, assuming modern node module resolution rules, as configured by the - * `options` parameter. - * - * @param fileName The normalized absolute path to check the format of (it need not exist on disk) - * @param [packageJsonInfoCache] A cache for package file lookups - it's best to have a cache when this function is called often - * @param host The ModuleResolutionHost which can perform the filesystem lookups for package json data - * @param options The compiler options to perform the analysis under - relevant options are `moduleResolution` and `traceResolution` - * @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format - */ - function getImpliedNodeFormatForFile(fileName: Path, packageJsonInfoCache: PackageJsonInfoCache | undefined, host: ModuleResolutionHost, options: CompilerOptions): ResolutionMode; - /** - * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' - * that represent a compilation unit. - * - * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and - * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. - * - * @param createProgramOptions - The options for creating a program. - * @returns A 'Program' object. - */ - function createProgram(createProgramOptions: CreateProgramOptions): Program; - /** - * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' - * that represent a compilation unit. - * - * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and - * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. - * - * @param rootNames - A set of root files. - * @param options - The compiler options which should be used. - * @param host - The host interacts with the underlying file system. - * @param oldProgram - Reuses an old program structure. - * @param configFileParsingDiagnostics - error during config file parsing - * @returns A 'Program' object. - */ - function createProgram(rootNames: readonly string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: readonly Diagnostic[]): Program; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } - /** - * Create the builder to manage semantic diagnostics and cache them - */ - function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): SemanticDiagnosticsBuilderProgram; - /** - * Create the builder that can handle the changes in program and iterate through changed files - * to emit the those files and manage semantic diagnostics cache as well - */ - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): EmitAndSemanticDiagnosticsBuilderProgram; - /** - * Creates a builder thats just abstraction over program and can be used with watch - */ - function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): BuilderProgram; - function createAbstractBuilder(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderProgram; - type AffectedFileResult = { - result: T; - affected: SourceFile | Program; - } | undefined; - interface BuilderProgramHost { - /** - * If provided this would be used this hash instead of actual file shape text for detecting changes - */ - createHash?: (data: string) => string; - /** - * When emit or emitNextAffectedFile are called without writeFile, - * this callback if present would be used to write files - */ - writeFile?: WriteFileCallback; - } - /** - * Builder to manage the program state changes - */ - interface BuilderProgram { - /** - * Returns current program - */ - getProgram(): Program; - /** - * Get compiler options of the program - */ - getCompilerOptions(): CompilerOptions; - /** - * Get the source file in the program with file name - */ - getSourceFile(fileName: string): SourceFile | undefined; - /** - * Get a list of files in the program - */ - getSourceFiles(): readonly SourceFile[]; - /** - * Get the diagnostics for compiler options - */ - getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; - /** - * Get the diagnostics that dont belong to any file - */ - getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; - /** - * Get the diagnostics from config file parsing - */ - getConfigFileParsingDiagnostics(): readonly Diagnostic[]; - /** - * Get the syntax diagnostics, for all source files if source file is not supplied - */ - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; - /** - * Get the declaration diagnostics, for all source files if source file is not supplied - */ - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; - /** - * Get all the dependencies of the file - */ - getAllDependencies(sourceFile: SourceFile): readonly string[]; - /** - * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program - * The semantic diagnostics are cached and managed here - * Note that it is assumed that when asked about semantic diagnostics through this API, - * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics - * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, - * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics - */ - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; - /** - * Emits the JavaScript and declaration files. - * When targetSource file is specified, emits the files corresponding to that source file, - * otherwise for the whole program. - * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, - * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, - * it will only emit all the affected files instead of whole program - * - * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host - * in that order would be used to write the files - */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; - /** - * Get the current directory of the program - */ - getCurrentDirectory(): string; - } - /** - * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files - */ - interface SemanticDiagnosticsBuilderProgram extends BuilderProgram { - /** - * Gets the semantic diagnostics from the program for the next affected file and caches it - * Returns undefined if the iteration is complete - */ - getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult; - } - /** - * The builder that can handle the changes in program and iterate through changed file to emit the files - * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files - */ - interface EmitAndSemanticDiagnosticsBuilderProgram extends SemanticDiagnosticsBuilderProgram { - /** - * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete - * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host - * in that order would be used to write the files - */ - emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult; - } - function readBuilderProgram(compilerOptions: CompilerOptions, host: ReadBuildProgramHost): EmitAndSemanticDiagnosticsBuilderProgram | undefined; - function createIncrementalCompilerHost(options: CompilerOptions, system?: System): CompilerHost; - function createIncrementalProgram({ rootNames, options, configFileParsingDiagnostics, projectReferences, host, createProgram }: IncrementalProgramOptions): T; - /** - * Create the watch compiler host for either configFile or fileNames and its options - */ - function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): WatchCompilerHostOfConfigFile; - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: readonly ProjectReference[], watchOptions?: WatchOptions): WatchCompilerHostOfFilesAndCompilerOptions; - /** - * Creates the watch from the host for root files and compiler options - */ - function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions; - /** - * Creates the watch from the host for config file - */ - function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; - interface ReadBuildProgramHost { - useCaseSensitiveFileNames(): boolean; - getCurrentDirectory(): string; - readFile(fileName: string): string | undefined; - } - interface IncrementalProgramOptions { - rootNames: readonly string[]; - options: CompilerOptions; - configFileParsingDiagnostics?: readonly Diagnostic[]; - projectReferences?: readonly ProjectReference[]; - host?: CompilerHost; - createProgram?: CreateProgram; - } - type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions, errorCount?: number) => void; - /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[] | undefined) => T; - /** Host that has watch functionality used in --watch mode */ - interface WatchHost { - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions, errorCount?: number): void; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; - } - interface ProgramHost { - /** - * Used to create the program when need for program creation or recreation detected - */ - createProgram: CreateProgram; - useCaseSensitiveFileNames(): boolean; - getNewLine(): string; - getCurrentDirectory(): string; - getDefaultLibFileName(options: CompilerOptions): string; - getDefaultLibLocation?(): string; - createHash?(data: string): string; - /** - * Use to check file presence for source files and - * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well - */ - fileExists(path: string): boolean; - /** - * Use to read file text for source files and - * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well - */ - readFile(path: string, encoding?: string): string | undefined; - /** If provided, used for module resolution as well as to handle directory structure */ - directoryExists?(path: string): boolean; - /** If provided, used in resolutions as well as handling directory structure */ - getDirectories?(path: string): string[]; - /** If provided, used to cache and handle directory structure modifications */ - readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; - /** Symbol links resolution */ - realpath?(path: string): string; - /** If provided would be used to write log about compilation */ - trace?(s: string): void; - /** If provided is used to get the environment variable */ - getEnvironmentVariable?(name: string): string | undefined; - /** - * @deprecated supply resolveModuleNameLiterals instead for resolution that can handle newer resolution modes like nodenext - * - * If provided, used to resolve the module names, otherwise typescript's default module resolution - */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[]; - /** - * @deprecated supply resolveTypeReferenceDirectiveReferences instead for resolution that can handle newer resolution modes like nodenext - * - * If provided, used to resolve type reference directives, otherwise typescript's default resolution - */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: ResolutionMode): (ResolvedTypeReferenceDirective | undefined)[]; - resolveModuleNameLiterals?(moduleLiterals: readonly StringLiteralLike[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile, reusedNames: readonly StringLiteralLike[] | undefined): readonly ResolvedModuleWithFailedLookupLocations[]; - resolveTypeReferenceDirectiveReferences?(typeDirectiveReferences: readonly T[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile | undefined, reusedNames: readonly T[] | undefined): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[]; - /** If provided along with custom resolveModuleNames or resolveTypeReferenceDirectives, used to determine if unchanged file path needs to re-resolve modules/type reference directives */ - hasInvalidatedResolutions?(filePath: Path): boolean; - /** - * Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it - */ - getModuleResolutionCache?(): ModuleResolutionCache | undefined; - } - interface WatchCompilerHost extends ProgramHost, WatchHost { - /** Instead of using output d.ts file from project reference, use its source file */ - useSourceOfProjectReferenceRedirect?(): boolean; - /** If provided, use this method to get parsed command lines for referenced projects */ - getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; - /** If provided, callback to invoke after every new program creation */ - afterProgramCreate?(program: T): void; - } - /** - * Host to create watch with root files and options - */ - interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost { - /** root files to use to generate program */ - rootFiles: string[]; - /** Compiler options */ - options: CompilerOptions; - watchOptions?: WatchOptions; - /** Project References */ - projectReferences?: readonly ProjectReference[]; - } - /** - * Host to create watch with config file - */ - interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter { - /** Name of the config file to compile */ - configFileName: string; - /** Options to extend */ - optionsToExtend?: CompilerOptions; - watchOptionsToExtend?: WatchOptions; - extraFileExtensions?: readonly FileExtensionInfo[]; - /** - * Used to generate source file names from the config file and its include, exclude, files rules - * and also to cache the directory stucture - */ - readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; - } - interface Watch { - /** Synchronize with host and get updated program */ - getProgram(): T; - /** Closes the watch */ - close(): void; - } - /** - * Creates the watch what generates program using the config file - */ - interface WatchOfConfigFile extends Watch { - } - /** - * Creates the watch that generates program using the root files and compiler options - */ - interface WatchOfFilesAndCompilerOptions extends Watch { - /** Updates the root files in the program, only if this is not config file compilation */ - updateRootFileNames(fileNames: string[]): void; - } - /** - * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic - */ - function createBuilderStatusReporter(system: System, pretty?: boolean): DiagnosticReporter; - function createSolutionBuilderHost(system?: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary): SolutionBuilderHost; - function createSolutionBuilderWithWatchHost(system?: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): SolutionBuilderWithWatchHost; - function createSolutionBuilder(host: SolutionBuilderHost, rootNames: readonly string[], defaultOptions: BuildOptions): SolutionBuilder; - function createSolutionBuilderWithWatch(host: SolutionBuilderWithWatchHost, rootNames: readonly string[], defaultOptions: BuildOptions, baseWatchOptions?: WatchOptions): SolutionBuilder; - interface BuildOptions { - dry?: boolean; - force?: boolean; - verbose?: boolean; - incremental?: boolean; - assumeChangesOnlyAffectDirectDependencies?: boolean; - declaration?: boolean; - declarationMap?: boolean; - emitDeclarationOnly?: boolean; - sourceMap?: boolean; - inlineSourceMap?: boolean; - traceResolution?: boolean; - [option: string]: CompilerOptionsValue | undefined; - } - type ReportEmitErrorSummary = (errorCount: number, filesInError: (ReportFileInError | undefined)[]) => void; - interface ReportFileInError { - fileName: string; - line: number; - } - interface SolutionBuilderHostBase extends ProgramHost { - createDirectory?(path: string): void; - /** - * Should provide create directory and writeFile if done of invalidatedProjects is not invoked with - * writeFileCallback - */ - writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void; - getCustomTransformers?: (project: string) => CustomTransformers | undefined; - getModifiedTime(fileName: string): Date | undefined; - setModifiedTime(fileName: string, date: Date): void; - deleteFile(fileName: string): void; - getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; - reportDiagnostic: DiagnosticReporter; - reportSolutionBuilderStatus: DiagnosticReporter; - afterProgramEmitAndDiagnostics?(program: T): void; - } - interface SolutionBuilderHost extends SolutionBuilderHostBase { - reportErrorSummary?: ReportEmitErrorSummary; - } - interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { - } - interface SolutionBuilder { - build(project?: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; - clean(project?: string): ExitStatus; - buildReferences(project: string, cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, getCustomTransformers?: (project: string) => CustomTransformers): ExitStatus; - cleanReferences(project?: string): ExitStatus; - getNextInvalidatedProject(cancellationToken?: CancellationToken): InvalidatedProject | undefined; - } - enum InvalidatedProjectKind { - Build = 0, - /** @deprecated */ UpdateBundle = 1, - UpdateOutputFileStamps = 2 - } - interface InvalidatedProjectBase { - readonly kind: InvalidatedProjectKind; - readonly project: ResolvedConfigFileName; - /** - * To dispose this project and ensure that all the necessary actions are taken and state is updated accordingly - */ - done(cancellationToken?: CancellationToken, writeFile?: WriteFileCallback, customTransformers?: CustomTransformers): ExitStatus; - getCompilerOptions(): CompilerOptions; - getCurrentDirectory(): string; - } - interface UpdateOutputFileStampsProject extends InvalidatedProjectBase { - readonly kind: InvalidatedProjectKind.UpdateOutputFileStamps; - updateOutputFileStatmps(): void; - } - interface BuildInvalidedProject extends InvalidatedProjectBase { - readonly kind: InvalidatedProjectKind.Build; - getBuilderProgram(): T | undefined; - getProgram(): Program | undefined; - getSourceFile(fileName: string): SourceFile | undefined; - getSourceFiles(): readonly SourceFile[]; - getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; - getConfigFileParsingDiagnostics(): readonly Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; - getAllDependencies(sourceFile: SourceFile): readonly string[]; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; - getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult; - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult | undefined; - } - /** @deprecated */ - interface UpdateBundleProject extends InvalidatedProjectBase { - readonly kind: InvalidatedProjectKind.UpdateBundle; - emit(writeFile?: WriteFileCallback, customTransformers?: CustomTransformers): EmitResult | BuildInvalidedProject | undefined; - } - type InvalidatedProject = UpdateOutputFileStampsProject | BuildInvalidedProject | UpdateBundleProject; - namespace JsTyping { - interface TypingResolutionHost { - directoryExists(path: string): boolean; - fileExists(fileName: string): boolean; - readFile(path: string, encoding?: string): string | undefined; - readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; - } - } - function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; - /** - * Represents an immutable snapshot of a script at a specified time.Once acquired, the - * snapshot is observably immutable. i.e. the same calls with the same parameters will return - * the same values. - */ - interface IScriptSnapshot { - /** Gets a portion of the script snapshot specified by [start, end). */ - getText(start: number, end: number): string; - /** Gets the length of this script snapshot. */ - getLength(): number; - /** - * Gets the TextChangeRange that describe how the text changed between this text and - * an older version. This information is used by the incremental parser to determine - * what sections of the script need to be re-parsed. 'undefined' can be returned if the - * change range cannot be determined. However, in that case, incremental parsing will - * not happen and the entire document will be re - parsed. - */ - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined; - /** Releases all resources held by this script snapshot */ - dispose?(): void; - } - namespace ScriptSnapshot { - function fromString(text: string): IScriptSnapshot; - } - interface PreProcessedFileInfo { - referencedFiles: FileReference[]; - typeReferenceDirectives: FileReference[]; - libReferenceDirectives: FileReference[]; - importedFiles: FileReference[]; - ambientExternalModules?: string[]; - isLibFile: boolean; - } - interface HostCancellationToken { - isCancellationRequested(): boolean; - } - interface InstallPackageOptions { - fileName: Path; - packageName: string; - } - interface PerformanceEvent { - kind: "UpdateGraph" | "CreatePackageJsonAutoImportProvider"; - durationMs: number; - } - enum LanguageServiceMode { - Semantic = 0, - PartialSemantic = 1, - Syntactic = 2 - } - interface IncompleteCompletionsCache { - get(): CompletionInfo | undefined; - set(response: CompletionInfo): void; - clear(): void; - } - interface LanguageServiceHost extends GetEffectiveTypeRootsHost, MinimalResolutionCacheHost { - getCompilationSettings(): CompilerOptions; - getNewLine?(): string; - getProjectVersion?(): string; - getScriptFileNames(): string[]; - getScriptKind?(fileName: string): ScriptKind; - getScriptVersion(fileName: string): string; - getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; - getProjectReferences?(): readonly ProjectReference[] | undefined; - getLocalizedDiagnosticMessages?(): any; - getCancellationToken?(): HostCancellationToken; - getCurrentDirectory(): string; - getDefaultLibFileName(options: CompilerOptions): string; - log?(s: string): void; - trace?(s: string): void; - error?(s: string): void; - useCaseSensitiveFileNames?(): boolean; - readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; - realpath?(path: string): string; - readFile(path: string, encoding?: string): string | undefined; - fileExists(path: string): boolean; - getTypeRootsVersion?(): number; - /** @deprecated supply resolveModuleNameLiterals instead for resolution that can handle newer resolution modes like nodenext */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[]; - getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string, resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations | undefined; - /** @deprecated supply resolveTypeReferenceDirectiveReferences instead for resolution that can handle newer resolution modes like nodenext */ - resolveTypeReferenceDirectives?(typeDirectiveNames: string[] | FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: ResolutionMode): (ResolvedTypeReferenceDirective | undefined)[]; - resolveModuleNameLiterals?(moduleLiterals: readonly StringLiteralLike[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile, reusedNames: readonly StringLiteralLike[] | undefined): readonly ResolvedModuleWithFailedLookupLocations[]; - resolveTypeReferenceDirectiveReferences?(typeDirectiveReferences: readonly T[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile | undefined, reusedNames: readonly T[] | undefined): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[]; - getDirectories?(directoryName: string): string[]; - /** - * Gets a set of custom transformers to use during emit. - */ - getCustomTransformers?(): CustomTransformers | undefined; - isKnownTypesPackageName?(name: string): boolean; - installPackage?(options: InstallPackageOptions): Promise; - writeFile?(fileName: string, content: string): void; - getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined; - } - type WithMetadata = T & { - metadata?: unknown; - }; - enum SemanticClassificationFormat { - Original = "original", - TwentyTwenty = "2020" - } - interface LanguageService { - /** This is used as a part of restarting the language service. */ - cleanupSemanticCache(): void; - /** - * Gets errors indicating invalid syntax in a file. - * - * In English, "this cdeo have, erorrs" is syntactically invalid because it has typos, - * grammatical errors, and misplaced punctuation. Likewise, examples of syntax - * errors in TypeScript are missing parentheses in an `if` statement, mismatched - * curly braces, and using a reserved keyword as a variable name. - * - * These diagnostics are inexpensive to compute and don't require knowledge of - * other files. Note that a non-empty result increases the likelihood of false positives - * from `getSemanticDiagnostics`. - * - * While these represent the majority of syntax-related diagnostics, there are some - * that require the type system, which will be present in `getSemanticDiagnostics`. - * - * @param fileName A path to the file you want syntactic diagnostics for - */ - getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; - /** - * Gets warnings or errors indicating type system issues in a given file. - * Requesting semantic diagnostics may start up the type system and - * run deferred work, so the first call may take longer than subsequent calls. - * - * Unlike the other get*Diagnostics functions, these diagnostics can potentially not - * include a reference to a source file. Specifically, the first time this is called, - * it will return global diagnostics with no associated location. - * - * To contrast the differences between semantic and syntactic diagnostics, consider the - * sentence: "The sun is green." is syntactically correct; those are real English words with - * correct sentence structure. However, it is semantically invalid, because it is not true. - * - * @param fileName A path to the file you want semantic diagnostics for - */ - getSemanticDiagnostics(fileName: string): Diagnostic[]; - /** - * Gets suggestion diagnostics for a specific file. These diagnostics tend to - * proactively suggest refactors, as opposed to diagnostics that indicate - * potentially incorrect runtime behavior. - * - * @param fileName A path to the file you want semantic diagnostics for - */ - getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; - /** - * Gets global diagnostics related to the program configuration and compiler options. - */ - getCompilerOptionsDiagnostics(): Diagnostic[]; - /** @deprecated Use getEncodedSyntacticClassifications instead. */ - getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - getSyntacticClassifications(fileName: string, span: TextSpan, format: SemanticClassificationFormat): ClassifiedSpan[] | ClassifiedSpan2020[]; - /** @deprecated Use getEncodedSemanticClassifications instead. */ - getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - getSemanticClassifications(fileName: string, span: TextSpan, format: SemanticClassificationFormat): ClassifiedSpan[] | ClassifiedSpan2020[]; - /** Encoded as triples of [start, length, ClassificationType]. */ - getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; - /** - * Gets semantic highlights information for a particular file. Has two formats, an older - * version used by VS and a format used by VS Code. - * - * @param fileName The path to the file - * @param position A text span to return results within - * @param format Which format to use, defaults to "original" - * @returns a number array encoded as triples of [start, length, ClassificationType, ...]. - */ - getEncodedSemanticClassifications(fileName: string, span: TextSpan, format?: SemanticClassificationFormat): Classifications; - /** - * Gets completion entries at a particular position in a file. - * - * @param fileName The path to the file - * @param position A zero-based index of the character where you want the entries - * @param options An object describing how the request was triggered and what kinds - * of code actions can be returned with the completions. - * @param formattingSettings settings needed for calling formatting functions. - */ - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined, formattingSettings?: FormatCodeSettings): WithMetadata | undefined; - /** - * Gets the extended details for a completion entry retrieved from `getCompletionsAtPosition`. - * - * @param fileName The path to the file - * @param position A zero based index of the character where you want the entries - * @param entryName The `name` from an existing completion which came from `getCompletionsAtPosition` - * @param formatOptions How should code samples in the completions be formatted, can be undefined for backwards compatibility - * @param source `source` property from the completion entry - * @param preferences User settings, can be undefined for backwards compatibility - * @param data `data` property from the completion entry - */ - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): CompletionEntryDetails | undefined; - getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; - /** - * Gets semantic information about the identifier at a particular position in a - * file. Quick info is what you typically see when you hover in an editor. - * - * @param fileName The path to the file - * @param position A zero-based index of the character where you want the quick info - */ - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; - getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; - getRenameInfo(fileName: string, position: number, preferences: UserPreferences): RenameInfo; - /** @deprecated Use the signature with `UserPreferences` instead. */ - getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, preferences: UserPreferences): readonly RenameLocation[] | undefined; - /** @deprecated Pass `providePrefixAndSuffixTextForRename` as part of a `UserPreferences` parameter. */ - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): readonly RenameLocation[] | undefined; - getSmartSelectionRange(fileName: string, position: number): SelectionRange; - getDefinitionAtPosition(fileName: string, position: number): readonly DefinitionInfo[] | undefined; - getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): readonly DefinitionInfo[] | undefined; - getImplementationAtPosition(fileName: string, position: number): readonly ImplementationLocation[] | undefined; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; - findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; - getFileReferences(fileName: string): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; - getNavigationBarItems(fileName: string): NavigationBarItem[]; - getNavigationTree(fileName: string): NavigationTree; - prepareCallHierarchy(fileName: string, position: number): CallHierarchyItem | CallHierarchyItem[] | undefined; - provideCallHierarchyIncomingCalls(fileName: string, position: number): CallHierarchyIncomingCall[]; - provideCallHierarchyOutgoingCalls(fileName: string, position: number): CallHierarchyOutgoingCall[]; - provideInlayHints(fileName: string, span: TextSpan, preferences: UserPreferences | undefined): InlayHint[]; - getOutliningSpans(fileName: string): OutliningSpan[]; - getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; - getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions, formatOptions?: FormatCodeSettings): TextInsertion | undefined; - isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - /** - * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. - * Editors should call this after `>` is typed. - */ - getJsxClosingTagAtPosition(fileName: string, position: number): JsxClosingTagInfo | undefined; - getLinkedEditingRangeAtPosition(fileName: string, position: number): LinkedEditingInfo | undefined; - getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined; - toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: readonly number[], formatOptions: FormatCodeSettings, preferences: UserPreferences): readonly CodeFixAction[]; - getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; - applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; - /** @deprecated `fileName` will be ignored */ - applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; - /** @deprecated `fileName` will be ignored */ - applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; - /** @deprecated `fileName` will be ignored */ - applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; - /** - * @param includeInteractiveActions Include refactor actions that require additional arguments to be - * passed when calling `getEditsForRefactor`. When true, clients should inspect the `isInteractive` - * property of each returned `RefactorActionInfo` and ensure they are able to collect the appropriate - * arguments for any interactive action before offering it. - */ - getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string, includeInteractiveActions?: boolean): ApplicableRefactorInfo[]; - getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined, interactiveRefactorArguments?: InteractiveRefactorArguments): RefactorEditInfo | undefined; - getMoveToRefactoringFileSuggestions(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): { - newFileName: string; - files: string[]; - }; - organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; - getProgram(): Program | undefined; - toggleLineComment(fileName: string, textRange: TextRange): TextChange[]; - toggleMultilineComment(fileName: string, textRange: TextRange): TextChange[]; - commentSelection(fileName: string, textRange: TextRange): TextChange[]; - uncommentSelection(fileName: string, textRange: TextRange): TextChange[]; - getSupportedCodeFixes(fileName?: string): readonly string[]; - dispose(): void; - } - interface JsxClosingTagInfo { - readonly newText: string; - } - interface LinkedEditingInfo { - readonly ranges: TextSpan[]; - wordPattern?: string; - } - interface CombinedCodeFixScope { - type: "file"; - fileName: string; - } - enum OrganizeImportsMode { - All = "All", - SortAndCombine = "SortAndCombine", - RemoveUnused = "RemoveUnused" - } - interface OrganizeImportsArgs extends CombinedCodeFixScope { - /** @deprecated Use `mode` instead */ - skipDestructiveCodeActions?: boolean; - mode?: OrganizeImportsMode; - } - type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; - enum CompletionTriggerKind { - /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ - Invoked = 1, - /** Completion was triggered by a trigger character. */ - TriggerCharacter = 2, - /** Completion was re-triggered as the current completion list is incomplete. */ - TriggerForIncompleteCompletions = 3 - } - interface GetCompletionsAtPositionOptions extends UserPreferences { - /** - * If the editor is asking for completions because a certain character was typed - * (as opposed to when the user explicitly requested them) this should be set. - */ - triggerCharacter?: CompletionsTriggerCharacter; - triggerKind?: CompletionTriggerKind; - /** - * Include a `symbol` property on each completion entry object. - * Symbols reference cyclic data structures and sometimes an entire TypeChecker instance, - * so use caution when serializing or retaining completion entries retrieved with this option. - * @default false - */ - includeSymbol?: boolean; - /** @deprecated Use includeCompletionsForModuleExports */ - includeExternalModuleExports?: boolean; - /** @deprecated Use includeCompletionsWithInsertText */ - includeInsertTextCompletions?: boolean; - } - type SignatureHelpTriggerCharacter = "," | "(" | "<"; - type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; - interface SignatureHelpItemsOptions { - triggerReason?: SignatureHelpTriggerReason; - } - type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; - /** - * Signals that the user manually requested signature help. - * The language service will unconditionally attempt to provide a result. - */ - interface SignatureHelpInvokedReason { - kind: "invoked"; - triggerCharacter?: undefined; - } - /** - * Signals that the signature help request came from a user typing a character. - * Depending on the character and the syntactic context, the request may or may not be served a result. - */ - interface SignatureHelpCharacterTypedReason { - kind: "characterTyped"; - /** - * Character that was responsible for triggering signature help. - */ - triggerCharacter: SignatureHelpTriggerCharacter; - } - /** - * Signals that this signature help request came from typing a character or moving the cursor. - * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. - * The language service will unconditionally attempt to provide a result. - * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. - */ - interface SignatureHelpRetriggeredReason { - kind: "retrigger"; - /** - * Character that was responsible for triggering signature help. - */ - triggerCharacter?: SignatureHelpRetriggerCharacter; - } - interface ApplyCodeActionCommandResult { - successMessage: string; - } - interface Classifications { - spans: number[]; - endOfLineState: EndOfLineState; - } - interface ClassifiedSpan { - textSpan: TextSpan; - classificationType: ClassificationTypeNames; - } - interface ClassifiedSpan2020 { - textSpan: TextSpan; - classificationType: number; - } - /** - * Navigation bar interface designed for visual studio's dual-column layout. - * This does not form a proper tree. - * The navbar is returned as a list of top-level items, each of which has a list of child items. - * Child items always have an empty array for their `childItems`. - */ - interface NavigationBarItem { - text: string; - kind: ScriptElementKind; - kindModifiers: string; - spans: TextSpan[]; - childItems: NavigationBarItem[]; - indent: number; - bolded: boolean; - grayed: boolean; - } - /** - * Node in a tree of nested declarations in a file. - * The top node is always a script or module node. - */ - interface NavigationTree { - /** Name of the declaration, or a short description, e.g. "". */ - text: string; - kind: ScriptElementKind; - /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ - kindModifiers: string; - /** - * Spans of the nodes that generated this declaration. - * There will be more than one if this is the result of merging. - */ - spans: TextSpan[]; - nameSpan: TextSpan | undefined; - /** Present if non-empty */ - childItems?: NavigationTree[]; - } - interface CallHierarchyItem { - name: string; - kind: ScriptElementKind; - kindModifiers?: string; - file: string; - span: TextSpan; - selectionSpan: TextSpan; - containerName?: string; - } - interface CallHierarchyIncomingCall { - from: CallHierarchyItem; - fromSpans: TextSpan[]; - } - interface CallHierarchyOutgoingCall { - to: CallHierarchyItem; - fromSpans: TextSpan[]; - } - enum InlayHintKind { - Type = "Type", - Parameter = "Parameter", - Enum = "Enum" - } - interface InlayHint { - /** This property will be the empty string when displayParts is set. */ - text: string; - position: number; - kind: InlayHintKind; - whitespaceBefore?: boolean; - whitespaceAfter?: boolean; - displayParts?: InlayHintDisplayPart[]; - } - interface InlayHintDisplayPart { - text: string; - span?: TextSpan; - file?: string; - } - interface TodoCommentDescriptor { - text: string; - priority: number; - } - interface TodoComment { - descriptor: TodoCommentDescriptor; - message: string; - position: number; - } - interface TextChange { - span: TextSpan; - newText: string; - } - interface FileTextChanges { - fileName: string; - textChanges: readonly TextChange[]; - isNewFile?: boolean; - } - interface CodeAction { - /** Description of the code action to display in the UI of the editor */ - description: string; - /** Text changes to apply to each file as part of the code action */ - changes: FileTextChanges[]; - /** - * If the user accepts the code fix, the editor should send the action back in a `applyAction` request. - * This allows the language service to have side effects (e.g. installing dependencies) upon a code fix. - */ - commands?: CodeActionCommand[]; - } - interface CodeFixAction extends CodeAction { - /** Short name to identify the fix, for use by telemetry. */ - fixName: string; - /** - * If present, one may call 'getCombinedCodeFix' with this fixId. - * This may be omitted to indicate that the code fix can't be applied in a group. - */ - fixId?: {}; - fixAllDescription?: string; - } - interface CombinedCodeActions { - changes: readonly FileTextChanges[]; - commands?: readonly CodeActionCommand[]; - } - type CodeActionCommand = InstallPackageAction; - interface InstallPackageAction { - } - /** - * A set of one or more available refactoring actions, grouped under a parent refactoring. - */ - interface ApplicableRefactorInfo { - /** - * The programmatic name of the refactoring - */ - name: string; - /** - * A description of this refactoring category to show to the user. - * If the refactoring gets inlined (see below), this text will not be visible. - */ - description: string; - /** - * Inlineable refactorings can have their actions hoisted out to the top level - * of a context menu. Non-inlineanable refactorings should always be shown inside - * their parent grouping. - * - * If not specified, this value is assumed to be 'true' - */ - inlineable?: boolean; - actions: RefactorActionInfo[]; - } - /** - * Represents a single refactoring action - for example, the "Extract Method..." refactor might - * offer several actions, each corresponding to a surround class or closure to extract into. - */ - interface RefactorActionInfo { - /** - * The programmatic name of the refactoring action - */ - name: string; - /** - * A description of this refactoring action to show to the user. - * If the parent refactoring is inlined away, this will be the only text shown, - * so this description should make sense by itself if the parent is inlineable=true - */ - description: string; - /** - * A message to show to the user if the refactoring cannot be applied in - * the current context. - */ - notApplicableReason?: string; - /** - * The hierarchical dotted name of the refactor action. - */ - kind?: string; - /** - * Indicates that the action requires additional arguments to be passed - * when calling `getEditsForRefactor`. - */ - isInteractive?: boolean; - } - /** - * A set of edits to make in response to a refactor action, plus an optional - * location where renaming should be invoked from - */ - interface RefactorEditInfo { - edits: FileTextChanges[]; - renameFilename?: string; - renameLocation?: number; - commands?: CodeActionCommand[]; - notApplicableReason?: string; - } - type RefactorTriggerReason = "implicit" | "invoked"; - interface TextInsertion { - newText: string; - /** The position in newText the caret should point to after the insertion. */ - caretOffset: number; - } - interface DocumentSpan { - textSpan: TextSpan; - fileName: string; - /** - * If the span represents a location that was remapped (e.g. via a .d.ts.map file), - * then the original filename and span will be specified here - */ - originalTextSpan?: TextSpan; - originalFileName?: string; - /** - * If DocumentSpan.textSpan is the span for name of the declaration, - * then this is the span for relevant declaration - */ - contextSpan?: TextSpan; - originalContextSpan?: TextSpan; - } - interface RenameLocation extends DocumentSpan { - readonly prefixText?: string; - readonly suffixText?: string; - } - interface ReferenceEntry extends DocumentSpan { - isWriteAccess: boolean; - isInString?: true; - } - interface ImplementationLocation extends DocumentSpan { - kind: ScriptElementKind; - displayParts: SymbolDisplayPart[]; - } - enum HighlightSpanKind { - none = "none", - definition = "definition", - reference = "reference", - writtenReference = "writtenReference" - } - interface HighlightSpan { - fileName?: string; - isInString?: true; - textSpan: TextSpan; - contextSpan?: TextSpan; - kind: HighlightSpanKind; - } - interface NavigateToItem { - name: string; - kind: ScriptElementKind; - kindModifiers: string; - matchKind: "exact" | "prefix" | "substring" | "camelCase"; - isCaseSensitive: boolean; - fileName: string; - textSpan: TextSpan; - containerName: string; - containerKind: ScriptElementKind; - } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2 - } - enum SemicolonPreference { - Ignore = "ignore", - Insert = "insert", - Remove = "remove" - } - /** @deprecated - consider using EditorSettings instead */ - interface EditorOptions { - BaseIndentSize?: number; - IndentSize: number; - TabSize: number; - NewLineCharacter: string; - ConvertTabsToSpaces: boolean; - IndentStyle: IndentStyle; - } - interface EditorSettings { - baseIndentSize?: number; - indentSize?: number; - tabSize?: number; - newLineCharacter?: string; - convertTabsToSpaces?: boolean; - indentStyle?: IndentStyle; - trimTrailingWhitespace?: boolean; - } - /** @deprecated - consider using FormatCodeSettings instead */ - interface FormatCodeOptions extends EditorOptions { - InsertSpaceAfterCommaDelimiter: boolean; - InsertSpaceAfterSemicolonInForStatements: boolean; - InsertSpaceBeforeAndAfterBinaryOperators: boolean; - InsertSpaceAfterConstructor?: boolean; - InsertSpaceAfterKeywordsInControlFlowStatements: boolean; - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; - InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - InsertSpaceAfterTypeAssertion?: boolean; - InsertSpaceBeforeFunctionParenthesis?: boolean; - PlaceOpenBraceOnNewLineForFunctions: boolean; - PlaceOpenBraceOnNewLineForControlBlocks: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - } - interface FormatCodeSettings extends EditorSettings { - readonly insertSpaceAfterCommaDelimiter?: boolean; - readonly insertSpaceAfterSemicolonInForStatements?: boolean; - readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; - readonly insertSpaceAfterConstructor?: boolean; - readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - readonly insertSpaceAfterOpeningAndBeforeClosingEmptyBraces?: boolean; - readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - readonly insertSpaceAfterTypeAssertion?: boolean; - readonly insertSpaceBeforeFunctionParenthesis?: boolean; - readonly placeOpenBraceOnNewLineForFunctions?: boolean; - readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; - readonly insertSpaceBeforeTypeAnnotation?: boolean; - readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; - readonly semicolons?: SemicolonPreference; - readonly indentSwitchCase?: boolean; - } - interface DefinitionInfo extends DocumentSpan { - kind: ScriptElementKind; - name: string; - containerKind: ScriptElementKind; - containerName: string; - unverified?: boolean; - } - interface DefinitionInfoAndBoundSpan { - definitions?: readonly DefinitionInfo[]; - textSpan: TextSpan; - } - interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { - displayParts: SymbolDisplayPart[]; - } - interface ReferencedSymbol { - definition: ReferencedSymbolDefinitionInfo; - references: ReferencedSymbolEntry[]; - } - interface ReferencedSymbolEntry extends ReferenceEntry { - isDefinition?: boolean; - } - enum SymbolDisplayPartKind { - aliasName = 0, - className = 1, - enumName = 2, - fieldName = 3, - interfaceName = 4, - keyword = 5, - lineBreak = 6, - numericLiteral = 7, - stringLiteral = 8, - localName = 9, - methodName = 10, - moduleName = 11, - operator = 12, - parameterName = 13, - propertyName = 14, - punctuation = 15, - space = 16, - text = 17, - typeParameterName = 18, - enumMemberName = 19, - functionName = 20, - regularExpressionLiteral = 21, - link = 22, - linkName = 23, - linkText = 24 - } - interface SymbolDisplayPart { - text: string; - kind: string; - } - interface JSDocLinkDisplayPart extends SymbolDisplayPart { - target: DocumentSpan; - } - interface JSDocTagInfo { - name: string; - text?: SymbolDisplayPart[]; - } - interface QuickInfo { - kind: ScriptElementKind; - kindModifiers: string; - textSpan: TextSpan; - displayParts?: SymbolDisplayPart[]; - documentation?: SymbolDisplayPart[]; - tags?: JSDocTagInfo[]; - } - type RenameInfo = RenameInfoSuccess | RenameInfoFailure; - interface RenameInfoSuccess { - canRename: true; - /** - * File or directory to rename. - * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. - */ - fileToRename?: string; - displayName: string; - fullDisplayName: string; - kind: ScriptElementKind; - kindModifiers: string; - triggerSpan: TextSpan; - } - interface RenameInfoFailure { - canRename: false; - localizedErrorMessage: string; - } - /** - * @deprecated Use `UserPreferences` instead. - */ - interface RenameInfoOptions { - readonly allowRenameOfImportPath?: boolean; - } - interface DocCommentTemplateOptions { - readonly generateReturnInDocTemplate?: boolean; - } - interface InteractiveRefactorArguments { - targetFile: string; - } - interface SignatureHelpParameter { - name: string; - documentation: SymbolDisplayPart[]; - displayParts: SymbolDisplayPart[]; - isOptional: boolean; - isRest?: boolean; - } - interface SelectionRange { - textSpan: TextSpan; - parent?: SelectionRange; - } - /** - * Represents a single signature to show in signature help. - * The id is used for subsequent calls into the language service to ask questions about the - * signature help item in the context of any documents that have been updated. i.e. after - * an edit has happened, while signature help is still active, the host can ask important - * questions like 'what parameter is the user currently contained within?'. - */ - interface SignatureHelpItem { - isVariadic: boolean; - prefixDisplayParts: SymbolDisplayPart[]; - suffixDisplayParts: SymbolDisplayPart[]; - separatorDisplayParts: SymbolDisplayPart[]; - parameters: SignatureHelpParameter[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; - } - /** - * Represents a set of signature help items, and the preferred item that should be selected. - */ - interface SignatureHelpItems { - items: SignatureHelpItem[]; - applicableSpan: TextSpan; - selectedItemIndex: number; - argumentIndex: number; - argumentCount: number; - } - enum CompletionInfoFlags { - None = 0, - MayIncludeAutoImports = 1, - IsImportStatementCompletion = 2, - IsContinuation = 4, - ResolvedModuleSpecifiers = 8, - ResolvedModuleSpecifiersBeyondLimit = 16, - MayIncludeMethodSnippets = 32 - } - interface CompletionInfo { - /** For performance telemetry. */ - flags?: CompletionInfoFlags; - /** Not true for all global completions. This will be true if the enclosing scope matches a few syntax kinds. See `isSnippetScope`. */ - isGlobalCompletion: boolean; - isMemberCompletion: boolean; - /** - * In the absence of `CompletionEntry["replacementSpan"]`, the editor may choose whether to use - * this span or its default one. If `CompletionEntry["replacementSpan"]` is defined, that span - * must be used to commit that completion entry. - */ - optionalReplacementSpan?: TextSpan; - /** - * true when the current location also allows for a new identifier - */ - isNewIdentifierLocation: boolean; - /** - * Indicates to client to continue requesting completions on subsequent keystrokes. - */ - isIncomplete?: true; - entries: CompletionEntry[]; - } - interface CompletionEntryDataAutoImport { - /** - * The name of the property or export in the module's symbol table. Differs from the completion name - * in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default. - */ - exportName: string; - exportMapKey?: string; - moduleSpecifier?: string; - /** The file name declaring the export's module symbol, if it was an external module */ - fileName?: string; - /** The module name (with quotes stripped) of the export's module symbol, if it was an ambient module */ - ambientModuleName?: string; - /** True if the export was found in the package.json AutoImportProvider */ - isPackageJsonImport?: true; - } - interface CompletionEntryDataUnresolved extends CompletionEntryDataAutoImport { - exportMapKey: string; - } - interface CompletionEntryDataResolved extends CompletionEntryDataAutoImport { - moduleSpecifier: string; - } - type CompletionEntryData = CompletionEntryDataUnresolved | CompletionEntryDataResolved; - interface CompletionEntry { - name: string; - kind: ScriptElementKind; - kindModifiers?: string; - sortText: string; - insertText?: string; - filterText?: string; - isSnippet?: true; - /** - * An optional span that indicates the text to be replaced by this completion item. - * If present, this span should be used instead of the default one. - * It will be set if the required span differs from the one generated by the default replacement behavior. - */ - replacementSpan?: TextSpan; - hasAction?: true; - source?: string; - sourceDisplay?: SymbolDisplayPart[]; - labelDetails?: CompletionEntryLabelDetails; - isRecommended?: true; - isFromUncheckedFile?: true; - isPackageJsonImport?: true; - isImportStatementCompletion?: true; - /** - * For API purposes. - * Included for non-string completions only when `includeSymbol: true` option is passed to `getCompletionsAtPosition`. - * @example Get declaration of completion: `symbol.valueDeclaration` - */ - symbol?: Symbol; - /** - * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, - * that allows TS Server to look up the symbol represented by the completion item, disambiguating - * items with the same name. Currently only defined for auto-import completions, but the type is - * `unknown` in the protocol, so it can be changed as needed to support other kinds of completions. - * The presence of this property should generally not be used to assume that this completion entry - * is an auto-import. - */ - data?: CompletionEntryData; - } - interface CompletionEntryLabelDetails { - detail?: string; - description?: string; - } - interface CompletionEntryDetails { - name: string; - kind: ScriptElementKind; - kindModifiers: string; - displayParts: SymbolDisplayPart[]; - documentation?: SymbolDisplayPart[]; - tags?: JSDocTagInfo[]; - codeActions?: CodeAction[]; - /** @deprecated Use `sourceDisplay` instead. */ - source?: SymbolDisplayPart[]; - sourceDisplay?: SymbolDisplayPart[]; - } - interface OutliningSpan { - /** The span of the document to actually collapse. */ - textSpan: TextSpan; - /** The span of the document to display when the user hovers over the collapsed span. */ - hintSpan: TextSpan; - /** The text to display in the editor for the collapsed region. */ - bannerText: string; - /** - * Whether or not this region should be automatically collapsed when - * the 'Collapse to Definitions' command is invoked. - */ - autoCollapse: boolean; - /** - * Classification of the contents of the span - */ - kind: OutliningSpanKind; - } - enum OutliningSpanKind { - /** Single or multi-line comments */ - Comment = "comment", - /** Sections marked by '// #region' and '// #endregion' comments */ - Region = "region", - /** Declarations and expressions */ - Code = "code", - /** Contiguous blocks of import declarations */ - Imports = "imports" - } - enum OutputFileType { - JavaScript = 0, - SourceMap = 1, - Declaration = 2 - } - enum EndOfLineState { - None = 0, - InMultiLineCommentTrivia = 1, - InSingleQuoteStringLiteral = 2, - InDoubleQuoteStringLiteral = 3, - InTemplateHeadOrNoSubstitutionTemplate = 4, - InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6 - } - enum TokenClass { - Punctuation = 0, - Keyword = 1, - Operator = 2, - Comment = 3, - Whitespace = 4, - Identifier = 5, - NumberLiteral = 6, - BigIntLiteral = 7, - StringLiteral = 8, - RegExpLiteral = 9 - } - interface ClassificationResult { - finalLexState: EndOfLineState; - entries: ClassificationInfo[]; - } - interface ClassificationInfo { - length: number; - classification: TokenClass; - } - interface Classifier { - /** - * Gives lexical classifications of tokens on a line without any syntactic context. - * For instance, a token consisting of the text 'string' can be either an identifier - * named 'string' or the keyword 'string', however, because this classifier is not aware, - * it relies on certain heuristics to give acceptable results. For classifications where - * speed trumps accuracy, this function is preferable; however, for true accuracy, the - * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the - * lexical, syntactic, and semantic classifiers may issue the best user experience. - * - * @param text The text of a line to classify. - * @param lexState The state of the lexical classifier at the end of the previous line. - * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. - * If there is no syntactic classifier (syntacticClassifierAbsent=true), - * certain heuristics may be used in its place; however, if there is a - * syntactic classifier (syntacticClassifierAbsent=false), certain - * classifications which may be incorrectly categorized will be given - * back as Identifiers in order to allow the syntactic classifier to - * subsume the classification. - * @deprecated Use getLexicalClassifications instead. - */ - getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; - getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; - } - enum ScriptElementKind { - unknown = "", - warning = "warning", - /** predefined type (void) or keyword (class) */ - keyword = "keyword", - /** top level script node */ - scriptElement = "script", - /** module foo {} */ - moduleElement = "module", - /** class X {} */ - classElement = "class", - /** var x = class X {} */ - localClassElement = "local class", - /** interface Y {} */ - interfaceElement = "interface", - /** type T = ... */ - typeElement = "type", - /** enum E */ - enumElement = "enum", - enumMemberElement = "enum member", - /** - * Inside module and script only - * const v = .. - */ - variableElement = "var", - /** Inside function */ - localVariableElement = "local var", - /** using foo = ... */ - variableUsingElement = "using", - /** await using foo = ... */ - variableAwaitUsingElement = "await using", - /** - * Inside module and script only - * function f() { } - */ - functionElement = "function", - /** Inside function */ - localFunctionElement = "local function", - /** class X { [public|private]* foo() {} } */ - memberFunctionElement = "method", - /** class X { [public|private]* [get|set] foo:number; } */ - memberGetAccessorElement = "getter", - memberSetAccessorElement = "setter", - /** - * class X { [public|private]* foo:number; } - * interface Y { foo:number; } - */ - memberVariableElement = "property", - /** class X { [public|private]* accessor foo: number; } */ - memberAccessorVariableElement = "accessor", - /** - * class X { constructor() { } } - * class X { static { } } - */ - constructorImplementationElement = "constructor", - /** interface Y { ():number; } */ - callSignatureElement = "call", - /** interface Y { []:number; } */ - indexSignatureElement = "index", - /** interface Y { new():Y; } */ - constructSignatureElement = "construct", - /** function foo(*Y*: string) */ - parameterElement = "parameter", - typeParameterElement = "type parameter", - primitiveType = "primitive type", - label = "label", - alias = "alias", - constElement = "const", - letElement = "let", - directory = "directory", - externalModuleName = "external module name", - /** - * - * @deprecated - */ - jsxAttribute = "JSX attribute", - /** String literal */ - string = "string", - /** Jsdoc @link: in `{@link C link text}`, the before and after text "{@link " and "}" */ - link = "link", - /** Jsdoc @link: in `{@link C link text}`, the entity name "C" */ - linkName = "link name", - /** Jsdoc @link: in `{@link C link text}`, the link text "link text" */ - linkText = "link text" - } - enum ScriptElementKindModifier { - none = "", - publicMemberModifier = "public", - privateMemberModifier = "private", - protectedMemberModifier = "protected", - exportedModifier = "export", - ambientModifier = "declare", - staticModifier = "static", - abstractModifier = "abstract", - optionalModifier = "optional", - deprecatedModifier = "deprecated", - dtsModifier = ".d.ts", - tsModifier = ".ts", - tsxModifier = ".tsx", - jsModifier = ".js", - jsxModifier = ".jsx", - jsonModifier = ".json", - dmtsModifier = ".d.mts", - mtsModifier = ".mts", - mjsModifier = ".mjs", - dctsModifier = ".d.cts", - ctsModifier = ".cts", - cjsModifier = ".cjs" - } - enum ClassificationTypeNames { - comment = "comment", - identifier = "identifier", - keyword = "keyword", - numericLiteral = "number", - bigintLiteral = "bigint", - operator = "operator", - stringLiteral = "string", - whiteSpace = "whitespace", - text = "text", - punctuation = "punctuation", - className = "class name", - enumName = "enum name", - interfaceName = "interface name", - moduleName = "module name", - typeParameterName = "type parameter name", - typeAliasName = "type alias name", - parameterName = "parameter name", - docCommentTagName = "doc comment tag name", - jsxOpenTagName = "jsx open tag name", - jsxCloseTagName = "jsx close tag name", - jsxSelfClosingTagName = "jsx self closing tag name", - jsxAttribute = "jsx attribute", - jsxText = "jsx text", - jsxAttributeStringLiteralValue = "jsx attribute string literal value" - } - enum ClassificationType { - comment = 1, - identifier = 2, - keyword = 3, - numericLiteral = 4, - operator = 5, - stringLiteral = 6, - regularExpressionLiteral = 7, - whiteSpace = 8, - text = 9, - punctuation = 10, - className = 11, - enumName = 12, - interfaceName = 13, - moduleName = 14, - typeParameterName = 15, - typeAliasName = 16, - parameterName = 17, - docCommentTagName = 18, - jsxOpenTagName = 19, - jsxCloseTagName = 20, - jsxSelfClosingTagName = 21, - jsxAttribute = 22, - jsxText = 23, - jsxAttributeStringLiteralValue = 24, - bigintLiteral = 25 - } - interface InlayHintsContext { - file: SourceFile; - program: Program; - cancellationToken: CancellationToken; - host: LanguageServiceHost; - span: TextSpan; - preferences: UserPreferences; - } - /** The classifier is used for syntactic highlighting in editors via the TSServer */ - function createClassifier(): Classifier; - interface DocumentHighlights { - fileName: string; - highlightSpans: HighlightSpan[]; - } - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; - /** - * The document registry represents a store of SourceFile objects that can be shared between - * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) - * of files in the context. - * SourceFile objects account for most of the memory usage by the language service. Sharing - * the same DocumentRegistry instance between different instances of LanguageService allow - * for more efficient memory utilization since all projects will share at least the library - * file (lib.d.ts). - * - * A more advanced use of the document registry is to serialize sourceFile objects to disk - * and re-hydrate them when needed. - * - * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it - * to all subsequent createLanguageService calls. - */ - interface DocumentRegistry { - /** - * Request a stored SourceFile with a given fileName and compilationSettings. - * The first call to acquire will call createLanguageServiceSourceFile to generate - * the SourceFile if was not found in the registry. - * - * @param fileName The name of the file requested - * @param compilationSettingsOrHost Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. A minimal - * resolution cache is needed to fully define a source file's shape when - * the compilation settings include `module: node16`+, so providing a cache host - * object should be preferred. A common host is a language service `ConfiguredProject`. - * @param scriptSnapshot Text of the file. Only used if the file was not found - * in the registry and a new one was created. - * @param version Current version of the file. Only used if the file was not found - * in the registry and a new one was created. - */ - acquireDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; - acquireDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; - /** - * Request an updated version of an already existing SourceFile with a given fileName - * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile - * to get an updated SourceFile. - * - * @param fileName The name of the file requested - * @param compilationSettingsOrHost Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. A minimal - * resolution cache is needed to fully define a source file's shape when - * the compilation settings include `module: node16`+, so providing a cache host - * object should be preferred. A common host is a language service `ConfiguredProject`. - * @param scriptSnapshot Text of the file. - * @param version Current version of the file. - */ - updateDocument(fileName: string, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; - updateDocumentWithKey(fileName: string, path: Path, compilationSettingsOrHost: CompilerOptions | MinimalResolutionCacheHost, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind, sourceFileOptions?: CreateSourceFileOptions | ScriptTarget): SourceFile; - getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey; - /** - * Informs the DocumentRegistry that a file is not needed any longer. - * - * Note: It is not allowed to call release on a SourceFile that was not acquired from - * this registry originally. - * - * @param fileName The name of the file to be released - * @param compilationSettings The compilation settings used to acquire the file - * @param scriptKind The script kind of the file to be released - * - * @deprecated pass scriptKind and impliedNodeFormat for correctness - */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind?: ScriptKind): void; - /** - * Informs the DocumentRegistry that a file is not needed any longer. - * - * Note: It is not allowed to call release on a SourceFile that was not acquired from - * this registry originally. - * - * @param fileName The name of the file to be released - * @param compilationSettings The compilation settings used to acquire the file - * @param scriptKind The script kind of the file to be released - * @param impliedNodeFormat The implied source file format of the file to be released - */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions, scriptKind: ScriptKind, impliedNodeFormat: ResolutionMode): void; - /** - * @deprecated pass scriptKind for and impliedNodeFormat correctness */ - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind?: ScriptKind): void; - releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey, scriptKind: ScriptKind, impliedNodeFormat: ResolutionMode): void; - reportStats(): string; - } - type DocumentRegistryBucketKey = string & { - __bucketKey: any; - }; - function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; - function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; - interface TranspileOptions { - compilerOptions?: CompilerOptions; - fileName?: string; - reportDiagnostics?: boolean; - moduleName?: string; - renamedDependencies?: MapLike; - transformers?: CustomTransformers; - } - interface TranspileOutput { - outputText: string; - diagnostics?: Diagnostic[]; - sourceMapText?: string; - } - function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; - function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; - function getDefaultCompilerOptions(): CompilerOptions; - function getSupportedCodeFixes(): readonly string[]; - function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTargetOrOptions: ScriptTarget | CreateSourceFileOptions, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; - function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnlyOrLanguageServiceMode?: boolean | LanguageServiceMode): LanguageService; - /** - * Get the path of the default library files (lib.d.ts) as distributed with the typescript - * node package. - * The functionality is not supported if the ts module is consumed outside of a node module. - */ - function getDefaultLibFilePath(options: CompilerOptions): string; - /** The version of the language service API */ - const servicesVersion = "0.8"; - /** - * Transform one or more nodes using the supplied transformers. - * @param source A single `Node` or an array of `Node` objects. - * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. - * @param compilerOptions Optional compiler options. - */ - function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions): TransformationResult; -} -export = ts; \ No newline at end of file +import ts = require("./typescript.js"); +export = ts; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 3be5dc3c25764..0421149e4cff8 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -14,6 +14,4066 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { + namespace server { + type ActionSet = "action::set"; + type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type EventTypesRegistry = "event::typesRegistry"; + type EventBeginInstallTypes = "event::beginInstallTypes"; + type EventEndInstallTypes = "event::endInstallTypes"; + type EventInitializationFailed = "event::initializationFailed"; + type ActionWatchTypingLocations = "action::watchTypingLocations"; + interface TypingInstallerResponse { + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed | ActionWatchTypingLocations; + } + interface TypingInstallerRequestWithProjectName { + readonly projectName: string; + } + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { + readonly fileNames: string[]; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; + readonly cachePath?: string; + readonly kind: "discover"; + } + interface CloseProject extends TypingInstallerRequestWithProjectName { + readonly kind: "closeProject"; + } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; + } + interface InitializationFailedResponse extends TypingInstallerResponse { + readonly kind: EventInitializationFailed; + readonly message: string; + readonly stack?: string; + } + interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: readonly string[]; + } + interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; + } + interface InstallTypingHost extends JsTyping.TypingResolutionHost { + useCaseSensitiveFileNames: boolean; + writeFile(path: string, content: string): void; + createDirectory(path: string): void; + getCurrentDirectory?(): string; + } + interface SetTypings extends ProjectResponse { + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; + readonly typings: string[]; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; + } + interface WatchTypingLocations extends ProjectResponse { + /** if files is undefined, retain same set of watchers */ + readonly files: readonly string[] | undefined; + readonly kind: ActionWatchTypingLocations; + } + namespace protocol { + enum CommandTypes { + JsxClosingTag = "jsxClosingTag", + LinkedEditingRange = "linkedEditingRange", + Brace = "brace", + BraceCompletion = "braceCompletion", + GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", + Change = "change", + Close = "close", + /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ + Completions = "completions", + CompletionInfo = "completionInfo", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", + DefinitionAndBoundSpan = "definitionAndBoundSpan", + Implementation = "implementation", + Exit = "exit", + FileReferences = "fileReferences", + Format = "format", + Formatonkey = "formatonkey", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", + NavBar = "navbar", + Navto = "navto", + NavTree = "navtree", + NavTreeFull = "navtree-full", + DocumentHighlights = "documentHighlights", + Open = "open", + Quickinfo = "quickinfo", + References = "references", + Reload = "reload", + Rename = "rename", + Saveto = "saveto", + SignatureHelp = "signatureHelp", + FindSourceDefinition = "findSourceDefinition", + Status = "status", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", + UpdateOpen = "updateOpen", + GetOutliningSpans = "getOutliningSpans", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", + ApplyCodeActionCommand = "applyCodeActionCommand", + GetSupportedCodeFixes = "getSupportedCodeFixes", + GetApplicableRefactors = "getApplicableRefactors", + GetEditsForRefactor = "getEditsForRefactor", + GetMoveToRefactoringFileSuggestions = "getMoveToRefactoringFileSuggestions", + OrganizeImports = "organizeImports", + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin", + SelectionRange = "selectionRange", + ToggleLineComment = "toggleLineComment", + ToggleMultilineComment = "toggleMultilineComment", + CommentSelection = "commentSelection", + UncommentSelection = "uncommentSelection", + PrepareCallHierarchy = "prepareCallHierarchy", + ProvideCallHierarchyIncomingCalls = "provideCallHierarchyIncomingCalls", + ProvideCallHierarchyOutgoingCalls = "provideCallHierarchyOutgoingCalls", + ProvideInlayHints = "provideInlayHints" + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: "request" | "response" | "event"; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + type: "request"; + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + type: "event"; + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + type: "response"; + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * If success === false, this should always be provided. + * Otherwise, may (or may not) contain a success message. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: unknown; + /** + * Exposes information about the performance of this request-response pair. + */ + performanceData?: PerformanceData; + } + interface PerformanceData { + /** + * Time spent updating the program graph, in milliseconds. + */ + updateGraphDurationMs?: number; + /** + * The time spent creating or updating the auto-import program, in milliseconds. + */ + createAutoImportProviderProgramDurationMs?: number; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + interface StatusRequest extends Request { + command: CommandTypes.Status; + } + interface StatusResponseBody { + /** + * The TypeScript version (`ts.version`). + */ + version: string; + } + /** + * Response to StatusRequest + */ + interface StatusResponse extends Response { + body: StatusResponseBody; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to determine if the caret is inside a comment. + */ + interface SpanOfEnclosingCommentRequest extends FileLocationRequest { + command: CommandTypes.GetSpanOfEnclosingComment; + arguments: SpanOfEnclosingCommentRequestArgs; + } + interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { + /** + * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. + */ + onlyMultiLine: boolean; + } + /** + * Request to obtain outlining spans in file. + */ + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.GetOutliningSpans; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + /** + * Response to OutliningSpansRequest request. + */ + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + reportsDeprecated?: {}; + relatedInformation?: DiagnosticRelatedInformation[]; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + /** + * Request refactorings at a given position or selection area. + */ + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs & { + triggerReason?: RefactorTriggerReason; + kind?: string; + /** + * Include refactor actions that require additional arguments to be passed when + * calling 'GetEditsForRefactor'. When true, clients should inspect the + * `isInteractive` property of each returned `RefactorActionInfo` + * and ensure they are able to collect the appropriate arguments for any + * interactive refactor before offering it. + */ + includeInteractiveActions?: boolean; + }; + type RefactorTriggerReason = "implicit" | "invoked"; + /** + * Response is a list of available refactorings. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + /** + * Request refactorings at a given position or selection area to move to an existing file. + */ + interface GetMoveToRefactoringFileSuggestionsRequest extends Request { + command: CommandTypes.GetMoveToRefactoringFileSuggestions; + arguments: GetMoveToRefactoringFileSuggestionsRequestArgs; + } + type GetMoveToRefactoringFileSuggestionsRequestArgs = FileLocationOrRangeRequestArgs & { + kind?: string; + }; + /** + * Response is a list of available files. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ + interface GetMoveToRefactoringFileSuggestions extends Response { + body: { + newFileName: string; + files: string[]; + }; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + interface RefactorActionInfo { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + /** + * A message to show to the user if the refactoring cannot be applied in + * the current context. + */ + notApplicableReason?: string; + /** + * The hierarchical dotted name of the refactor action. + */ + kind?: string; + /** + * Indicates that the action requires additional arguments to be passed + * when calling 'GetEditsForRefactor'. + */ + isInteractive?: boolean; + } + interface GetEditsForRefactorRequest extends Request { + command: CommandTypes.GetEditsForRefactor; + arguments: GetEditsForRefactorRequestArgs; + } + /** + * Request the edits that a particular refactoring action produces. + * Callers must specify the name of the refactor and the name of the action. + */ + type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { + refactor: string; + action: string; + interactiveRefactorArguments?: InteractiveRefactorArguments; + }; + interface GetEditsForRefactorResponse extends Response { + body?: RefactorEditInfo; + } + interface RefactorEditInfo { + edits: FileCodeEdits[]; + /** + * An optional location where the editor should start a rename operation once + * the refactoring edits have been applied + */ + renameLocation?: Location; + renameFilename?: string; + notApplicableReason?: string; + } + /** + * Organize imports by: + * 1) Removing unused imports + * 2) Coalescing imports from the same module + * 3) Sorting imports + */ + interface OrganizeImportsRequest extends Request { + command: CommandTypes.OrganizeImports; + arguments: OrganizeImportsRequestArgs; + } + type OrganizeImportsScope = GetCombinedCodeFixScope; + enum OrganizeImportsMode { + All = "All", + SortAndCombine = "SortAndCombine", + RemoveUnused = "RemoveUnused" + } + interface OrganizeImportsRequestArgs { + scope: OrganizeImportsScope; + /** @deprecated Use `mode` instead */ + skipDestructiveCodeActions?: boolean; + mode?: OrganizeImportsMode; + } + interface OrganizeImportsResponse extends Response { + body: readonly FileCodeEdits[]; + } + interface GetEditsForFileRenameRequest extends Request { + command: CommandTypes.GetEditsForFileRename; + arguments: GetEditsForFileRenameRequestArgs; + } + /** Note: Paths may also be directories. */ + interface GetEditsForFileRenameRequestArgs { + readonly oldFilePath: string; + readonly newFilePath: string; + } + interface GetEditsForFileRenameResponse extends Response { + body: readonly FileCodeEdits[]; + } + /** + * Request for the available codefixes at a specific position. + */ + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + interface GetCombinedCodeFixRequest extends Request { + command: CommandTypes.GetCombinedCodeFix; + arguments: GetCombinedCodeFixRequestArgs; + } + interface GetCombinedCodeFixResponse extends Response { + body: CombinedCodeActions; + } + interface ApplyCodeActionCommandRequest extends Request { + command: CommandTypes.ApplyCodeActionCommand; + arguments: ApplyCodeActionCommandRequestArgs; + } + interface ApplyCodeActionCommandResponse extends Response { + } + interface FileRangeRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + startOffset: number; + /** + * The line number for the request (1-based). + */ + endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + endOffset: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRangeRequestArgs { + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes: readonly number[]; + } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; + } + interface ApplyCodeActionCommandRequestArgs { + /** May also be an array of commands. */ + command: {}; + } + /** + * Response for GetCodeFixes request. + */ + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * A request to get codes of supported code fixes. + */ + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + arguments?: Partial; + } + /** + * A response for GetSupportedCodeFixesRequest request. + */ + interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + /** + * A request to get encoded semantic classifications for a span in the file + */ + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + /** + * Optional parameter for the semantic highlighting response, if absent it + * defaults to "original". + */ + format?: "original" | "2020"; + } + /** The response for a EncodedSemanticClassificationsRequest */ + interface EncodedSemanticClassificationsResponse extends Response { + body?: EncodedSemanticClassificationsResponseBody; + } + /** + * Implementation response message. Gives series of text spans depending on the format ar. + */ + interface EncodedSemanticClassificationsResponseBody { + endOfLineState: EndOfLineState; + spans: number[]; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + interface DefinitionAndBoundSpanRequest extends FileLocationRequest { + readonly command: CommandTypes.DefinitionAndBoundSpan; + } + interface FindSourceDefinitionRequest extends FileLocationRequest { + readonly command: CommandTypes.FindSourceDefinition; + } + interface DefinitionAndBoundSpanResponse extends Response { + readonly body: DefinitionInfoAndBoundSpan; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + /** + * Location in source code expressed as (one-based) line and (one-based) column offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + interface JSDocTagInfo { + /** Name of the JSDoc tag */ + name: string; + /** + * Comment text after the JSDoc tag -- the text after the tag name until the next tag or end of comment + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. + */ + text?: string | SymbolDisplayPart[]; + } + interface TextSpanWithContext extends TextSpan { + contextStart?: Location; + contextEnd?: Location; + } + interface FileSpanWithContext extends FileSpan, TextSpanWithContext { + } + interface DefinitionInfo extends FileSpanWithContext { + /** + * When true, the file may or may not exist. + */ + unverified?: boolean; + } + interface DefinitionInfoAndBoundSpan { + definitions: readonly DefinitionInfo[]; + textSpan: TextSpan; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: DefinitionInfo[]; + } + interface DefinitionInfoAndBoundSpanResponse extends Response { + body?: DefinitionInfoAndBoundSpan; + } + /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ + type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpanWithContext[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpanWithContext[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + interface JsxClosingTagRequest extends FileLocationRequest { + readonly command: CommandTypes.JsxClosingTag; + readonly arguments: JsxClosingTagRequestArgs; + } + interface JsxClosingTagRequestArgs extends FileLocationRequestArgs { + } + interface JsxClosingTagResponse extends Response { + readonly body: TextInsertion; + } + interface LinkedEditingRangeRequest extends FileLocationRequest { + readonly command: CommandTypes.LinkedEditingRange; + } + interface LinkedEditingRangesBody { + ranges: TextSpan[]; + wordPattern?: string; + } + interface LinkedEditingRangeResponse extends Response { + readonly body: LinkedEditingRangesBody; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + */ + interface HighlightSpan extends TextSpanWithContext { + kind: HighlightSpanKind; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpanWithContext { + /** + * Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has loaded the referencing files). + * + * If {@link UserPreferences.disableLineTextInReferences} is enabled, the property won't be filled + */ + lineText?: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * Present only if the search was triggered from a declaration. + * True indicates that the references refers to the same symbol + * (i.e. has the same meaning) as the declaration that began the + * search. + */ + isDefinition?: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: readonly ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + interface FileReferencesRequest extends FileRequest { + command: CommandTypes.FileReferences; + } + interface FileReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: readonly ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + } + interface FileReferencesResponse extends Response { + body?: FileReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + /** + * True if item can be renamed. + */ + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpanWithContext { + readonly prefixText?: string; + readonly suffixText?: string; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: readonly SpanGroup[]; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicitly. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKindName | ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * Explicitly specified type acquisition for the project + */ + typeAcquisition?: TypeAcquisition; + } + interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin & WatchOptions; + interface FileWithProjectReferenceRedirectInfo { + /** + * Name of file + */ + fileName: string; + /** + * True if the file is primarily included in a referenced project + */ + isSourceOfProjectReferenceRedirect: boolean; + } + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[] | FileWithProjectReferenceRedirectInfo[]; + /** + * List of removed files + */ + removed: string[] | FileWithProjectReferenceRedirectInfo[]; + /** + * List of updated files + */ + updated: string[] | FileWithProjectReferenceRedirectInfo[]; + /** + * List of files that have had their project reference redirect status updated + * Only provided when the synchronizeProjectList request has includeProjectReferenceRedirectInfo set to true + */ + updatedRedirects?: FileWithProjectReferenceRedirectInfo[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + preferences?: UserPreferences; + /** + * The host's additional supported .js file extensions + */ + extraFileExtensions?: FileExtensionInfo[]; + watchOptions?: WatchOptions; + } + enum WatchFileKind { + FixedPollingInterval = "FixedPollingInterval", + PriorityPollingInterval = "PriorityPollingInterval", + DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling", + UseFsEvents = "UseFsEvents", + UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory" + } + enum WatchDirectoryKind { + UseFsEvents = "UseFsEvents", + FixedPollingInterval = "FixedPollingInterval", + DynamicPriorityPolling = "DynamicPriorityPolling", + FixedChunkSizePolling = "FixedChunkSizePolling" + } + enum PollingWatchKind { + FixedInterval = "FixedInterval", + PriorityInterval = "PriorityInterval", + DynamicPriority = "DynamicPriority", + FixedChunkSize = "FixedChunkSize" + } + interface WatchOptions { + watchFile?: WatchFileKind | ts.WatchFileKind; + watchDirectory?: WatchDirectoryKind | ts.WatchDirectoryKind; + fallbackPolling?: PollingWatchKind | ts.PollingWatchKind; + synchronousWatchDirectory?: boolean; + excludeDirectories?: string[]; + excludeFiles?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } + interface ConfigurePluginResponse extends Response { + } + interface SelectionRangeRequest extends FileRequest { + command: CommandTypes.SelectionRange; + arguments: SelectionRangeRequestArgs; + } + interface SelectionRangeRequestArgs extends FileRequestArgs { + locations: Location[]; + } + interface SelectionRangeResponse extends Response { + body?: SelectionRange[]; + } + interface SelectionRange { + textSpan: TextSpan; + parent?: SelectionRange; + } + interface ToggleLineCommentRequest extends FileRequest { + command: CommandTypes.ToggleLineComment; + arguments: FileRangeRequestArgs; + } + interface ToggleMultilineCommentRequest extends FileRequest { + command: CommandTypes.ToggleMultilineComment; + arguments: FileRangeRequestArgs; + } + interface CommentSelectionRequest extends FileRequest { + command: CommandTypes.CommentSelection; + arguments: FileRangeRequestArgs; + } + interface UncommentSelectionRequest extends FileRequest { + command: CommandTypes.UncommentSelection; + arguments: FileRangeRequestArgs; + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: ScriptKindName; + /** + * Used to limit the searching for project config file. If given the searching will stop at this + * root path; otherwise it will go all the way up to the dist root path. + */ + projectRootPath?: string; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Request to synchronize list of open files with the client + */ + interface UpdateOpenRequest extends Request { + command: CommandTypes.UpdateOpen; + arguments: UpdateOpenRequestArgs; + } + /** + * Arguments to UpdateOpenRequest + */ + interface UpdateOpenRequestArgs { + /** + * List of newly open files + */ + openFiles?: OpenRequestArgs[]; + /** + * List of open files files that were changes + */ + changedFiles?: FileCodeEdits[]; + /** + * List of files that were closed + */ + closedFiles?: string[]; + } + /** + * External projects have a typeAcquisition option so they need to be added separately to compiler options for inferred projects. + */ + type InferredProjectCompilerOptions = ExternalProjectCompilerOptions & TypeAcquisition; + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: InferredProjectCompilerOptions; + /** + * Specifies the project root path used to scope compiler options. + * It is an error to provide this property if the server has not been started with + * `useInferredProjectPerProjectRoot` enabled. + */ + projectRootPath?: string; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + /** + * true if project uses outFile or out compiler option + */ + projectUsesOutFile: boolean; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + includeLinePosition?: boolean; + /** if true - return response as object with emitSkipped and diagnostics */ + richResponse?: boolean; + } + interface CompileOnSaveEmitFileResponse extends Response { + body: boolean | EmitResult; + } + interface EmitResult { + emitSkipped: boolean; + diagnostics: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + arguments: FileLocationRequestArgs; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. + */ + documentation: string | SymbolDisplayPart[]; + /** + * JSDoc tags associated with symbol. + */ + tags: JSDocTagInfo[]; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + /** The code actions that are available */ + body?: CodeFixAction[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileCodeEdits[]; + /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ + commands?: {}[]; + } + interface CombinedCodeActions { + changes: readonly FileCodeEdits[]; + commands?: readonly {}[]; + } + interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; + /** + * If present, one may call 'getCombinedCodeFix' with this fixId. + * This may be omitted to indicate that the code fix can't be applied in a group. + */ + fixId?: {}; + /** Should be present if and only if 'fixId' is. */ + fixAllDescription?: string; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; + enum CompletionTriggerKind { + /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ + Invoked = 1, + /** Completion was triggered by a trigger character. */ + TriggerCharacter = 2, + /** Completion was re-triggered as the current completion list is incomplete. */ + TriggerForIncompleteCompletions = 3 + } + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + /** + * Character that was responsible for triggering completion. + * Should be `undefined` if a user manually requested completion. + */ + triggerCharacter?: CompletionsTriggerCharacter; + triggerKind?: CompletionTriggerKind; + /** + * @deprecated Use UserPreferences.includeCompletionsForModuleExports + */ + includeExternalModuleExports?: boolean; + /** + * @deprecated Use UserPreferences.includeCompletionsWithInsertText + */ + includeInsertTextCompletions?: boolean; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions | CommandTypes.CompletionInfo; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: (string | CompletionEntryIdentifier)[]; + } + interface CompletionEntryIdentifier { + name: string; + source?: string; + data?: unknown; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** A part of a symbol description that links from a jsdoc @link tag to a declaration */ + interface JSDocLinkDisplayPart extends SymbolDisplayPart { + /** The location of the declaration that the @link tag links to. */ + target: FileSpan; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: string; + /** + * A string that should be used when filtering a set of + * completion items. + */ + filterText?: string; + /** + * `insertText` should be interpreted as a snippet if true. + */ + isSnippet?: true; + /** + * An optional span that indicates the text to be replaced by this completion item. + * If present, this span should be used instead of the default one. + * It will be set if the required span differs from the one generated by the default replacement behavior. + */ + replacementSpan?: TextSpan; + /** + * Indicates whether commiting this completion entry will require additional code actions to be + * made to avoid errors. The CompletionEntryDetails will have these actions. + */ + hasAction?: true; + /** + * Identifier (not necessarily human-readable) identifying where this completion came from. + */ + source?: string; + /** + * Human-readable description of the `source`. + */ + sourceDisplay?: SymbolDisplayPart[]; + /** + * Additional details for the label. + */ + labelDetails?: CompletionEntryLabelDetails; + /** + * If true, this completion should be highlighted as recommended. There will only be one of these. + * This will be set when we know the user should write an expression with a certain type and that type is an enum or constructable class. + * Then either that enum/class or a namespace containing it will be the recommended symbol. + */ + isRecommended?: true; + /** + * If true, this completion was generated from traversing the name table of an unchecked JS file, + * and therefore may not be accurate. + */ + isFromUncheckedFile?: true; + /** + * If true, this completion was for an auto-import of a module not yet in the program, but listed + * in the project package.json. Used for telemetry reporting. + */ + isPackageJsonImport?: true; + /** + * If true, this completion was an auto-import-style completion of an import statement (i.e., the + * module specifier was inserted along with the imported identifier). Used for telemetry reporting. + */ + isImportStatementCompletion?: true; + /** + * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, + * that allows TS Server to look up the symbol represented by the completion item, disambiguating + * items with the same name. + */ + data?: unknown; + } + interface CompletionEntryLabelDetails { + /** + * An optional string which is rendered less prominently directly after + * {@link CompletionEntry.name name}, without any spacing. Should be + * used for function signatures or type annotations. + */ + detail?: string; + /** + * An optional string which is rendered less prominently after + * {@link CompletionEntryLabelDetails.detail}. Should be used for fully qualified + * names or file path. + */ + description?: string; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation?: SymbolDisplayPart[]; + /** + * JSDoc tags for the symbol. + */ + tags?: JSDocTagInfo[]; + /** + * The associated code actions for this entry + */ + codeActions?: CodeAction[]; + /** + * @deprecated Use `sourceDisplay` instead. + */ + source?: SymbolDisplayPart[]; + /** + * Human-readable description of the `source` from the CompletionEntry. + */ + sourceDisplay?: SymbolDisplayPart[]; + } + /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionInfoResponse extends Response { + body?: CompletionInfo; + } + interface CompletionInfo { + readonly flags?: number; + readonly isGlobalCompletion: boolean; + readonly isMemberCompletion: boolean; + readonly isNewIdentifierLocation: boolean; + /** + * In the absence of `CompletionEntry["replacementSpan"]`, the editor may choose whether to use + * this span or its default one. If `CompletionEntry["replacementSpan"]` is defined, that span + * must be used to commit that completion entry. + */ + readonly optionalReplacementSpan?: TextSpan; + readonly isIncomplete?: boolean; + readonly entries: readonly CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + /** + * The signature's JSDoc tags + */ + tags: JSDocTagInfo[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + type SignatureHelpTriggerCharacter = "," | "(" | "<"; + type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + /** + * Reason why signature help was invoked. + * See each individual possible + */ + triggerReason?: SignatureHelpTriggerReason; + } + type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ + interface SignatureHelpInvokedReason { + kind: "invoked"; + triggerCharacter?: undefined; + } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ + interface SignatureHelpCharacterTypedReason { + kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter: SignatureHelpTriggerCharacter; + } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ + interface SignatureHelpRetriggeredReason { + kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter?: SignatureHelpRetriggerCharacter; + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + type InlayHintKind = "Type" | "Parameter" | "Enum"; + interface InlayHintsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + interface InlayHintsRequest extends Request { + command: CommandTypes.ProvideInlayHints; + arguments: InlayHintsRequestArgs; + } + interface InlayHintItem { + /** This property will be the empty string when displayParts is set. */ + text: string; + position: Location; + kind: InlayHintKind; + whitespaceBefore?: boolean; + whitespaceAfter?: boolean; + displayParts?: InlayHintItemDisplayPart[]; + } + interface InlayHintItemDisplayPart { + text: string; + span?: FileSpan; + } + interface InlayHintsResponse extends Response { + body?: InlayHintItem[]; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SuggestionDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SuggestionDiagnosticsSync; + arguments: SuggestionDiagnosticsSyncRequestArgs; + } + type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; + type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + type RequestCompletedEventName = "requestCompleted"; + /** + * Event that is sent when server have finished processing request with specified id. + */ + interface RequestCompletedEvent extends Event { + event: RequestCompletedEventName; + body: RequestCompletedEventBody; + } + interface RequestCompletedEventBody { + request_seq: number; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + /** + * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". + */ + category: string; + reportsUnnecessary?: {}; + reportsDeprecated?: {}; + /** + * Any related spans the diagnostic may have, such as other locations relevant to an error, such as declarartion sites + */ + relatedInformation?: DiagnosticRelatedInformation[]; + /** + * The error code of the diagnostic message. + */ + code?: number; + /** + * The name of the plugin reporting the message. + */ + source?: string; + } + interface DiagnosticWithFileName extends Diagnostic { + /** + * Name of the file the diagnostic is in + */ + fileName: string; + } + /** + * Represents additional spans returned with a diagnostic which are relevant to it + */ + interface DiagnosticRelatedInformation { + /** + * The category of the related information message, e.g. "error", "warning", or "suggestion". + */ + category: string; + /** + * The code used ot identify the related information + */ + code: number; + /** + * Text of related or additional information. + */ + message: string; + /** + * Associated location + */ + span?: FileSpan; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag"; + /** + * Event message for DiagnosticEventKind event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + event: DiagnosticEventKind; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: DiagnosticWithFileName[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent extends Event { + event: ProjectLanguageServiceStateEventName; + body?: ProjectLanguageServiceStateEventBody; + } + interface ProjectLanguageServiceStateEventBody { + /** + * Project name that has changes in the state of language service. + * For configured projects this will be the config file path. + * For external projects this will be the name of the projects specified when project was open. + * For inferred projects this event is not raised. + */ + projectName: string; + /** + * True if language service state switched from disabled to enabled + * and false otherwise. + */ + languageServiceEnabled: boolean; + } + type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent extends Event { + event: ProjectsUpdatedInBackgroundEventName; + body: ProjectsUpdatedInBackgroundEventBody; + } + interface ProjectsUpdatedInBackgroundEventBody { + /** + * Current set of open files + */ + openFiles: string[]; + } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } + type LargeFileReferencedEventName = "largeFileReferenced"; + interface LargeFileReferencedEvent extends Event { + event: LargeFileReferencedEventName; + body: LargeFileReferencedEventBody; + } + interface LargeFileReferencedEventBody { + /** + * name of the large file being loaded + */ + file: string; + /** + * size of the file + */ + fileSize: number; + /** + * max file size allowed on the server + */ + maxFileSize: number; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + /** + * The file for the request (absolute pathname required). + */ + file?: string; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ + currentFileOnly?: boolean; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends Request { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem extends FileSpan { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * exact, substring, or prefix. + */ + matchKind: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: ScriptElementKind; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: ScriptElementKind; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: ScriptElementKind; + kindModifiers: string; + spans: TextSpan[]; + nameSpan: TextSpan | undefined; + childItems?: NavigationTree[]; + } + type TelemetryEventName = "telemetry"; + interface TelemetryEvent extends Event { + event: TelemetryEventName; + body: TelemetryEventBody; + } + interface TelemetryEventBody { + telemetryEventName: string; + payload: any; + } + type TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; + interface TypesInstallerInitializationFailedEvent extends Event { + event: TypesInstallerInitializationFailedEventName; + body: TypesInstallerInitializationFailedEventBody; + } + interface TypesInstallerInitializationFailedEventBody { + message: string; + } + type TypingsInstalledTelemetryEventName = "typingsInstalled"; + interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { + telemetryEventName: TypingsInstalledTelemetryEventName; + payload: TypingsInstalledTelemetryEventPayload; + } + interface TypingsInstalledTelemetryEventPayload { + /** + * Comma separated list of installed typing packages + */ + installedPackages: string; + /** + * true if install request succeeded, otherwise - false + */ + installSuccess: boolean; + /** + * version of typings installer + */ + typingsInstallerVersion: string; + } + type BeginInstallTypesEventName = "beginInstallTypes"; + type EndInstallTypesEventName = "endInstallTypes"; + interface BeginInstallTypesEvent extends Event { + event: BeginInstallTypesEventName; + body: BeginInstallTypesEventBody; + } + interface EndInstallTypesEvent extends Event { + event: EndInstallTypesEventName; + body: EndInstallTypesEventBody; + } + interface InstallTypesEventBody { + /** + * correlation id to match begin and end events + */ + eventId: number; + /** + * list of packages to install + */ + packages: readonly string[]; + } + interface BeginInstallTypesEventBody extends InstallTypesEventBody { + } + interface EndInstallTypesEventBody extends InstallTypesEventBody { + /** + * true if installation succeeded, otherwise false + */ + success: boolean; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + interface CallHierarchyItem { + name: string; + kind: ScriptElementKind; + kindModifiers?: string; + file: string; + span: TextSpan; + selectionSpan: TextSpan; + containerName?: string; + } + interface CallHierarchyIncomingCall { + from: CallHierarchyItem; + fromSpans: TextSpan[]; + } + interface CallHierarchyOutgoingCall { + to: CallHierarchyItem; + fromSpans: TextSpan[]; + } + interface PrepareCallHierarchyRequest extends FileLocationRequest { + command: CommandTypes.PrepareCallHierarchy; + } + interface PrepareCallHierarchyResponse extends Response { + readonly body: CallHierarchyItem | CallHierarchyItem[]; + } + interface ProvideCallHierarchyIncomingCallsRequest extends FileLocationRequest { + command: CommandTypes.ProvideCallHierarchyIncomingCalls; + } + interface ProvideCallHierarchyIncomingCallsResponse extends Response { + readonly body: CallHierarchyIncomingCall[]; + } + interface ProvideCallHierarchyOutgoingCallsRequest extends FileLocationRequest { + command: CommandTypes.ProvideCallHierarchyOutgoingCalls; + } + interface ProvideCallHierarchyOutgoingCallsResponse extends Response { + readonly body: CallHierarchyOutgoingCall[]; + } + enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart" + } + enum SemicolonPreference { + Ignore = "ignore", + Insert = "insert", + Remove = "remove" + } + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + trimTrailingWhitespace?: boolean; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterConstructor?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingEmptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + insertSpaceBeforeFunctionParenthesis?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; + semicolons?: SemicolonPreference; + indentSwitchCase?: boolean; + } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "auto" | "double" | "single"; + /** + * If enabled, TypeScript will search through all external modules' exports and add them to the completions list. + * This affects lone identifier completions but not completions on the right hand side of `obj.`. + */ + readonly includeCompletionsForModuleExports?: boolean; + /** + * Enables auto-import-style completions on partially-typed import statements. E.g., allows + * `import write|` to be completed to `import { writeFile } from "fs"`. + */ + readonly includeCompletionsForImportStatements?: boolean; + /** + * Allows completions to be formatted with snippet text, indicated by `CompletionItem["isSnippet"]`. + */ + readonly includeCompletionsWithSnippetText?: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + readonly includeCompletionsWithInsertText?: boolean; + /** + * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, + * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined + * values, with insertion text to replace preceding `.` tokens with `?.`. + */ + readonly includeAutomaticOptionalChainCompletions?: boolean; + /** + * If enabled, completions for class members (e.g. methods and properties) will include + * a whole declaration for the member. + * E.g., `class A { f| }` could be completed to `class A { foo(): number {} }`, instead of + * `class A { foo }`. + */ + readonly includeCompletionsWithClassMemberSnippets?: boolean; + /** + * If enabled, object literal methods will have a method declaration completion entry in addition + * to the regular completion entry containing just the method name. + * E.g., `const objectLiteral: T = { f| }` could be completed to `const objectLiteral: T = { foo(): void {} }`, + * in addition to `const objectLiteral: T = { foo }`. + */ + readonly includeCompletionsWithObjectLiteralMethodSnippets?: boolean; + /** + * Indicates whether {@link CompletionEntry.labelDetails completion entry label details} are supported. + * If not, contents of `labelDetails` may be included in the {@link CompletionEntry.name} property. + */ + readonly useLabelDetailsInCompletionEntries?: boolean; + readonly allowIncompleteCompletions?: boolean; + readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; + readonly provideRefactorNotApplicableReason?: boolean; + readonly allowRenameOfImportPath?: boolean; + readonly includePackageJsonAutoImports?: "auto" | "on" | "off"; + readonly jsxAttributeCompletionStyle?: "auto" | "braces" | "none"; + readonly displayPartsForJSDoc?: boolean; + readonly generateReturnInDocTemplate?: boolean; + readonly includeInlayParameterNameHints?: "none" | "literals" | "all"; + readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; + readonly includeInlayFunctionParameterTypeHints?: boolean; + readonly includeInlayVariableTypeHints?: boolean; + readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; + readonly includeInlayPropertyDeclarationTypeHints?: boolean; + readonly includeInlayFunctionLikeReturnTypeHints?: boolean; + readonly includeInlayEnumMemberValueHints?: boolean; + readonly interactiveInlayHints?: boolean; + readonly autoImportFileExcludePatterns?: string[]; + /** + * Indicates whether imports should be organized in a case-insensitive manner. + */ + readonly organizeImportsIgnoreCase?: "auto" | boolean; + /** + * Indicates whether imports should be organized via an "ordinal" (binary) comparison using the numeric value + * of their code points, or via "unicode" collation (via the + * [Unicode Collation Algorithm](https://unicode.org/reports/tr10/#Scope)) using rules associated with the locale + * specified in {@link organizeImportsCollationLocale}. + * + * Default: `"ordinal"`. + */ + readonly organizeImportsCollation?: "ordinal" | "unicode"; + /** + * Indicates the locale to use for "unicode" collation. If not specified, the locale `"en"` is used as an invariant + * for the sake of consistent sorting. Use `"auto"` to use the detected UI locale. + * + * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. + * + * Default: `"en"` + */ + readonly organizeImportsCollationLocale?: string; + /** + * Indicates whether numeric collation should be used for digit sequences in strings. When `true`, will collate + * strings such that `a1z < a2z < a100z`. When `false`, will collate strings such that `a1z < a100z < a2z`. + * + * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. + * + * Default: `false` + */ + readonly organizeImportsNumericCollation?: boolean; + /** + * Indicates whether accents and other diacritic marks are considered unequal for the purpose of collation. When + * `true`, characters with accents and other diacritics will be collated in the order defined by the locale specified + * in {@link organizeImportsCollationLocale}. + * + * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. + * + * Default: `true` + */ + readonly organizeImportsAccentCollation?: boolean; + /** + * Indicates whether upper case or lower case should sort first. When `false`, the default order for the locale + * specified in {@link organizeImportsCollationLocale} is used. + * + * This preference is ignored if {@link organizeImportsCollation} is not `"unicode"`. This preference is also + * ignored if we are using case-insensitive sorting, which occurs when {@link organizeImportsIgnoreCase} is `true`, + * or if {@link organizeImportsIgnoreCase} is `"auto"` and the auto-detected case sensitivity is determined to be + * case-insensitive. + * + * Default: `false` + */ + readonly organizeImportsCaseFirst?: "upper" | "lower" | false; + /** + * Indicates whether {@link ReferencesResponseItem.lineText} is supported. + */ + readonly disableLineTextInReferences?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + checkJs?: boolean; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + downlevelIteration?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + plugins?: PluginImport[]; + preserveConstEnums?: boolean; + preserveSymlinks?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + references?: ProjectReference[]; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strict?: boolean; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + useDefineForClassFields?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + resolveJsonModule?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React" + } + enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", + ESNext = "ESNext" + } + enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node" + } + enum NewLineKind { + Crlf = "Crlf", + Lf = "Lf" + } + enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", + ES2016 = "ES2016", + ES2017 = "ES2017", + ES2018 = "ES2018", + ES2019 = "ES2019", + ES2020 = "ES2020", + ES2021 = "ES2021", + ES2022 = "ES2022", + ESNext = "ESNext" + } + enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + jsxOpenTagName = 19, + jsxCloseTagName = 20, + jsxSelfClosingTagName = 21, + jsxAttribute = 22, + jsxText = 23, + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 + } + } + namespace typingsInstaller { + interface Log { + isEnabled(): boolean; + writeLine(text: string): void; + } + type RequestCompletedAction = (success: boolean) => void; + interface PendingRequest { + requestId: number; + packageNames: string[]; + cwd: string; + onRequestCompleted: RequestCompletedAction; + } + abstract class TypingsInstaller { + protected readonly installTypingHost: InstallTypingHost; + private readonly globalCachePath; + private readonly safeListPath; + private readonly typesMapLocation; + private readonly throttleLimit; + protected readonly log: Log; + private readonly packageNameToTypingLocation; + private readonly missingTypingsSet; + private readonly knownCachesSet; + private readonly projectWatchers; + private safeList; + private installRunCount; + private inFlightRequestCount; + abstract readonly typesRegistry: Map>; + constructor(installTypingHost: InstallTypingHost, globalCachePath: string, safeListPath: Path, typesMapLocation: Path, throttleLimit: number, log?: Log); + closeProject(req: CloseProject): void; + private closeWatchers; + install(req: DiscoverTypings): void; + private initializeSafeList; + private processCacheLocation; + private filterTypings; + protected ensurePackageDirectoryExists(directory: string): void; + private installTypings; + private ensureDirectoryExists; + private watchFiles; + private createSetTypings; + private installTypingsAsync; + private executeWithThrottling; + protected abstract installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void; + protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | WatchTypingLocations): void; + protected readonly latestDistTag = "latest"; + } + } + interface CompressedData { + length: number; + compressionKind: string; + data: any; + } + type ModuleImportResult = { + module: {}; + error: undefined; + } | { + module: undefined; + error: { + stack?: string; + message?: string; + }; + }; + /** @deprecated Use {@link ModuleImportResult} instead. */ + type RequireResult = ModuleImportResult; + interface ServerHost extends System { + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; + setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + clearTimeout(timeoutId: any): void; + setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + clearImmediate(timeoutId: any): void; + gc?(): void; + trace?(s: string): void; + require?(initialPath: string, moduleName: string): ModuleImportResult; + } + function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings; + function toNormalizedPath(fileName: string): NormalizedPath; + function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; + function asNormalizedPath(fileName: string): NormalizedPath; + function createNormalizedPathMap(): NormalizedPathMap; + function isInferredProjectName(name: string): boolean; + function makeInferredProjectName(counter: number): string; + function createSortedArray(): SortedArray; + enum LogLevel { + terse = 0, + normal = 1, + requestTime = 2, + verbose = 3 + } + const emptyArray: SortedReadonlyArray; + interface Logger { + close(): void; + hasLevel(level: LogLevel): boolean; + loggingEnabled(): boolean; + perftrc(s: string): void; + info(s: string): void; + startGroup(): void; + endGroup(): void; + msg(s: string, type?: Msg): void; + getLogFileName(): string | undefined; + } + enum Msg { + Err = "Err", + Info = "Info", + Perf = "Perf" + } + namespace Errors { + function ThrowNoProject(): never; + function ThrowProjectLanguageServiceDisabled(): never; + function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; + } + type NormalizedPath = string & { + __normalizedPathTag: any; + }; + interface NormalizedPathMap { + get(path: NormalizedPath): T | undefined; + set(path: NormalizedPath, value: T): void; + contains(path: NormalizedPath): boolean; + remove(path: NormalizedPath): void; + } + function isDynamicFileName(fileName: NormalizedPath): boolean; + class ScriptInfo { + private readonly host; + readonly fileName: NormalizedPath; + readonly scriptKind: ScriptKind; + readonly hasMixedContent: boolean; + readonly path: Path; + /** + * All projects that include this file + */ + readonly containingProjects: Project[]; + private formatSettings; + private preferences; + constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path, initialVersion?: number); + isScriptOpen(): boolean; + open(newText: string | undefined): void; + close(fileExists?: boolean): void; + getSnapshot(): IScriptSnapshot; + private ensureRealPath; + getFormatCodeSettings(): FormatCodeSettings | undefined; + getPreferences(): protocol.UserPreferences | undefined; + attachToProject(project: Project): boolean; + isAttached(project: Project): boolean; + detachFromProject(project: Project): void; + detachAllProjects(): void; + getDefaultProject(): Project; + registerFileUpdate(): void; + setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; + getLatestVersion(): string; + saveTo(fileName: string): void; + reloadFromFile(tempFileName?: NormalizedPath): boolean; + editContent(start: number, end: number, newText: string): void; + markContainingProjectsAsDirty(): void; + isOrphan(): boolean; + /** + * @param line 1 based index + */ + lineToTextSpan(line: number): TextSpan; + /** + * @param line 1 based index + * @param offset 1 based index + */ + lineOffsetToPosition(line: number, offset: number): number; + positionToLineOffset(position: number): protocol.Location; + isJavaScript(): boolean; + } + interface InstallPackageOptionsWithProject extends InstallPackageOptions { + projectName: string; + projectRootPath: Path; + } + interface ITypingsInstaller { + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptionsWithProject): Promise; + enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; + attach(projectService: ProjectService): void; + onProjectClosed(p: Project): void; + readonly globalTypingsCacheLocation: string | undefined; + } + const nullTypingsInstaller: ITypingsInstaller; + function allRootFilesAreJsOrDts(project: Project): boolean; + function allFilesAreJsOrDts(project: Project): boolean; + enum ProjectKind { + Inferred = 0, + Configured = 1, + External = 2, + AutoImportProvider = 3, + Auxiliary = 4 + } + interface PluginCreateInfo { + project: Project; + languageService: LanguageService; + languageServiceHost: LanguageServiceHost; + serverHost: ServerHost; + session?: Session; + config: any; + } + interface PluginModule { + create(createInfo: PluginCreateInfo): LanguageService; + getExternalFiles?(proj: Project): string[]; + onConfigurationChanged?(config: any): void; + } + interface PluginModuleWithName { + name: string; + module: PluginModule; + } + type PluginModuleFactory = (mod: { + typescript: typeof ts; + }) => PluginModule; + abstract class Project implements LanguageServiceHost, ModuleResolutionHost { + readonly projectKind: ProjectKind; + readonly projectService: ProjectService; + private documentRegistry; + private compilerOptions; + compileOnSaveEnabled: boolean; + protected watchOptions: WatchOptions | undefined; + private rootFiles; + private rootFilesMap; + private program; + private externalFiles; + private missingFilesMap; + private generatedFilesMap; + protected languageService: LanguageService; + languageServiceEnabled: boolean; + readonly trace?: (s: string) => void; + readonly realpath?: (path: string) => string; + private builderState; + /** + * Set of files names that were updated since the last call to getChangesSinceVersion. + */ + private updatedFileNames; + /** + * Set of files that was returned from the last call to getChangesSinceVersion. + */ + private lastReportedFileNames; + /** + * Last version that was reported. + */ + private lastReportedVersion; + /** + * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) + * This property is changed in 'updateGraph' based on the set of files in program + */ + private projectProgramVersion; + /** + * Current version of the project state. It is changed when: + * - new root file was added/removed + * - edit happen in some file that is currently included in the project. + * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project + */ + private projectStateVersion; + protected projectErrors: Diagnostic[] | undefined; + protected isInitialLoadPending: () => boolean; + private readonly cancellationToken; + isNonTsProject(): boolean; + isJsOnlyProject(): boolean; + static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined; + isKnownTypesPackageName(name: string): boolean; + installPackage(options: InstallPackageOptions): Promise; + private get typingsCache(); + getCompilationSettings(): ts.CompilerOptions; + getCompilerOptions(): ts.CompilerOptions; + getNewLine(): string; + getProjectVersion(): string; + getProjectReferences(): readonly ProjectReference[] | undefined; + getScriptFileNames(): string[]; + private getOrCreateScriptInfoAndAttachToProject; + getScriptKind(fileName: string): ts.ScriptKind; + getScriptVersion(filename: string): string; + getScriptSnapshot(filename: string): IScriptSnapshot | undefined; + getCancellationToken(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(): string; + useCaseSensitiveFileNames(): boolean; + readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; + readFile(fileName: string): string | undefined; + writeFile(fileName: string, content: string): void; + fileExists(file: string): boolean; + getModuleResolutionCache(): ModuleResolutionCache | undefined; + directoryExists(path: string): boolean; + getDirectories(path: string): string[]; + log(s: string): void; + error(s: string): void; + private setInternalCompilerOptionsForEmittingJsFiles; + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors(): readonly Diagnostic[]; + /** + * Get all the project errors + */ + getAllProjectErrors(): readonly Diagnostic[]; + setProjectErrors(projectErrors: Diagnostic[] | undefined): void; + getLanguageService(ensureSynchronized?: boolean): LanguageService; + getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; + /** + * Returns true if emit was conducted + */ + emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): EmitResult; + enableLanguageService(): void; + disableLanguageService(lastFileExceededProgramSize?: string): void; + getProjectName(): string; + protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; + getExternalFiles(): SortedReadonlyArray; + getSourceFile(path: Path): ts.SourceFile | undefined; + close(): void; + private detachScriptInfoIfNotRoot; + isClosed(): boolean; + hasRoots(): boolean; + getRootFiles(): ts.server.NormalizedPath[]; + getRootScriptInfos(): ts.server.ScriptInfo[]; + getScriptInfos(): ScriptInfo[]; + getExcludedFiles(): readonly NormalizedPath[]; + getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): ts.server.NormalizedPath[]; + hasConfigFile(configFilePath: NormalizedPath): boolean; + containsScriptInfo(info: ScriptInfo): boolean; + containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; + isRoot(info: ScriptInfo): boolean; + addRoot(info: ScriptInfo, fileName?: NormalizedPath): void; + addMissingFileRoot(fileName: NormalizedPath): void; + removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; + registerFileUpdate(fileName: string): void; + markAsDirty(): void; + /** + * Updates set of files that contribute to this project + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph(): boolean; + protected removeExistingTypings(include: string[]): string[]; + private updateGraphWorker; + private detachScriptInfoFromProject; + private addMissingFileWatcher; + private isWatchedMissingFile; + private createGeneratedFileWatcher; + private isValidGeneratedFileWatcher; + private clearGeneratedFileWatch; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; + getScriptInfo(uncheckedFileName: string): ts.server.ScriptInfo | undefined; + filesToString(writeProjectFileNames: boolean): string; + setCompilerOptions(compilerOptions: CompilerOptions): void; + setTypeAcquisition(newTypeAcquisition: TypeAcquisition | undefined): void; + getTypeAcquisition(): ts.TypeAcquisition; + protected removeRoot(info: ScriptInfo): void; + protected enableGlobalPlugins(options: CompilerOptions): void; + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + refreshDiagnostics(): void; + } + /** + * If a file is opened and no tsconfig (or jsconfig) is found, + * the file and its imports/references are put into an InferredProject. + */ + class InferredProject extends Project { + private _isJsInferredProject; + toggleJsInferredProject(isJsInferredProject: boolean): void; + setCompilerOptions(options?: CompilerOptions): void; + /** this is canonical project root path */ + readonly projectRootPath: string | undefined; + addRoot(info: ScriptInfo): void; + removeRoot(info: ScriptInfo): void; + isProjectWithSingleRoot(): boolean; + close(): void; + getTypeAcquisition(): TypeAcquisition; + } + class AutoImportProviderProject extends Project { + private hostProject; + private rootFileNames; + isOrphan(): boolean; + updateGraph(): boolean; + hasRoots(): boolean; + markAsDirty(): void; + getScriptFileNames(): string[]; + getLanguageService(): never; + getHostForAutoImportProvider(): never; + getProjectReferences(): readonly ts.ProjectReference[] | undefined; + getTypeAcquisition(): TypeAcquisition; + } + /** + * If a file is opened, the server will look for a tsconfig (or jsconfig) + * and if successful create a ConfiguredProject for it. + * Otherwise it will create an InferredProject. + */ + class ConfiguredProject extends Project { + readonly canonicalConfigFilePath: NormalizedPath; + /** Ref count to the project when opened from external project */ + private externalProjectRefCount; + private projectReferences; + /** + * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph + * @returns: true if set of files in the project stays the same and false - otherwise. + */ + updateGraph(): boolean; + getConfigFilePath(): ts.server.NormalizedPath; + getProjectReferences(): readonly ProjectReference[] | undefined; + updateReferences(refs: readonly ProjectReference[] | undefined): void; + /** + * Get the errors that dont have any file name associated + */ + getGlobalProjectErrors(): readonly Diagnostic[]; + /** + * Get all the project errors + */ + getAllProjectErrors(): readonly Diagnostic[]; + setProjectErrors(projectErrors: Diagnostic[]): void; + close(): void; + getEffectiveTypeRoots(): string[]; + } + /** + * Project whose configuration is handled externally, such as in a '.csproj'. + * These are created only if a host explicitly calls `openExternalProject`. + */ + class ExternalProject extends Project { + externalProjectName: string; + compileOnSaveEnabled: boolean; + excludedFiles: readonly NormalizedPath[]; + updateGraph(): boolean; + getExcludedFiles(): readonly ts.server.NormalizedPath[]; + } + function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; + function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; + function convertWatchOptions(protocolOptions: protocol.ExternalProjectCompilerOptions, currentDirectory?: string): WatchOptionsAndErrors | undefined; + function convertTypeAcquisition(protocolOptions: protocol.InferredProjectCompilerOptions): TypeAcquisition | undefined; + function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; + function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; + const maxProgramSizeForNonTsFiles: number; + const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + interface ProjectsUpdatedInBackgroundEvent { + eventName: typeof ProjectsUpdatedInBackgroundEvent; + data: { + openFiles: string[]; + }; + } + const ProjectLoadingStartEvent = "projectLoadingStart"; + interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { + project: Project; + reason: string; + }; + } + const ProjectLoadingFinishEvent = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { + project: Project; + }; + } + const LargeFileReferencedEvent = "largeFileReferenced"; + interface LargeFileReferencedEvent { + eventName: typeof LargeFileReferencedEvent; + data: { + file: string; + fileSize: number; + maxFileSize: number; + }; + } + const ConfigFileDiagEvent = "configFileDiag"; + interface ConfigFileDiagEvent { + eventName: typeof ConfigFileDiagEvent; + data: { + triggerFile: string; + configFileName: string; + diagnostics: readonly Diagnostic[]; + }; + } + const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + interface ProjectLanguageServiceStateEvent { + eventName: typeof ProjectLanguageServiceStateEvent; + data: { + project: Project; + languageServiceEnabled: boolean; + }; + } + const ProjectInfoTelemetryEvent = "projectInfo"; + /** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */ + interface ProjectInfoTelemetryEvent { + readonly eventName: typeof ProjectInfoTelemetryEvent; + readonly data: ProjectInfoTelemetryEventData; + } + const OpenFileInfoTelemetryEvent = "openFileInfo"; + /** + * Info that we may send about a file that was just opened. + * Info about a file will only be sent once per session, even if the file changes in ways that might affect the info. + * Currently this is only sent for '.js' files. + */ + interface OpenFileInfoTelemetryEvent { + readonly eventName: typeof OpenFileInfoTelemetryEvent; + readonly data: OpenFileInfoTelemetryEventData; + } + interface ProjectInfoTelemetryEventData { + /** Cryptographically secure hash of project file location. */ + readonly projectId: string; + /** Count of file extensions seen in the project. */ + readonly fileStats: FileStats; + /** + * Any compiler options that might contain paths will be taken out. + * Enum compiler options will be converted to strings. + */ + readonly compilerOptions: CompilerOptions; + readonly extends: boolean | undefined; + readonly files: boolean | undefined; + readonly include: boolean | undefined; + readonly exclude: boolean | undefined; + readonly compileOnSave: boolean; + readonly typeAcquisition: ProjectInfoTypeAcquisitionData; + readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other"; + readonly projectType: "external" | "configured"; + readonly languageServiceEnabled: boolean; + /** TypeScript version used by the server. */ + readonly version: string; + } + interface OpenFileInfoTelemetryEventData { + readonly info: OpenFileInfo; + } + interface ProjectInfoTypeAcquisitionData { + readonly enable: boolean | undefined; + readonly include: boolean; + readonly exclude: boolean; + } + interface FileStats { + readonly js: number; + readonly jsSize?: number; + readonly jsx: number; + readonly jsxSize?: number; + readonly ts: number; + readonly tsSize?: number; + readonly tsx: number; + readonly tsxSize?: number; + readonly dts: number; + readonly dtsSize?: number; + readonly deferred: number; + readonly deferredSize?: number; + } + interface OpenFileInfo { + readonly checkJs: boolean; + } + type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; + interface SafeList { + [name: string]: { + match: RegExp; + exclude?: (string | number)[][]; + types?: string[]; + }; + } + interface TypesMapFile { + typesMap: SafeList; + simpleMap: { + [libName: string]: string; + }; + } + interface HostConfiguration { + formatCodeOptions: FormatCodeSettings; + preferences: protocol.UserPreferences; + hostInfo: string; + extraFileExtensions?: FileExtensionInfo[]; + watchOptions?: WatchOptions; + } + interface OpenConfiguredProjectResult { + configFileName?: NormalizedPath; + configFileErrors?: readonly Diagnostic[]; + } + interface ProjectServiceOptions { + host: ServerHost; + logger: Logger; + cancellationToken: HostCancellationToken; + useSingleInferredProject: boolean; + useInferredProjectPerProjectRoot: boolean; + typingsInstaller?: ITypingsInstaller; + eventHandler?: ProjectServiceEventHandler; + suppressDiagnosticEvents?: boolean; + throttleWaitMilliseconds?: number; + globalPlugins?: readonly string[]; + pluginProbeLocations?: readonly string[]; + allowLocalPluginLoads?: boolean; + typesMapLocation?: string; + serverMode?: LanguageServiceMode; + session: Session | undefined; + } + interface WatchOptionsAndErrors { + watchOptions: WatchOptions; + errors: Diagnostic[] | undefined; + } + class ProjectService { + private readonly nodeModulesWatchers; + /** + * Contains all the deleted script info's version information so that + * it does not reset when creating script info again + * (and could have potentially collided with version where contents mismatch) + */ + private readonly filenameToScriptInfoVersion; + private readonly allJsFilesForOpenFileTelemetry; + /** + * maps external project file name to list of config files that were the part of this project + */ + private readonly externalProjectToConfiguredProjectMap; + /** + * external projects (configuration and list of root files is not controlled by tsserver) + */ + readonly externalProjects: ExternalProject[]; + /** + * projects built from openFileRoots + */ + readonly inferredProjects: InferredProject[]; + /** + * projects specified by a tsconfig.json file + */ + readonly configuredProjects: Map; + /** + * Open files: with value being project root path, and key being Path of the file that is open + */ + readonly openFiles: Map; + /** + * Map of open files that are opened without complete path but have projectRoot as current directory + */ + private readonly openFilesWithNonRootedDiskPath; + private compilerOptionsForInferredProjects; + private compilerOptionsForInferredProjectsPerProjectRoot; + private watchOptionsForInferredProjects; + private watchOptionsForInferredProjectsPerProjectRoot; + private typeAcquisitionForInferredProjects; + private typeAcquisitionForInferredProjectsPerProjectRoot; + /** + * Project size for configured or external projects + */ + private readonly projectToSizeMap; + private readonly hostConfiguration; + private safelist; + private readonly legacySafelist; + private pendingProjectUpdates; + readonly currentDirectory: NormalizedPath; + readonly toCanonicalFileName: (f: string) => string; + readonly host: ServerHost; + readonly logger: Logger; + readonly cancellationToken: HostCancellationToken; + readonly useSingleInferredProject: boolean; + readonly useInferredProjectPerProjectRoot: boolean; + readonly typingsInstaller: ITypingsInstaller; + private readonly globalCacheLocationDirectoryPath; + readonly throttleWaitMilliseconds?: number; + private readonly eventHandler?; + private readonly suppressDiagnosticEvents?; + readonly globalPlugins: readonly string[]; + readonly pluginProbeLocations: readonly string[]; + readonly allowLocalPluginLoads: boolean; + readonly typesMapLocation: string | undefined; + readonly serverMode: LanguageServiceMode; + /** Tracks projects that we have already sent telemetry for. */ + private readonly seenProjects; + private performanceEventHandler?; + private pendingPluginEnablements?; + private currentPluginEnablementPromise?; + constructor(opts: ProjectServiceOptions); + toPath(fileName: string): Path; + private loadTypesMap; + updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; + private delayUpdateProjectGraph; + private delayUpdateProjectGraphs; + setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.InferredProjectCompilerOptions, projectRootPath?: string): void; + findProject(projectName: string): Project | undefined; + getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined; + private doEnsureDefaultProjectForFile; + getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined; + /** + * Ensures the project structures are upto date + * This means, + * - we go through all the projects and update them if they are dirty + * - if updates reflect some change in structure or there was pending request to ensure projects for open files + * ensure that each open script info has project + */ + private ensureProjectStructuresUptoDate; + getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; + getPreferences(file: NormalizedPath): protocol.UserPreferences; + getHostFormatCodeOptions(): FormatCodeSettings; + getHostPreferences(): protocol.UserPreferences; + private onSourceFileChanged; + private handleSourceMapProjects; + private delayUpdateSourceInfoProjects; + private delayUpdateProjectsOfScriptInfoPath; + private handleDeletedFile; + private removeProject; + private assignOrphanScriptInfosToInferredProject; + /** + * Remove this file from the set of open, non-configured files. + * @param info The file that has been closed or newly configured + */ + private closeOpenFile; + private deleteScriptInfo; + private configFileExists; + /** + * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project + */ + private configFileExistenceImpactsRootOfInferredProject; + /** + * This is called on file close, so that we stop watching the config file for this script info + */ + private stopWatchingConfigFilesForClosedScriptInfo; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + */ + private forEachConfigFileLocation; + /** + * This function tries to search for a tsconfig.json for the given file. + * This is different from the method the compiler uses because + * the compiler can assume it will always start searching in the + * current directory (the directory in which tsc was invoked). + * The server must start searching from the directory containing + * the newly opened file. + * If script info is passed in, it is asserted to be open script info + * otherwise just file name + */ + private getConfigFileNameForFile; + private printProjects; + private getConfiguredProjectByCanonicalConfigFilePath; + private findExternalProjectByProjectName; + /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ + private getFilenameForExceededTotalSizeLimitForNonTsFiles; + private createExternalProject; + private addFilesToNonInferredProject; + private updateNonInferredProjectFiles; + private updateRootAndOptionsOfNonInferredProject; + private sendConfigFileDiagEvent; + private getOrCreateInferredProjectForProjectRootPathIfEnabled; + private getOrCreateSingleInferredProjectIfEnabled; + private getOrCreateSingleInferredWithoutProjectRoot; + private createInferredProject; + getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; + private watchClosedScriptInfo; + private createNodeModulesWatcher; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; + private stopWatchingScriptInfo; + private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; + private getOrCreateScriptInfoOpenedByClientForNormalizedPath; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { + fileExists(path: string): boolean; + }): ScriptInfo | undefined; + private getOrCreateScriptInfoWorker; + /** + * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred + */ + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; + getScriptInfoForPath(fileName: Path): ScriptInfo | undefined; + private addSourceInfoToSourceMap; + private addMissingSourceMapFile; + setHostConfiguration(args: protocol.ConfigureRequestArguments): void; + closeLog(): void; + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ + reloadProjects(): void; + /** + * This function goes through all the openFiles and tries to file the config file for them. + * If the config file is found and it refers to existing project, it reloads it either immediately + * or schedules it for reload depending on delayReload option + * If there is no existing project it just opens the configured project for the config file + * reloadForInfo provides a way to filter out files to reload configured project for + */ + private reloadConfiguredProjectForFiles; + /** + * Remove the root of inferred project if script info is part of another project + */ + private removeRootOfInferredProjectIfNowPartOfOtherProject; + /** + * This function is to update the project structure for every inferred project. + * It is called on the premise that all the configured projects are + * up to date. + * This will go through open files and assign them to inferred project if open file is not part of any other project + * After that all the inferred project graphs are updated + */ + private ensureProjectForOpenFiles; + /** + * Open file whose contents is managed by the client + * @param filename is absolute pathname + * @param fileContent is a known version of the file content that is more up to date than the one on disk + */ + openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; + private findExternalProjectContainingOpenScriptInfo; + private getOrCreateOpenScriptInfo; + private assignProjectToOpenedScriptInfo; + private createAncestorProjects; + private ensureProjectChildren; + private cleanupAfterOpeningFile; + openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; + private removeOrphanConfiguredProjects; + private removeOrphanScriptInfos; + private telemetryOnOpenFile; + /** + * Close file whose contents is managed by the client + * @param filename is absolute pathname + */ + closeClientFile(uncheckedFileName: string): void; + private collectChanges; + private closeConfiguredProjectReferencedFromExternalProject; + closeExternalProject(uncheckedFileName: string): void; + openExternalProjects(projects: protocol.ExternalProject[]): void; + /** Makes a filename safe to insert in a RegExp */ + private static readonly filenameEscapeRegexp; + private static escapeFilenameForRegex; + resetSafeList(): void; + applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; + openExternalProject(proj: protocol.ExternalProject): void; + hasDeferredExtension(): boolean; + private enableRequestedPluginsAsync; + private enableRequestedPluginsWorker; + private enableRequestedPluginsForProjectAsync; + configurePlugin(args: protocol.ConfigurePluginRequestArguments): void; + } + function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: BufferEncoding) => number, newLine: string): string; + interface ServerCancellationToken extends HostCancellationToken { + setRequest(requestId: number): void; + resetRequest(requestId: number): void; + } + const nullCancellationToken: ServerCancellationToken; + interface PendingErrorCheck { + fileName: NormalizedPath; + project: Project; + } + /** @deprecated use ts.server.protocol.CommandTypes */ + type CommandNames = protocol.CommandTypes; + /** @deprecated use ts.server.protocol.CommandTypes */ + const CommandNames: any; + type Event = (body: T, eventName: string) => void; + interface EventSender { + event: Event; + } + interface SessionOptions { + host: ServerHost; + cancellationToken: ServerCancellationToken; + useSingleInferredProject: boolean; + useInferredProjectPerProjectRoot: boolean; + typingsInstaller?: ITypingsInstaller; + byteLength: (buf: string, encoding?: BufferEncoding) => number; + hrtime: (start?: [ + number, + number + ]) => [ + number, + number + ]; + logger: Logger; + /** + * If falsy, all events are suppressed. + */ + canUseEvents: boolean; + eventHandler?: ProjectServiceEventHandler; + /** Has no effect if eventHandler is also specified. */ + suppressDiagnosticEvents?: boolean; + serverMode?: LanguageServiceMode; + throttleWaitMilliseconds?: number; + noGetErrOnBackgroundUpdate?: boolean; + globalPlugins?: readonly string[]; + pluginProbeLocations?: readonly string[]; + allowLocalPluginLoads?: boolean; + typesMapLocation?: string; + } + class Session implements EventSender { + private readonly gcTimer; + protected projectService: ProjectService; + private changeSeq; + private performanceData; + private currentRequestId; + private errorCheck; + protected host: ServerHost; + private readonly cancellationToken; + protected readonly typingsInstaller: ITypingsInstaller; + protected byteLength: (buf: string, encoding?: BufferEncoding) => number; + private hrtime; + protected logger: Logger; + protected canUseEvents: boolean; + private suppressDiagnosticEvents?; + private eventHandler; + private readonly noGetErrOnBackgroundUpdate?; + constructor(opts: SessionOptions); + private sendRequestCompletedEvent; + private addPerformanceData; + private performanceEventHandler; + private defaultEventHandler; + private projectsUpdatedInBackgroundEvent; + logError(err: Error, cmd: string): void; + private logErrorWorker; + send(msg: protocol.Message): void; + protected writeMessage(msg: protocol.Message): void; + event(body: T, eventName: string): void; + private semanticCheck; + private syntacticCheck; + private suggestionCheck; + private sendDiagnosticsEvent; + /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ + private updateErrorCheck; + private cleanProjects; + private cleanup; + private getEncodedSyntacticClassifications; + private getEncodedSemanticClassifications; + private getProject; + private getConfigFileAndProject; + private getConfigFileDiagnostics; + private convertToDiagnosticsWithLinePositionFromDiagnosticFile; + private getCompilerOptionsDiagnostics; + private convertToDiagnosticsWithLinePosition; + private getDiagnosticsWorker; + private getDefinition; + private mapDefinitionInfoLocations; + private getDefinitionAndBoundSpan; + private findSourceDefinition; + private getEmitOutput; + private mapJSDocTagInfo; + private mapDisplayParts; + private mapSignatureHelpItems; + private mapDefinitionInfo; + private static mapToOriginalLocation; + private toFileSpan; + private toFileSpanWithContext; + private getTypeDefinition; + private mapImplementationLocations; + private getImplementation; + private getSyntacticDiagnosticsSync; + private getSemanticDiagnosticsSync; + private getSuggestionDiagnosticsSync; + private getJsxClosingTag; + private getLinkedEditingRange; + private getDocumentHighlights; + private provideInlayHints; + private setCompilerOptionsForInferredProjects; + private getProjectInfo; + private getProjectInfoWorker; + private getRenameInfo; + private getProjects; + private getDefaultProject; + private getRenameLocations; + private mapRenameInfo; + private toSpanGroups; + private getReferences; + private getFileReferences; + /** + * @param fileName is the name of the file to be opened + * @param fileContent is a version of the file content that is known to be more up to date than the one on disk + */ + private openClientFile; + private getPosition; + private getPositionInFile; + private getFileAndProject; + private getFileAndLanguageServiceForSyntacticOperation; + private getFileAndProjectWorker; + private getOutliningSpans; + private getTodoComments; + private getDocCommentTemplate; + private getSpanOfEnclosingComment; + private getIndentation; + private getBreakpointStatement; + private getNameOrDottedNameSpan; + private isValidBraceCompletion; + private getQuickInfoWorker; + private getFormattingEditsForRange; + private getFormattingEditsForRangeFull; + private getFormattingEditsForDocumentFull; + private getFormattingEditsAfterKeystrokeFull; + private getFormattingEditsAfterKeystroke; + private getCompletions; + private getCompletionEntryDetails; + private getCompileOnSaveAffectedFileList; + private emitFile; + private getSignatureHelpItems; + private toPendingErrorCheck; + private getDiagnostics; + private change; + private reload; + private saveToTmp; + private closeClientFile; + private mapLocationNavigationBarItems; + private getNavigationBarItems; + private toLocationNavigationTree; + private getNavigationTree; + private getNavigateToItems; + private getFullNavigateToItems; + private getSupportedCodeFixes; + private isLocation; + private extractPositionOrRange; + private getRange; + private getApplicableRefactors; + private getEditsForRefactor; + private getMoveToRefactoringFileSuggestions; + private organizeImports; + private getEditsForFileRename; + private getCodeFixes; + private getCombinedCodeFix; + private applyCodeActionCommand; + private getStartAndEndPosition; + private mapCodeAction; + private mapCodeFixAction; + private mapTextChangesToCodeEdits; + private mapTextChangeToCodeEdit; + private convertTextChangeToCodeEdit; + private getBraceMatching; + private getDiagnosticsForProject; + private configurePlugin; + private getSmartSelectionRange; + private toggleLineComment; + private toggleMultilineComment; + private commentSelection; + private uncommentSelection; + private mapSelectionRange; + private getScriptInfoFromProjectService; + private toProtocolCallHierarchyItem; + private toProtocolCallHierarchyIncomingCall; + private toProtocolCallHierarchyOutgoingCall; + private prepareCallHierarchy; + private provideCallHierarchyIncomingCalls; + private provideCallHierarchyOutgoingCalls; + getCanonicalFileName(fileName: string): string; + exit(): void; + private notRequired; + private requiredResponse; + private handlers; + addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; + private setCurrentRequest; + private resetCurrentRequest; + executeWithRequestId(requestId: number, f: () => T): T; + executeCommand(request: protocol.Request): HandlerResponse; + onMessage(message: TMessage): void; + protected parseMessage(message: TMessage): protocol.Request; + protected toStringMessage(message: TMessage): string; + private getFormatOptions; + private getPreferences; + private getHostFormatOptions; + private getHostPreferences; + } + interface HandlerResponse { + response?: {}; + responseRequired?: boolean; + } + } const versionMajorMinor = "5.3"; /** The version of the TypeScript compiler release */ const version: string; @@ -5898,90 +9958,6 @@ declare namespace ts { readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; } } - namespace server { - type ActionSet = "action::set"; - type ActionInvalidate = "action::invalidate"; - type ActionPackageInstalled = "action::packageInstalled"; - type EventTypesRegistry = "event::typesRegistry"; - type EventBeginInstallTypes = "event::beginInstallTypes"; - type EventEndInstallTypes = "event::endInstallTypes"; - type EventInitializationFailed = "event::initializationFailed"; - type ActionWatchTypingLocations = "action::watchTypingLocations"; - interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed | ActionWatchTypingLocations; - } - interface TypingInstallerRequestWithProjectName { - readonly projectName: string; - } - interface DiscoverTypings extends TypingInstallerRequestWithProjectName { - readonly fileNames: string[]; - readonly projectRootPath: Path; - readonly compilerOptions: CompilerOptions; - readonly typeAcquisition: TypeAcquisition; - readonly unresolvedImports: SortedReadonlyArray; - readonly cachePath?: string; - readonly kind: "discover"; - } - interface CloseProject extends TypingInstallerRequestWithProjectName { - readonly kind: "closeProject"; - } - interface TypesRegistryRequest { - readonly kind: "typesRegistry"; - } - interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { - readonly kind: "installPackage"; - readonly fileName: Path; - readonly packageName: string; - readonly projectRootPath: Path; - } - interface PackageInstalledResponse extends ProjectResponse { - readonly kind: ActionPackageInstalled; - readonly success: boolean; - readonly message: string; - } - interface InitializationFailedResponse extends TypingInstallerResponse { - readonly kind: EventInitializationFailed; - readonly message: string; - readonly stack?: string; - } - interface ProjectResponse extends TypingInstallerResponse { - readonly projectName: string; - } - interface InvalidateCachedTypings extends ProjectResponse { - readonly kind: ActionInvalidate; - } - interface InstallTypes extends ProjectResponse { - readonly kind: EventBeginInstallTypes | EventEndInstallTypes; - readonly eventId: number; - readonly typingsInstallerVersion: string; - readonly packagesToInstall: readonly string[]; - } - interface BeginInstallTypes extends InstallTypes { - readonly kind: EventBeginInstallTypes; - } - interface EndInstallTypes extends InstallTypes { - readonly kind: EventEndInstallTypes; - readonly installSuccess: boolean; - } - interface InstallTypingHost extends JsTyping.TypingResolutionHost { - useCaseSensitiveFileNames: boolean; - writeFile(path: string, content: string): void; - createDirectory(path: string): void; - getCurrentDirectory?(): string; - } - interface SetTypings extends ProjectResponse { - readonly typeAcquisition: TypeAcquisition; - readonly compilerOptions: CompilerOptions; - readonly typings: string[]; - readonly unresolvedImports: SortedReadonlyArray; - readonly kind: ActionSet; - } - interface WatchTypingLocations extends ProjectResponse { - /** if files is undefined, retain same set of watchers */ - readonly files: readonly string[] | undefined; - readonly kind: ActionWatchTypingLocations; - } - } function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; /** * Represents an immutable snapshot of a script at a specified time.Once acquired, the From 38553696e25eedf9ce68812e592f37302054d88c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Mon, 14 Aug 2023 22:13:32 +0200 Subject: [PATCH 10/81] Fixed `hasInvalidEscape` implementation (#55373) Co-authored-by: Damien Engels --- src/compiler/utilities.ts | 9 +++++++-- ...nvalidTaggedTemplateEscapeSequences(target=es2015).js | 8 ++++---- .../taggedTemplateStringsHexadecimalEscapesES6.js | 6 +----- .../taggedTemplateStringsWithUnicodeEscapesES6.js | 6 +----- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 638d76f79b53e..75e1f55abc6f6 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -509,6 +509,7 @@ import { TaggedTemplateExpression, TemplateLiteral, TemplateLiteralLikeNode, + TemplateLiteralToken, TemplateLiteralTypeSpan, TemplateSpan, TextRange, @@ -5801,11 +5802,15 @@ function escapeTemplateSubstitution(str: string): string { return str.replace(templateSubstitutionRegExp, "\\${"); } +function containsInvalidEscapeFlag(node: TemplateLiteralToken): boolean { + return !!((node.templateFlags || 0) & TokenFlags.ContainsInvalidEscape); +} + /** @internal */ export function hasInvalidEscape(template: TemplateLiteral): boolean { return template && !!(isNoSubstitutionTemplateLiteral(template) - ? template.templateFlags - : (template.head.templateFlags || some(template.templateSpans, span => !!span.literal.templateFlags))); + ? containsInvalidEscapeFlag(template) + : (containsInvalidEscapeFlag(template.head) || some(template.templateSpans, span => containsInvalidEscapeFlag(span.literal)))); } // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, diff --git a/tests/baselines/reference/invalidTaggedTemplateEscapeSequences(target=es2015).js b/tests/baselines/reference/invalidTaggedTemplateEscapeSequences(target=es2015).js index b70c41deae109..ca5f18a639296 100644 --- a/tests/baselines/reference/invalidTaggedTemplateEscapeSequences(target=es2015).js +++ b/tests/baselines/reference/invalidTaggedTemplateEscapeSequences(target=es2015).js @@ -46,11 +46,11 @@ const a3 = tag(__makeTemplateObject(["", void 0], ["", "\\u"]), 100); // \\u const a4 = tag(__makeTemplateObject(["", void 0], ["", "\\u0"]), 100); // \\u0 const a5 = tag(__makeTemplateObject(["", void 0], ["", "\\u00"]), 100); // \\u00 const a6 = tag(__makeTemplateObject(["", void 0], ["", "\\u000"]), 100); // \\u000 -const a7 = tag(__makeTemplateObject(["", "\0"], ["", "\\u0000"]), 100); // \u0000 +const a7 = tag `${100}\u0000`; // \u0000 const a8 = tag(__makeTemplateObject(["", void 0], ["", "\\u{"]), 100); // \\u{ -const a9 = tag(__makeTemplateObject(["", "\uDBFF\uDFFF"], ["", "\\u{10FFFF}"]), 100); // \\u{10FFFF +const a9 = tag `${100}\u{10FFFF}`; // \\u{10FFFF const a10 = tag(__makeTemplateObject(["", void 0], ["", "\\u{1f622"]), 100); // \\u{1f622 -const a11 = tag(__makeTemplateObject(["", "\uD83D\uDE22"], ["", "\\u{1f622}"]), 100); // \u{1f622} +const a11 = tag `${100}\u{1f622}`; // \u{1f622} const a12 = tag(__makeTemplateObject(["", void 0], ["", "\\x"]), 100); // \\x const a13 = tag(__makeTemplateObject(["", void 0], ["", "\\x0"]), 100); // \\x0 -const a14 = tag(__makeTemplateObject(["", "\0"], ["", "\\x00"]), 100); // \x00 +const a14 = tag `${100}\x00`; // \x00 diff --git a/tests/baselines/reference/taggedTemplateStringsHexadecimalEscapesES6.js b/tests/baselines/reference/taggedTemplateStringsHexadecimalEscapesES6.js index 3faabd401f504..5a31708de558f 100644 --- a/tests/baselines/reference/taggedTemplateStringsHexadecimalEscapesES6.js +++ b/tests/baselines/reference/taggedTemplateStringsHexadecimalEscapesES6.js @@ -7,10 +7,6 @@ function f(...args: any[]) { f `\x0D${ "Interrupted CRLF" }\x0A`; //// [taggedTemplateStringsHexadecimalEscapesES6.js] -var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; function f(...args) { } -f(__makeTemplateObject(["\r", "\n"], ["\\x0D", "\\x0A"]), "Interrupted CRLF"); +f `\x0D${"Interrupted CRLF"}\x0A`; diff --git a/tests/baselines/reference/taggedTemplateStringsWithUnicodeEscapesES6.js b/tests/baselines/reference/taggedTemplateStringsWithUnicodeEscapesES6.js index 4bec587b0a84a..c75c5f28ca77c 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithUnicodeEscapesES6.js +++ b/tests/baselines/reference/taggedTemplateStringsWithUnicodeEscapesES6.js @@ -7,10 +7,6 @@ function f(...args: any[]) { f `'\u{1f4a9}'${ " should be converted to " }'\uD83D\uDCA9'`; //// [taggedTemplateStringsWithUnicodeEscapesES6.js] -var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; function f(...args) { } -f(__makeTemplateObject(["'\uD83D\uDCA9'", "'\uD83D\uDCA9'"], ["'\\u{1f4a9}'", "'\\uD83D\\uDCA9'"]), " should be converted to "); +f `'\u{1f4a9}'${" should be converted to "}'\uD83D\uDCA9'`; From 16dab6d5d64dce76927a16e70416bb28d5e3d4df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Mon, 14 Aug 2023 22:13:42 +0200 Subject: [PATCH 11/81] Preserve input key style of computed properties in declaration emit (#55298) --- src/compiler/checker.ts | 9 ++++- ...declarationEmitPropertyNumericStringKey.js | 40 +++++++++++++++++++ ...rationEmitPropertyNumericStringKey.symbols | 31 ++++++++++++++ ...larationEmitPropertyNumericStringKey.types | 39 ++++++++++++++++++ ...ationEmitStringEnumUsedInNonlocalSpread.js | 4 +- ...onEmitStringEnumUsedInNonlocalSpread.types | 6 +-- ...eObjectLiteralProperty_computedName1.types | 4 +- .../literalsInComputedProperties1.types | 12 +++--- ...declarationEmitPropertyNumericStringKey.ts | 13 ++++++ 9 files changed, 144 insertions(+), 14 deletions(-) create mode 100644 tests/baselines/reference/declarationEmitPropertyNumericStringKey.js create mode 100644 tests/baselines/reference/declarationEmitPropertyNumericStringKey.symbols create mode 100644 tests/baselines/reference/declarationEmitPropertyNumericStringKey.types create mode 100644 tests/cases/compiler/declarationEmitPropertyNumericStringKey.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c43435bc001c5..33441d618d79a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8082,7 +8082,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isStringNamed(d: Declaration) { const name = getNameOfDeclaration(d); - return !!name && isStringLiteral(name); + if (!name) { + return false; + } + if (isComputedPropertyName(name)) { + const type = checkExpression(name.expression); + return !!(type.flags & TypeFlags.StringLike); + } + return isStringLiteral(name); } function isSingleQuotedStringNamed(d: Declaration) { diff --git a/tests/baselines/reference/declarationEmitPropertyNumericStringKey.js b/tests/baselines/reference/declarationEmitPropertyNumericStringKey.js new file mode 100644 index 0000000000000..2c1a4c01da182 --- /dev/null +++ b/tests/baselines/reference/declarationEmitPropertyNumericStringKey.js @@ -0,0 +1,40 @@ +//// [tests/cases/compiler/declarationEmitPropertyNumericStringKey.ts] //// + +//// [declarationEmitPropertyNumericStringKey.ts] +// https://github.com/microsoft/TypeScript/issues/55292 + +const STATUS = { + ["404"]: "not found", +} as const; + +const hundredStr = "100"; +const obj = { [hundredStr]: "foo" }; + +const hundredNum = 100; +const obj2 = { [hundredNum]: "bar" }; + + +//// [declarationEmitPropertyNumericStringKey.js] +// https://github.com/microsoft/TypeScript/issues/55292 +var _a, _b, _c; +var STATUS = (_a = {}, + _a["404"] = "not found", + _a); +var hundredStr = "100"; +var obj = (_b = {}, _b[hundredStr] = "foo", _b); +var hundredNum = 100; +var obj2 = (_c = {}, _c[hundredNum] = "bar", _c); + + +//// [declarationEmitPropertyNumericStringKey.d.ts] +declare const STATUS: { + readonly "404": "not found"; +}; +declare const hundredStr = "100"; +declare const obj: { + "100": string; +}; +declare const hundredNum = 100; +declare const obj2: { + 100: string; +}; diff --git a/tests/baselines/reference/declarationEmitPropertyNumericStringKey.symbols b/tests/baselines/reference/declarationEmitPropertyNumericStringKey.symbols new file mode 100644 index 0000000000000..99d9687cb226b --- /dev/null +++ b/tests/baselines/reference/declarationEmitPropertyNumericStringKey.symbols @@ -0,0 +1,31 @@ +//// [tests/cases/compiler/declarationEmitPropertyNumericStringKey.ts] //// + +=== declarationEmitPropertyNumericStringKey.ts === +// https://github.com/microsoft/TypeScript/issues/55292 + +const STATUS = { +>STATUS : Symbol(STATUS, Decl(declarationEmitPropertyNumericStringKey.ts, 2, 5)) + + ["404"]: "not found", +>["404"] : Symbol(["404"], Decl(declarationEmitPropertyNumericStringKey.ts, 2, 16)) +>"404" : Symbol(["404"], Decl(declarationEmitPropertyNumericStringKey.ts, 2, 16)) + +} as const; +>const : Symbol(const) + +const hundredStr = "100"; +>hundredStr : Symbol(hundredStr, Decl(declarationEmitPropertyNumericStringKey.ts, 6, 5)) + +const obj = { [hundredStr]: "foo" }; +>obj : Symbol(obj, Decl(declarationEmitPropertyNumericStringKey.ts, 7, 5)) +>[hundredStr] : Symbol([hundredStr], Decl(declarationEmitPropertyNumericStringKey.ts, 7, 13)) +>hundredStr : Symbol(hundredStr, Decl(declarationEmitPropertyNumericStringKey.ts, 6, 5)) + +const hundredNum = 100; +>hundredNum : Symbol(hundredNum, Decl(declarationEmitPropertyNumericStringKey.ts, 9, 5)) + +const obj2 = { [hundredNum]: "bar" }; +>obj2 : Symbol(obj2, Decl(declarationEmitPropertyNumericStringKey.ts, 10, 5)) +>[hundredNum] : Symbol([hundredNum], Decl(declarationEmitPropertyNumericStringKey.ts, 10, 14)) +>hundredNum : Symbol(hundredNum, Decl(declarationEmitPropertyNumericStringKey.ts, 9, 5)) + diff --git a/tests/baselines/reference/declarationEmitPropertyNumericStringKey.types b/tests/baselines/reference/declarationEmitPropertyNumericStringKey.types new file mode 100644 index 0000000000000..2d4d8531b158d --- /dev/null +++ b/tests/baselines/reference/declarationEmitPropertyNumericStringKey.types @@ -0,0 +1,39 @@ +//// [tests/cases/compiler/declarationEmitPropertyNumericStringKey.ts] //// + +=== declarationEmitPropertyNumericStringKey.ts === +// https://github.com/microsoft/TypeScript/issues/55292 + +const STATUS = { +>STATUS : { readonly "404": "not found"; } +>{ ["404"]: "not found",} as const : { readonly "404": "not found"; } +>{ ["404"]: "not found",} : { readonly "404": "not found"; } + + ["404"]: "not found", +>["404"] : "not found" +>"404" : "404" +>"not found" : "not found" + +} as const; + +const hundredStr = "100"; +>hundredStr : "100" +>"100" : "100" + +const obj = { [hundredStr]: "foo" }; +>obj : { "100": string; } +>{ [hundredStr]: "foo" } : { "100": string; } +>[hundredStr] : string +>hundredStr : "100" +>"foo" : "foo" + +const hundredNum = 100; +>hundredNum : 100 +>100 : 100 + +const obj2 = { [hundredNum]: "bar" }; +>obj2 : { 100: string; } +>{ [hundredNum]: "bar" } : { 100: string; } +>[hundredNum] : string +>hundredNum : 100 +>"bar" : "bar" + diff --git a/tests/baselines/reference/declarationEmitStringEnumUsedInNonlocalSpread.js b/tests/baselines/reference/declarationEmitStringEnumUsedInNonlocalSpread.js index b303c32b198ed..b2cce43877394 100644 --- a/tests/baselines/reference/declarationEmitStringEnumUsedInNonlocalSpread.js +++ b/tests/baselines/reference/declarationEmitStringEnumUsedInNonlocalSpread.js @@ -109,7 +109,7 @@ import { A } from './class'; export declare class B extends A { getA(): { a: string; - 123123: string; - 12312312312: string; + "123123": string; + "12312312312": string; }; } diff --git a/tests/baselines/reference/declarationEmitStringEnumUsedInNonlocalSpread.types b/tests/baselines/reference/declarationEmitStringEnumUsedInNonlocalSpread.types index 784334b5c95fe..031089bf3b9a2 100644 --- a/tests/baselines/reference/declarationEmitStringEnumUsedInNonlocalSpread.types +++ b/tests/baselines/reference/declarationEmitStringEnumUsedInNonlocalSpread.types @@ -34,7 +34,7 @@ export class A { >getA : () => ITest return { ->{ [TestEnum.Test1]: '123', [TestEnum.Test2]: '123', } : { 123123: string; 12312312312: string; } +>{ [TestEnum.Test1]: '123', [TestEnum.Test2]: '123', } : { "123123": string; "12312312312": string; } [TestEnum.Test1]: '123', >[TestEnum.Test1] : string @@ -62,10 +62,10 @@ export class B extends A { >A : A getA() { // TS4053 error ->getA : () => { a: string; 123123: string; 12312312312: string; } +>getA : () => { a: string; "123123": string; "12312312312": string; } return { ->{ ...super.getA(), a: '123', } : { a: string; 123123: string; 12312312312: string; } +>{ ...super.getA(), a: '123', } : { a: string; "123123": string; "12312312312": string; } ...super.getA(), >super.getA() : import("class").ITest diff --git a/tests/baselines/reference/duplicateObjectLiteralProperty_computedName1.types b/tests/baselines/reference/duplicateObjectLiteralProperty_computedName1.types index fd94a2b9e90dd..7c3f3e50cd320 100644 --- a/tests/baselines/reference/duplicateObjectLiteralProperty_computedName1.types +++ b/tests/baselines/reference/duplicateObjectLiteralProperty_computedName1.types @@ -90,8 +90,8 @@ const t6 = { } const t7 = { ->t7 : { [-1]: number; } ->{ "-1": 1, ["-1"]: 0 // duplicate} : { [-1]: number; } +>t7 : { "-1": number; } +>{ "-1": 1, ["-1"]: 0 // duplicate} : { "-1": number; } "-1": 1, >"-1" : number diff --git a/tests/baselines/reference/literalsInComputedProperties1.types b/tests/baselines/reference/literalsInComputedProperties1.types index 869ce9f56d884..cd04bb0c8cc4b 100644 --- a/tests/baselines/reference/literalsInComputedProperties1.types +++ b/tests/baselines/reference/literalsInComputedProperties1.types @@ -2,8 +2,8 @@ === literalsInComputedProperties1.ts === let x = { ->x : { 1: number; 2: number; "3": number; 4: number; } ->{ 1:1, [2]:1, "3":1, ["4"]:1} : { 1: number; 2: number; "3": number; 4: number; } +>x : { 1: number; 2: number; "3": number; "4": number; } +>{ 1:1, [2]:1, "3":1, ["4"]:1} : { 1: number; 2: number; "3": number; "4": number; } 1:1, >1 : number @@ -27,7 +27,7 @@ x[1].toExponential(); >x[1].toExponential() : string >x[1].toExponential : (fractionDigits?: number) => string >x[1] : number ->x : { 1: number; 2: number; "3": number; 4: number; } +>x : { 1: number; 2: number; "3": number; "4": number; } >1 : 1 >toExponential : (fractionDigits?: number) => string @@ -35,7 +35,7 @@ x[2].toExponential(); >x[2].toExponential() : string >x[2].toExponential : (fractionDigits?: number) => string >x[2] : number ->x : { 1: number; 2: number; "3": number; 4: number; } +>x : { 1: number; 2: number; "3": number; "4": number; } >2 : 2 >toExponential : (fractionDigits?: number) => string @@ -43,7 +43,7 @@ x[3].toExponential(); >x[3].toExponential() : string >x[3].toExponential : (fractionDigits?: number) => string >x[3] : number ->x : { 1: number; 2: number; "3": number; 4: number; } +>x : { 1: number; 2: number; "3": number; "4": number; } >3 : 3 >toExponential : (fractionDigits?: number) => string @@ -51,7 +51,7 @@ x[4].toExponential(); >x[4].toExponential() : string >x[4].toExponential : (fractionDigits?: number) => string >x[4] : number ->x : { 1: number; 2: number; "3": number; 4: number; } +>x : { 1: number; 2: number; "3": number; "4": number; } >4 : 4 >toExponential : (fractionDigits?: number) => string diff --git a/tests/cases/compiler/declarationEmitPropertyNumericStringKey.ts b/tests/cases/compiler/declarationEmitPropertyNumericStringKey.ts new file mode 100644 index 0000000000000..b5692f9d4cc56 --- /dev/null +++ b/tests/cases/compiler/declarationEmitPropertyNumericStringKey.ts @@ -0,0 +1,13 @@ +// @declaration: true + +// https://github.com/microsoft/TypeScript/issues/55292 + +const STATUS = { + ["404"]: "not found", +} as const; + +const hundredStr = "100"; +const obj = { [hundredStr]: "foo" }; + +const hundredNum = 100; +const obj2 = { [hundredNum]: "bar" }; From f5e73d7e605d931f605ad11598a25cdf140a0894 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Mon, 14 Aug 2023 23:03:31 +0200 Subject: [PATCH 12/81] Add additional information section to the bug report template (#55360) --- .github/ISSUE_TEMPLATE/bug_report.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index c21d5edd1fd6c..ac2e1f6bd02c5 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -97,3 +97,7 @@ body: description: What you expected to happen instead, and why validations: required: true + - type: textarea + id: additional_info + attributes: + label: Additional information about the issue From 05cb53ec0b7c7591a5f9f4f105e084001b8d49b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maria=20Jos=C3=A9=20Solano?= Date: Mon, 14 Aug 2023 14:21:00 -0700 Subject: [PATCH 13/81] Organize/consolidate inlay hint tests (#55332) --- ...ine => inlayHintsEnumMemberValue.baseline} | 0 ...inlayHintsFunctionParameterTypes1.baseline | 80 +++ ...nlayHintsFunctionParameterTypes2.baseline} | 0 ...inlayHintsFunctionParameterTypes3.baseline | 17 + ...nlayHintsFunctionParameterTypes4.baseline} | 0 ...aseline => inlayHintsImportType1.baseline} | 0 ...aseline => inlayHintsImportType2.baseline} | 0 ...nlayHintsInteractiveOverloadCall.baseline} | 108 ++-- ...layHintsInteractiveParameterNames.baseline | 461 ++++++++++++++++++ ...InteractiveParameterNamesInSpan1.baseline} | 12 +- ...InteractiveParameterNamesInSpan2.baseline} | 12 +- ...activeParameterNamesWithComments.baseline} | 55 ++- ...yHintsInteractiveRestParameters1.baseline} | 76 +-- ...ayHintsInteractiveRestParameters2.baseline | 241 +++++++++ .../inlayHintsInteractiveReturnType.baseline | 205 ++++++++ ...nlayHintsInteractiveWithClosures.baseline} | 42 +- ...nlayHintsInterativeAnyParameter1.baseline} | 10 +- ...nlayHintsInterativeAnyParameter2.baseline} | 26 +- ...=> inlayHintsJsDocParameterNames.baseline} | 0 ...baseline => inlayHintsMultifile1.baseline} | 0 ...ntsNoHintWhenArgumentMatchesName.baseline} | 0 ...ne => inlayHintsNoParameterHints.baseline} | 0 ...=> inlayHintsNoVariableTypeHints.baseline} | 0 .../reference/inlayHintsOverloadCall.baseline | 89 ++++ .../inlayHintsParameterNames.baseline | 188 +++++++ .../inlayHintsParameterNamesInSpan1.baseline | 53 ++ .../inlayHintsParameterNamesInSpan2.baseline | 53 ++ ...> inlayHintsPropertyDeclarations.baseline} | 0 .../inlayHintsRestParameters1.baseline | 53 ++ .../inlayHintsRestParameters2.baseline | 98 ++++ .../reference/inlayHintsReturnType.baseline | 44 ++ .../reference/inlayHintsShouldWork1.baseline | 43 -- .../reference/inlayHintsShouldWork11.baseline | 43 -- .../reference/inlayHintsShouldWork12.baseline | 43 -- .../reference/inlayHintsShouldWork13.baseline | 21 - .../reference/inlayHintsShouldWork2.baseline | 21 - .../reference/inlayHintsShouldWork21.baseline | 1 - .../reference/inlayHintsShouldWork22.baseline | 1 - .../reference/inlayHintsShouldWork24.baseline | 17 - .../reference/inlayHintsShouldWork25.baseline | 8 - .../reference/inlayHintsShouldWork26.baseline | 8 - .../reference/inlayHintsShouldWork27.baseline | 17 - .../reference/inlayHintsShouldWork28.baseline | 8 - .../reference/inlayHintsShouldWork29.baseline | 35 -- .../reference/inlayHintsShouldWork3.baseline | 43 -- .../reference/inlayHintsShouldWork30.baseline | 8 - .../reference/inlayHintsShouldWork31.baseline | 8 - .../reference/inlayHintsShouldWork36.baseline | 43 -- .../reference/inlayHintsShouldWork38.baseline | 8 - .../reference/inlayHintsShouldWork39.baseline | 1 - .../reference/inlayHintsShouldWork4.baseline | 65 --- .../reference/inlayHintsShouldWork40.baseline | 8 - .../reference/inlayHintsShouldWork41.baseline | 8 - .../reference/inlayHintsShouldWork42.baseline | 8 - .../reference/inlayHintsShouldWork43.baseline | 8 - .../reference/inlayHintsShouldWork45.baseline | 1 - .../reference/inlayHintsShouldWork48.baseline | 8 - .../reference/inlayHintsShouldWork49.baseline | 1 - .../reference/inlayHintsShouldWork5.baseline | 65 --- .../reference/inlayHintsShouldWork53.baseline | 21 - .../reference/inlayHintsShouldWork55.baseline | 8 - .../reference/inlayHintsShouldWork57.baseline | 8 - .../reference/inlayHintsShouldWork58.baseline | 1 - .../reference/inlayHintsShouldWork59.baseline | 1 - .../reference/inlayHintsShouldWork6.baseline | 21 - .../reference/inlayHintsShouldWork60.baseline | 8 - .../reference/inlayHintsShouldWork61.baseline | 1 - .../reference/inlayHintsShouldWork62.baseline | 43 -- .../reference/inlayHintsShouldWork63.baseline | 87 ---- .../reference/inlayHintsShouldWork65.baseline | 8 - .../reference/inlayHintsShouldWork66.baseline | 8 - .../reference/inlayHintsShouldWork67.baseline | 1 - .../reference/inlayHintsShouldWork68.baseline | 43 -- .../reference/inlayHintsShouldWork69.baseline | 1 - .../reference/inlayHintsShouldWork7.baseline | 65 --- .../reference/inlayHintsShouldWork70.baseline | 17 - .../reference/inlayHintsShouldWork71.baseline | 17 - .../reference/inlayHintsShouldWork72.baseline | 17 - .../reference/inlayHintsShouldWork73.baseline | 17 - .../reference/inlayHintsShouldWork74.baseline | 17 - .../reference/inlayHintsShouldWork75.baseline | 26 - .../reference/inlayHintsShouldWork76.baseline | 8 - .../reference/inlayHintsShouldWork8.baseline | 65 --- ...ine => inlayHintsTypeMatchesName.baseline} | 0 ...line => inlayHintsVariableTypes1.baseline} | 6 +- ...line => inlayHintsVariableTypes2.baseline} | 9 + .../reference/inlayHintsWithClosures.baseline | 35 ++ ...Work44.ts => inlayHintsEnumMemberValue.ts} | 0 .../inlayHintsFunctionParameterTypes1.ts | 29 ++ ...s => inlayHintsFunctionParameterTypes2.ts} | 0 ...s => inlayHintsFunctionParameterTypes3.ts} | 6 + ...s => inlayHintsFunctionParameterTypes4.ts} | 0 ...ouldWork45.ts => inlayHintsImportType1.ts} | 0 ...ouldWork46.ts => inlayHintsImportType2.ts} | 0 .../inlayHintsInteractiveOverloadCall.ts | 30 ++ .../inlayHintsInteractiveParameterNames.ts | 49 ++ ...yHintsInteractiveParameterNamesInSpan1.ts} | 0 ...yHintsInteractiveParameterNamesInSpan2.ts} | 0 ...sInteractiveParameterNamesWithComments.ts} | 4 +- .../inlayHintsInteractiveRestParameters1.ts | 14 + .../inlayHintsInteractiveRestParameters2.ts | 23 + .../inlayHintsInteractiveWithClosures.ts | 18 + ...s => inlayHintsInterativeAnyParameter1.ts} | 0 ...s => inlayHintsInterativeAnyParameter2.ts} | 0 ...47.ts => inlayHintsJsDocParameterNames.ts} | 5 + ...houldWork51.ts => inlayHintsMultifile1.ts} | 0 ...nlayHintsNoHintWhenArgumentMatchesName.ts} | 0 ...ork14.ts => inlayHintsNoParameterHints.ts} | 0 ...20.ts => inlayHintsNoVariableTypeHints.ts} | 0 .../cases/fourslash/inlayHintsOverloadCall.ts | 30 ++ .../fourslash/inlayHintsParameterNames.ts | 49 ++ .../inlayHintsParameterNamesInSpan1.ts | 23 + .../inlayHintsParameterNamesInSpan2.ts | 23 + ...7.ts => inlayHintsPropertyDeclarations.ts} | 0 .../fourslash/inlayHintsRestParameters1.ts | 14 + .../fourslash/inlayHintsRestParameters2.ts | 22 + tests/cases/fourslash/inlayHintsReturnType.ts | 26 + .../cases/fourslash/inlayHintsShouldWork1.ts | 6 - .../cases/fourslash/inlayHintsShouldWork10.ts | 8 - .../cases/fourslash/inlayHintsShouldWork11.ts | 13 - .../cases/fourslash/inlayHintsShouldWork12.ts | 12 - .../cases/fourslash/inlayHintsShouldWork13.ts | 11 - .../cases/fourslash/inlayHintsShouldWork17.ts | 7 - .../cases/fourslash/inlayHintsShouldWork18.ts | 8 - .../cases/fourslash/inlayHintsShouldWork19.ts | 7 - .../cases/fourslash/inlayHintsShouldWork2.ts | 9 - .../cases/fourslash/inlayHintsShouldWork21.ts | 7 - .../cases/fourslash/inlayHintsShouldWork22.ts | 7 - .../cases/fourslash/inlayHintsShouldWork24.ts | 8 - .../cases/fourslash/inlayHintsShouldWork25.ts | 8 - .../cases/fourslash/inlayHintsShouldWork26.ts | 8 - .../cases/fourslash/inlayHintsShouldWork27.ts | 10 - .../cases/fourslash/inlayHintsShouldWork28.ts | 8 - .../cases/fourslash/inlayHintsShouldWork29.ts | 11 - .../cases/fourslash/inlayHintsShouldWork3.ts | 9 - .../cases/fourslash/inlayHintsShouldWork30.ts | 8 - .../cases/fourslash/inlayHintsShouldWork31.ts | 11 - .../cases/fourslash/inlayHintsShouldWork36.ts | 11 - .../cases/fourslash/inlayHintsShouldWork38.ts | 9 - .../cases/fourslash/inlayHintsShouldWork39.ts | 9 - .../cases/fourslash/inlayHintsShouldWork4.ts | 13 - .../cases/fourslash/inlayHintsShouldWork40.ts | 11 - .../cases/fourslash/inlayHintsShouldWork41.ts | 7 - .../cases/fourslash/inlayHintsShouldWork42.ts | 7 - .../cases/fourslash/inlayHintsShouldWork43.ts | 8 - .../cases/fourslash/inlayHintsShouldWork48.ts | 8 - .../cases/fourslash/inlayHintsShouldWork49.ts | 16 - .../cases/fourslash/inlayHintsShouldWork5.ts | 10 - .../cases/fourslash/inlayHintsShouldWork50.ts | 12 - .../cases/fourslash/inlayHintsShouldWork53.ts | 9 - .../cases/fourslash/inlayHintsShouldWork55.ts | 9 - .../cases/fourslash/inlayHintsShouldWork57.ts | 11 - .../cases/fourslash/inlayHintsShouldWork58.ts | 11 - .../cases/fourslash/inlayHintsShouldWork6.ts | 10 - .../cases/fourslash/inlayHintsShouldWork60.ts | 14 - .../cases/fourslash/inlayHintsShouldWork61.ts | 9 - .../cases/fourslash/inlayHintsShouldWork62.ts | 10 - .../cases/fourslash/inlayHintsShouldWork63.ts | 9 - .../cases/fourslash/inlayHintsShouldWork64.ts | 33 -- .../cases/fourslash/inlayHintsShouldWork65.ts | 8 - .../cases/fourslash/inlayHintsShouldWork68.ts | 11 - .../cases/fourslash/inlayHintsShouldWork7.ts | 14 - .../cases/fourslash/inlayHintsShouldWork70.ts | 10 - .../cases/fourslash/inlayHintsShouldWork71.ts | 10 - .../cases/fourslash/inlayHintsShouldWork72.ts | 10 - .../cases/fourslash/inlayHintsShouldWork73.ts | 10 - .../cases/fourslash/inlayHintsShouldWork74.ts | 10 - .../cases/fourslash/inlayHintsShouldWork75.ts | 10 - .../cases/fourslash/inlayHintsShouldWork76.ts | 10 - .../cases/fourslash/inlayHintsShouldWork8.ts | 14 - .../cases/fourslash/inlayHintsShouldWork9.ts | 16 - ...Work67.ts => inlayHintsTypeMatchesName.ts} | 0 ...dWork15.ts => inlayHintsVariableTypes1.ts} | 9 +- ...dWork56.ts => inlayHintsVariableTypes2.ts} | 3 + .../cases/fourslash/inlayHintsWithClosures.ts | 17 + 175 files changed, 2196 insertions(+), 1784 deletions(-) rename tests/baselines/reference/{inlayHintsShouldWork44.baseline => inlayHintsEnumMemberValue.baseline} (100%) create mode 100644 tests/baselines/reference/inlayHintsFunctionParameterTypes1.baseline rename tests/baselines/reference/{inlayHintsShouldWork10.baseline => inlayHintsFunctionParameterTypes2.baseline} (100%) create mode 100644 tests/baselines/reference/inlayHintsFunctionParameterTypes3.baseline rename tests/baselines/reference/{inlayHintsShouldWork14.baseline => inlayHintsFunctionParameterTypes4.baseline} (100%) rename tests/baselines/reference/{inlayHintsShouldWork15.baseline => inlayHintsImportType1.baseline} (100%) rename tests/baselines/reference/{inlayHintsShouldWork46.baseline => inlayHintsImportType2.baseline} (100%) rename tests/baselines/reference/{inlayHintsShouldWork64.baseline => inlayHintsInteractiveOverloadCall.baseline} (56%) create mode 100644 tests/baselines/reference/inlayHintsInteractiveParameterNames.baseline rename tests/baselines/reference/{inlayHintsShouldWork32.baseline => inlayHintsInteractiveParameterNamesInSpan1.baseline} (77%) rename tests/baselines/reference/{inlayHintsShouldWork33.baseline => inlayHintsInteractiveParameterNamesInSpan2.baseline} (75%) rename tests/baselines/reference/{inlayHintsShouldWork52.baseline => inlayHintsInteractiveParameterNamesWithComments.baseline} (50%) rename tests/baselines/reference/{inlayHintsShouldWork50.baseline => inlayHintsInteractiveRestParameters1.baseline} (55%) create mode 100644 tests/baselines/reference/inlayHintsInteractiveRestParameters2.baseline create mode 100644 tests/baselines/reference/inlayHintsInteractiveReturnType.baseline rename tests/baselines/reference/{inlayHintsShouldWork9.baseline => inlayHintsInteractiveWithClosures.baseline} (57%) rename tests/baselines/reference/{inlayHintsShouldWork34.baseline => inlayHintsInterativeAnyParameter1.baseline} (77%) rename tests/baselines/reference/{inlayHintsShouldWork35.baseline => inlayHintsInterativeAnyParameter2.baseline} (77%) rename tests/baselines/reference/{inlayHintsShouldWork47.baseline => inlayHintsJsDocParameterNames.baseline} (100%) rename tests/baselines/reference/{inlayHintsShouldWork51.baseline => inlayHintsMultifile1.baseline} (100%) rename tests/baselines/reference/{inlayHintsShouldWork54.baseline => inlayHintsNoHintWhenArgumentMatchesName.baseline} (100%) rename tests/baselines/reference/{inlayHintsShouldWork17.baseline => inlayHintsNoParameterHints.baseline} (100%) rename tests/baselines/reference/{inlayHintsShouldWork18.baseline => inlayHintsNoVariableTypeHints.baseline} (100%) create mode 100644 tests/baselines/reference/inlayHintsOverloadCall.baseline create mode 100644 tests/baselines/reference/inlayHintsParameterNames.baseline create mode 100644 tests/baselines/reference/inlayHintsParameterNamesInSpan1.baseline create mode 100644 tests/baselines/reference/inlayHintsParameterNamesInSpan2.baseline rename tests/baselines/reference/{inlayHintsShouldWork37.baseline => inlayHintsPropertyDeclarations.baseline} (100%) create mode 100644 tests/baselines/reference/inlayHintsRestParameters1.baseline create mode 100644 tests/baselines/reference/inlayHintsRestParameters2.baseline create mode 100644 tests/baselines/reference/inlayHintsReturnType.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork1.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork11.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork12.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork13.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork2.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork21.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork22.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork24.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork25.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork26.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork27.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork28.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork29.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork3.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork30.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork31.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork36.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork38.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork39.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork4.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork40.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork41.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork42.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork43.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork45.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork48.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork49.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork5.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork53.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork55.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork57.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork58.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork59.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork6.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork60.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork61.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork62.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork63.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork65.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork66.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork67.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork68.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork69.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork7.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork70.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork71.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork72.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork73.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork74.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork75.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork76.baseline delete mode 100644 tests/baselines/reference/inlayHintsShouldWork8.baseline rename tests/baselines/reference/{inlayHintsShouldWork20.baseline => inlayHintsTypeMatchesName.baseline} (100%) rename tests/baselines/reference/{inlayHintsShouldWork19.baseline => inlayHintsVariableTypes1.baseline} (59%) rename tests/baselines/reference/{inlayHintsShouldWork56.baseline => inlayHintsVariableTypes2.baseline} (77%) create mode 100644 tests/baselines/reference/inlayHintsWithClosures.baseline rename tests/cases/fourslash/{inlayHintsShouldWork44.ts => inlayHintsEnumMemberValue.ts} (100%) create mode 100644 tests/cases/fourslash/inlayHintsFunctionParameterTypes1.ts rename tests/cases/fourslash/{inlayHintsShouldWork69.ts => inlayHintsFunctionParameterTypes2.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork66.ts => inlayHintsFunctionParameterTypes3.ts} (66%) rename tests/cases/fourslash/{inlayHintsShouldWork59.ts => inlayHintsFunctionParameterTypes4.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork45.ts => inlayHintsImportType1.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork46.ts => inlayHintsImportType2.ts} (100%) create mode 100644 tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts create mode 100644 tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts rename tests/cases/fourslash/{inlayHintsShouldWork32.ts => inlayHintsInteractiveParameterNamesInSpan1.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork33.ts => inlayHintsInteractiveParameterNamesInSpan2.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork52.ts => inlayHintsInteractiveParameterNamesWithComments.ts} (84%) create mode 100644 tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts create mode 100644 tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts create mode 100644 tests/cases/fourslash/inlayHintsInteractiveWithClosures.ts rename tests/cases/fourslash/{inlayHintsShouldWork34.ts => inlayHintsInterativeAnyParameter1.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork35.ts => inlayHintsInterativeAnyParameter2.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork47.ts => inlayHintsJsDocParameterNames.ts} (80%) rename tests/cases/fourslash/{inlayHintsShouldWork51.ts => inlayHintsMultifile1.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork54.ts => inlayHintsNoHintWhenArgumentMatchesName.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork14.ts => inlayHintsNoParameterHints.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork20.ts => inlayHintsNoVariableTypeHints.ts} (100%) create mode 100644 tests/cases/fourslash/inlayHintsOverloadCall.ts create mode 100644 tests/cases/fourslash/inlayHintsParameterNames.ts create mode 100644 tests/cases/fourslash/inlayHintsParameterNamesInSpan1.ts create mode 100644 tests/cases/fourslash/inlayHintsParameterNamesInSpan2.ts rename tests/cases/fourslash/{inlayHintsShouldWork37.ts => inlayHintsPropertyDeclarations.ts} (100%) create mode 100644 tests/cases/fourslash/inlayHintsRestParameters1.ts create mode 100644 tests/cases/fourslash/inlayHintsRestParameters2.ts create mode 100644 tests/cases/fourslash/inlayHintsReturnType.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork1.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork10.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork11.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork12.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork13.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork17.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork18.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork19.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork2.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork21.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork22.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork24.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork25.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork26.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork27.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork28.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork29.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork3.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork30.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork31.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork36.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork38.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork39.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork4.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork40.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork41.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork42.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork43.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork48.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork49.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork5.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork50.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork53.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork55.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork57.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork58.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork6.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork60.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork61.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork62.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork63.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork64.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork65.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork68.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork7.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork70.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork71.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork72.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork73.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork74.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork75.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork76.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork8.ts delete mode 100644 tests/cases/fourslash/inlayHintsShouldWork9.ts rename tests/cases/fourslash/{inlayHintsShouldWork67.ts => inlayHintsTypeMatchesName.ts} (100%) rename tests/cases/fourslash/{inlayHintsShouldWork15.ts => inlayHintsVariableTypes1.ts} (87%) rename tests/cases/fourslash/{inlayHintsShouldWork56.ts => inlayHintsVariableTypes2.ts} (79%) create mode 100644 tests/cases/fourslash/inlayHintsWithClosures.ts diff --git a/tests/baselines/reference/inlayHintsShouldWork44.baseline b/tests/baselines/reference/inlayHintsEnumMemberValue.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork44.baseline rename to tests/baselines/reference/inlayHintsEnumMemberValue.baseline diff --git a/tests/baselines/reference/inlayHintsFunctionParameterTypes1.baseline b/tests/baselines/reference/inlayHintsFunctionParameterTypes1.baseline new file mode 100644 index 0000000000000..31c95617ae2ce --- /dev/null +++ b/tests/baselines/reference/inlayHintsFunctionParameterTypes1.baseline @@ -0,0 +1,80 @@ +const f1: F1 = (a, b) => { } + ^ +{ + "text": ": string", + "position": 58, + "kind": "Type", + "whitespaceBefore": true +} + +const f1: F1 = (a, b) => { } + ^ +{ + "text": ": number", + "position": 61, + "kind": "Type", + "whitespaceBefore": true +} + +const f2: F1 = (a, b: number) => { } + ^ +{ + "text": ": string", + "position": 87, + "kind": "Type", + "whitespaceBefore": true +} + +foo1((a) => { }) + ^ +{ + "text": ": string", + "position": 157, + "kind": "Type", + "whitespaceBefore": true +} + +foo2((a) => { }) + ^ +{ + "text": ": 2 | 3", + "position": 232, + "kind": "Type", + "whitespaceBefore": true +} + +foo3(a => { + ^ +{ + "text": ": (c: (d: 2 | 3) => void) => ...", + "position": 331, + "kind": "Type", + "whitespaceBefore": true +} + + a(d => {}) + ^ +{ + "text": ": 2 | 3", + "position": 344, + "kind": "Type", + "whitespaceBefore": true +} + +foo4(1, a => { }) + ^ +{ + "text": ": number", + "position": 409, + "kind": "Type", + "whitespaceBefore": true +} + +const foo5: F2 = (a) => { } + ^ +{ + "text": ": { a: number; b: string; }", + "position": 492, + "kind": "Type", + "whitespaceBefore": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork10.baseline b/tests/baselines/reference/inlayHintsFunctionParameterTypes2.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork10.baseline rename to tests/baselines/reference/inlayHintsFunctionParameterTypes2.baseline diff --git a/tests/baselines/reference/inlayHintsFunctionParameterTypes3.baseline b/tests/baselines/reference/inlayHintsFunctionParameterTypes3.baseline new file mode 100644 index 0000000000000..33923495c7bbd --- /dev/null +++ b/tests/baselines/reference/inlayHintsFunctionParameterTypes3.baseline @@ -0,0 +1,17 @@ + bar: function (x?): void { + ^ +{ + "text": ": boolean", + "position": 87, + "kind": "Type", + "whitespaceBefore": true +} + + set foo(value) { this.#value = value; } + ^ +{ + "text": ": number", + "position": 250, + "kind": "Type", + "whitespaceBefore": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork14.baseline b/tests/baselines/reference/inlayHintsFunctionParameterTypes4.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork14.baseline rename to tests/baselines/reference/inlayHintsFunctionParameterTypes4.baseline diff --git a/tests/baselines/reference/inlayHintsShouldWork15.baseline b/tests/baselines/reference/inlayHintsImportType1.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork15.baseline rename to tests/baselines/reference/inlayHintsImportType1.baseline diff --git a/tests/baselines/reference/inlayHintsShouldWork46.baseline b/tests/baselines/reference/inlayHintsImportType2.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork46.baseline rename to tests/baselines/reference/inlayHintsImportType2.baseline diff --git a/tests/baselines/reference/inlayHintsShouldWork64.baseline b/tests/baselines/reference/inlayHintsInteractiveOverloadCall.baseline similarity index 56% rename from tests/baselines/reference/inlayHintsShouldWork64.baseline rename to tests/baselines/reference/inlayHintsInteractiveOverloadCall.baseline index 3b0b481bfe47f..10df249d87895 100644 --- a/tests/baselines/reference/inlayHintsShouldWork64.baseline +++ b/tests/baselines/reference/inlayHintsInteractiveOverloadCall.baseline @@ -1,18 +1,18 @@ - "hello", - ^ +call(1); + ^ { "text": "", - "position": 183, + "position": 131, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "a", "span": { - "start": 18, + "start": 22, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -20,21 +20,21 @@ ] } - undefined, - ^ +call(1, 2); + ^ { "text": "", - "position": 196, + "position": 140, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "b", "span": { - "start": 33, + "start": 44, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -42,21 +42,21 @@ ] } - null, - ^ +call(1, 2); + ^ { "text": "", - "position": 211, + "position": 143, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "c", "span": { - "start": 51, + "start": 55, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -64,21 +64,21 @@ ] } - true, - ^ +new call(1); + ^ { "text": "", - "position": 221, + "position": 156, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "d", "span": { - "start": 64, + "start": 81, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -86,21 +86,21 @@ ] } - false, +foo(1) ^ { "text": "", - "position": 231, + "position": 326, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "e", + "text": "w", "span": { - "start": 80, + "start": 181, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -108,21 +108,21 @@ ] } - Infinity, +foo(1, 2) ^ { "text": "", - "position": 242, + "position": 333, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "f", + "text": "a", "span": { - "start": 96, + "start": 219, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -130,21 +130,21 @@ ] } - -Infinity, - ^ +foo(1, 2) + ^ { "text": "", - "position": 256, + "position": 336, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "g", + "text": "b", "span": { - "start": 111, + "start": 230, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -152,21 +152,21 @@ ] } - NaN, - ^ +new Class(1) + ^ { "text": "", - "position": 271, + "position": 475, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "h", + "text": "a", "span": { - "start": 126, + "start": 369, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -174,21 +174,21 @@ ] } - /hello/g, - ^ +new Class(1, 2) + ^ { "text": "", - "position": 280, + "position": 488, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "i", + "text": "b", "span": { - "start": 141, + "start": 397, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" @@ -196,21 +196,21 @@ ] } - 123n, - ^ +new Class(1, 2) + ^ { "text": "", - "position": 294, + "position": 491, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "j", + "text": "c", "span": { - "start": 156, + "start": 408, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork64.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts" }, { "text": ":" diff --git a/tests/baselines/reference/inlayHintsInteractiveParameterNames.baseline b/tests/baselines/reference/inlayHintsInteractiveParameterNames.baseline new file mode 100644 index 0000000000000..b6ab7a563a21e --- /dev/null +++ b/tests/baselines/reference/inlayHintsInteractiveParameterNames.baseline @@ -0,0 +1,461 @@ + foo1(1, 2); + ^ +{ + "text": "", + "position": 47, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 16, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + foo1(1, 2); + ^ +{ + "text": "", + "position": 50, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "b", + "span": { + "start": 27, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + foo2(1, { c: 1 }); + ^ +{ + "text": "", + "position": 102, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 70, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + +const C1 = class extends foo3(1) { } + ^ +{ + "text": "", + "position": 180, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 130, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + +class C2 extends foo3(1) { } + ^ +{ + "text": "", + "position": 209, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 130, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + +foo4(1, +1, -1, +"1"); + ^ +{ + "text": "", + "position": 282, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 230, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + +foo4(1, +1, -1, +"1"); + ^ +{ + "text": "", + "position": 285, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "b", + "span": { + "start": 241, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + +foo4(1, +1, -1, +"1"); + ^ +{ + "text": "", + "position": 289, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "c", + "span": { + "start": 252, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + +foo4(1, +1, -1, +"1"); + ^ +{ + "text": "", + "position": 293, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "d", + "span": { + "start": 263, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + "hello", + ^ +{ + "text": "", + "position": 484, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 319, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + undefined, + ^ +{ + "text": "", + "position": 497, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "b", + "span": { + "start": 334, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + null, + ^ +{ + "text": "", + "position": 512, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "c", + "span": { + "start": 352, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + true, + ^ +{ + "text": "", + "position": 522, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "d", + "span": { + "start": 365, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + false, + ^ +{ + "text": "", + "position": 532, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "e", + "span": { + "start": 381, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + Infinity, + ^ +{ + "text": "", + "position": 543, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "f", + "span": { + "start": 397, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + -Infinity, + ^ +{ + "text": "", + "position": 557, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "g", + "span": { + "start": 412, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + NaN, + ^ +{ + "text": "", + "position": 572, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "h", + "span": { + "start": 427, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + /hello/g, + ^ +{ + "text": "", + "position": 581, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "i", + "span": { + "start": 442, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + + 123n, + ^ +{ + "text": "", + "position": 595, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "j", + "span": { + "start": 457, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + +trace(`${1}`); + ^ +{ + "text": "", + "position": 694, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "message", + "span": { + "start": 668, + "length": 7 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} + +trace(``); + ^ +{ + "text": "", + "position": 709, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "message", + "span": { + "start": 668, + "length": 7 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts" + }, + { + "text": ":" + } + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork32.baseline b/tests/baselines/reference/inlayHintsInteractiveParameterNamesInSpan1.baseline similarity index 77% rename from tests/baselines/reference/inlayHintsShouldWork32.baseline rename to tests/baselines/reference/inlayHintsInteractiveParameterNamesInSpan1.baseline index ae2a23eb09dc1..966225e43a31b 100644 --- a/tests/baselines/reference/inlayHintsShouldWork32.baseline +++ b/tests/baselines/reference/inlayHintsInteractiveParameterNamesInSpan1.baseline @@ -12,7 +12,7 @@ function c2 () { foo2(1, 2); } "start": 55, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork32.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan1.ts" }, { "text": ":" @@ -34,7 +34,7 @@ function c2 () { foo2(1, 2); } "start": 66, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork32.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan1.ts" }, { "text": ":" @@ -56,7 +56,7 @@ function c3 () { foo3(1, 2); } "start": 95, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork32.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan1.ts" }, { "text": ":" @@ -78,7 +78,7 @@ function c3 () { foo3(1, 2); } "start": 106, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork32.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan1.ts" }, { "text": ":" @@ -100,7 +100,7 @@ function c4 () { foo4(1, 2); } "start": 135, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork32.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan1.ts" }, { "text": ":" @@ -122,7 +122,7 @@ function c4 () { foo4(1, 2); } "start": 146, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork32.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan1.ts" }, { "text": ":" diff --git a/tests/baselines/reference/inlayHintsShouldWork33.baseline b/tests/baselines/reference/inlayHintsInteractiveParameterNamesInSpan2.baseline similarity index 75% rename from tests/baselines/reference/inlayHintsShouldWork33.baseline rename to tests/baselines/reference/inlayHintsInteractiveParameterNamesInSpan2.baseline index f64b6f03927d1..acc0b6dbdba22 100644 --- a/tests/baselines/reference/inlayHintsShouldWork33.baseline +++ b/tests/baselines/reference/inlayHintsInteractiveParameterNamesInSpan2.baseline @@ -12,7 +12,7 @@ foo2(1, 2); "start": 55, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork33.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan2.ts" }, { "text": ":" @@ -34,7 +34,7 @@ foo2(1, 2); "start": 66, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork33.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan2.ts" }, { "text": ":" @@ -56,7 +56,7 @@ foo3(1, 2); "start": 95, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork33.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan2.ts" }, { "text": ":" @@ -78,7 +78,7 @@ foo3(1, 2); "start": 106, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork33.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan2.ts" }, { "text": ":" @@ -100,7 +100,7 @@ foo4(1, 2); "start": 135, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork33.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan2.ts" }, { "text": ":" @@ -122,7 +122,7 @@ foo4(1, 2); "start": 146, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork33.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan2.ts" }, { "text": ":" diff --git a/tests/baselines/reference/inlayHintsShouldWork52.baseline b/tests/baselines/reference/inlayHintsInteractiveParameterNamesWithComments.baseline similarity index 50% rename from tests/baselines/reference/inlayHintsShouldWork52.baseline rename to tests/baselines/reference/inlayHintsInteractiveParameterNamesWithComments.baseline index b0572fd914cbd..9ca391a20c77d 100644 --- a/tests/baselines/reference/inlayHintsShouldWork52.baseline +++ b/tests/baselines/reference/inlayHintsInteractiveParameterNamesWithComments.baseline @@ -1,27 +1,40 @@ -function foo (aParameter: number, bParameter: number, cParameter: number) { } - ^ +fn(/* nobody knows exactly what this param is */ 42); + ^ { - "text": ": void", - "position": 73, - "kind": "Type", - "whitespaceBefore": true + "text": "", + "position": 76, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "x", + "span": { + "start": 12, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts" + }, + { + "text": ":" + } + ] } 2, ^ { "text": "", - "position": 134, + "position": 215, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "bParameter", "span": { - "start": 34, + "start": 115, "length": 10 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork52.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts" }, { "text": ":" @@ -33,17 +46,17 @@ function foo (aParameter: number, bParameter: number, cParameter: number) { } ^ { "text": "", - "position": 338, + "position": 419, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "cParameter", "span": { - "start": 54, + "start": 135, "length": 10 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork52.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts" }, { "text": ":" @@ -55,17 +68,17 @@ function foo (aParameter: number, bParameter: number, cParameter: number) { } ^ { "text": "", - "position": 373, + "position": 454, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "aParameter", "span": { - "start": 14, + "start": 95, "length": 10 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork52.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts" }, { "text": ":" @@ -77,17 +90,17 @@ function foo (aParameter: number, bParameter: number, cParameter: number) { } ^ { "text": "", - "position": 380, + "position": 461, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "bParameter", "span": { - "start": 34, + "start": 115, "length": 10 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork52.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts" }, { "text": ":" @@ -99,17 +112,17 @@ function foo (aParameter: number, bParameter: number, cParameter: number) { } ^ { "text": "", - "position": 440, + "position": 521, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "cParameter", "span": { - "start": 54, + "start": 135, "length": 10 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork52.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts" }, { "text": ":" diff --git a/tests/baselines/reference/inlayHintsShouldWork50.baseline b/tests/baselines/reference/inlayHintsInteractiveRestParameters1.baseline similarity index 55% rename from tests/baselines/reference/inlayHintsShouldWork50.baseline rename to tests/baselines/reference/inlayHintsInteractiveRestParameters1.baseline index df463016ccac4..6241709b7f373 100644 --- a/tests/baselines/reference/inlayHintsShouldWork50.baseline +++ b/tests/baselines/reference/inlayHintsInteractiveRestParameters1.baseline @@ -1,18 +1,18 @@ -foo(1, '', false, 1, 2) - ^ +foo1(1, 1, 1, 1); + ^ { "text": "", - "position": 161, + "position": 49, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "f", + "text": "a", "span": { - "start": 70, + "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork50.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts" }, { "text": ":" @@ -20,21 +20,21 @@ foo(1, '', false, 1, 2) ] } -foo(1, '', false, 1, 2) - ^ +foo1(1, 1, 1, 1); + ^ { "text": "", - "position": 164, + "position": 52, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "a", + "text": "...b", "span": { - "start": 10, + "start": 28, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork50.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts" }, { "text": ":" @@ -42,21 +42,21 @@ foo(1, '', false, 1, 2) ] } -foo(1, '', false, 1, 2) - ^ +foo2(1, 2, 3) + ^ { "text": "", - "position": 168, + "position": 153, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "b", + "text": "c", "span": { - "start": 21, + "start": 120, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork50.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts" }, { "text": ":" @@ -64,21 +64,21 @@ foo(1, '', false, 1, 2) ] } -foo(1, '', false, 1, 2) - ^ +foo2(1, 2, 3) + ^ { "text": "", - "position": 175, + "position": 156, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "...c", + "text": "a", "span": { - "start": 36, + "start": 76, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork50.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts" }, { "text": ":" @@ -86,21 +86,21 @@ foo(1, '', false, 1, 2) ] } -foo1(1, "", "") - ^ +foo2(1, 2, 3) + ^ { "text": "", - "position": 186, + "position": 159, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "f1", + "text": "b", "span": { - "start": 120, - "length": 2 + "start": 87, + "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork50.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts" }, { "text": ":" @@ -108,21 +108,21 @@ foo1(1, "", "") ] } -foo1(1, "", "") - ^ +foo3(1, 2, 3) + ^ { "text": "", - "position": 189, + "position": 247, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "...args", + "text": "c", "span": { - "start": 135, - "length": 4 + "start": 214, + "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork50.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts" }, { "text": ":" diff --git a/tests/baselines/reference/inlayHintsInteractiveRestParameters2.baseline b/tests/baselines/reference/inlayHintsInteractiveRestParameters2.baseline new file mode 100644 index 0000000000000..8d5e91db2fd01 --- /dev/null +++ b/tests/baselines/reference/inlayHintsInteractiveRestParameters2.baseline @@ -0,0 +1,241 @@ + foo(...x, 3); + ^ +{ + "text": "", + "position": 113, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 13, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(...x, 3); + ^ +{ + "text": "", + "position": 119, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "c", + "span": { + "start": 37, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(...x, 1, 2, 3); + ^ +{ + "text": "", + "position": 165, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 13, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(...x, 1, 2, 3); + ^ +{ + "text": "", + "position": 168, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "b", + "span": { + "start": 25, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(...x, 1, 2, 3); + ^ +{ + "text": "", + "position": 171, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "c", + "span": { + "start": 37, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(1, ...x); + ^ +{ + "text": "", + "position": 226, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 13, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(1, ...x); + ^ +{ + "text": "", + "position": 229, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "b", + "span": { + "start": 25, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(...x, 3); + ^ +{ + "text": "", + "position": 287, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 13, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(...x, 3); + ^ +{ + "text": "", + "position": 293, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "b", + "span": { + "start": 25, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(...x, 3); + ^ +{ + "text": "", + "position": 347, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "a", + "span": { + "start": 13, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} + + foo(...x, 3); + ^ +{ + "text": "", + "position": 353, + "kind": "Parameter", + "whitespaceAfter": true, + "displayParts": [ + { + "text": "c", + "span": { + "start": 37, + "length": 1 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts" + }, + { + "text": ":" + } + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsInteractiveReturnType.baseline b/tests/baselines/reference/inlayHintsInteractiveReturnType.baseline new file mode 100644 index 0000000000000..24d374144aece --- /dev/null +++ b/tests/baselines/reference/inlayHintsInteractiveReturnType.baseline @@ -0,0 +1,205 @@ +function numberLiteral() { return 1; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "number" + } + ], + "position": 52, + "kind": "Type", + "whitespaceBefore": true +} + +function stringLiteral() { return "foo"; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "string" + } + ], + "position": 91, + "kind": "Type", + "whitespaceBefore": true +} + +function nothing() { } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "void" + } + ], + "position": 128, + "kind": "Type", + "whitespaceBefore": true +} + +function closure() { return () => 1; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "(" + }, + { + "text": ")" + }, + { + "text": " => " + }, + { + "text": "number" + } + ], + "position": 151, + "kind": "Type", + "whitespaceBefore": true +} + +function closure() { return () => 1; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "number" + } + ], + "position": 163, + "kind": "Type", + "whitespaceBefore": true +} + +function fooClosure() { return (foo: Foo) => foo.bar; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "(" + }, + { + "text": ")" + }, + { + "text": " => " + }, + { + "text": "number" + } + ], + "position": 193, + "kind": "Type", + "whitespaceBefore": true +} + +function fooClosure() { return (foo: Foo) => foo.bar; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "number" + } + ], + "position": 213, + "kind": "Type", + "whitespaceBefore": true +} + +function returnFoo(foo: Foo) { return foo; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "Foo", + "span": { + "start": 5, + "length": 3 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveReturnType.ts" + } + ], + "position": 256, + "kind": "Type", + "whitespaceBefore": true +} + +function returnMaybeFoo(foo: Foo) { if (Math.random()) return foo; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "Foo", + "span": { + "start": 5, + "length": 3 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveReturnType.ts" + } + ], + "position": 306, + "kind": "Type", + "whitespaceBefore": true +} + +function returnFoos(foo: Foo) { return [foo, foo]; } + ^ +{ + "text": "", + "displayParts": [ + { + "text": ": " + }, + { + "text": "Foo", + "span": { + "start": 5, + "length": 3 + }, + "file": "/tests/cases/fourslash/inlayHintsInteractiveReturnType.ts" + }, + { + "text": "[]" + } + ], + "position": 371, + "kind": "Type", + "whitespaceBefore": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork9.baseline b/tests/baselines/reference/inlayHintsInteractiveWithClosures.baseline similarity index 57% rename from tests/baselines/reference/inlayHintsShouldWork9.baseline rename to tests/baselines/reference/inlayHintsInteractiveWithClosures.baseline index 2e42331c3faf2..105dc62910621 100644 --- a/tests/baselines/reference/inlayHintsShouldWork9.baseline +++ b/tests/baselines/reference/inlayHintsInteractiveWithClosures.baseline @@ -1,18 +1,18 @@ -call(1); +foo1(1)(2); ^ { "text": "", - "position": 131, + "position": 89, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "a", "span": { - "start": 22, + "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork9.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveWithClosures.ts" }, { "text": ":" @@ -20,21 +20,21 @@ call(1); ] } -call(1, 2); - ^ +foo1(1)(2); + ^ { "text": "", - "position": 140, + "position": 92, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { "text": "b", "span": { - "start": 44, + "start": 39, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork9.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveWithClosures.ts" }, { "text": ":" @@ -42,21 +42,21 @@ call(1, 2); ] } -call(1, 2); - ^ + return a(1) + 2 + ^ { "text": "", - "position": 143, + "position": 151, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "c", + "text": "b", "span": { - "start": 55, + "start": 114, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork9.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveWithClosures.ts" }, { "text": ":" @@ -64,21 +64,21 @@ call(1, 2); ] } -new call(1); - ^ +foo2((c: number) => c + 1); + ^ { "text": "", - "position": 156, + "position": 165, "kind": "Parameter", "whitespaceAfter": true, "displayParts": [ { - "text": "d", + "text": "a", "span": { - "start": 81, + "start": 110, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork9.ts" + "file": "/tests/cases/fourslash/inlayHintsInteractiveWithClosures.ts" }, { "text": ":" diff --git a/tests/baselines/reference/inlayHintsShouldWork34.baseline b/tests/baselines/reference/inlayHintsInterativeAnyParameter1.baseline similarity index 77% rename from tests/baselines/reference/inlayHintsShouldWork34.baseline rename to tests/baselines/reference/inlayHintsInterativeAnyParameter1.baseline index e4945d9a5d073..6d4d794d58e4a 100644 --- a/tests/baselines/reference/inlayHintsShouldWork34.baseline +++ b/tests/baselines/reference/inlayHintsInterativeAnyParameter1.baseline @@ -12,7 +12,7 @@ foo(1); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork34.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter1.ts" }, { "text": ":" @@ -34,7 +34,7 @@ foo(''); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork34.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter1.ts" }, { "text": ":" @@ -56,7 +56,7 @@ foo(true); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork34.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter1.ts" }, { "text": ":" @@ -78,7 +78,7 @@ foo((1)); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork34.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter1.ts" }, { "text": ":" @@ -100,7 +100,7 @@ foo(foo(1)); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork34.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter1.ts" }, { "text": ":" diff --git a/tests/baselines/reference/inlayHintsShouldWork35.baseline b/tests/baselines/reference/inlayHintsInterativeAnyParameter2.baseline similarity index 77% rename from tests/baselines/reference/inlayHintsShouldWork35.baseline rename to tests/baselines/reference/inlayHintsInterativeAnyParameter2.baseline index 5bf2348d3b7dd..510267abb4adb 100644 --- a/tests/baselines/reference/inlayHintsShouldWork35.baseline +++ b/tests/baselines/reference/inlayHintsInterativeAnyParameter2.baseline @@ -12,7 +12,7 @@ foo(1); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -34,7 +34,7 @@ foo(''); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -56,7 +56,7 @@ foo(true); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -78,7 +78,7 @@ foo(() => 1); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -100,7 +100,7 @@ foo(function () { return 1 }); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -122,7 +122,7 @@ foo({}); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -144,7 +144,7 @@ foo({ a: 1 }); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -166,7 +166,7 @@ foo([]); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -188,7 +188,7 @@ foo([1]); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -210,7 +210,7 @@ foo(foo); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -232,7 +232,7 @@ foo((1)); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -254,7 +254,7 @@ foo(foo(1)); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" @@ -276,7 +276,7 @@ foo(foo(1)); "start": 14, "length": 1 }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork35.ts" + "file": "/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts" }, { "text": ":" diff --git a/tests/baselines/reference/inlayHintsShouldWork47.baseline b/tests/baselines/reference/inlayHintsJsDocParameterNames.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork47.baseline rename to tests/baselines/reference/inlayHintsJsDocParameterNames.baseline diff --git a/tests/baselines/reference/inlayHintsShouldWork51.baseline b/tests/baselines/reference/inlayHintsMultifile1.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork51.baseline rename to tests/baselines/reference/inlayHintsMultifile1.baseline diff --git a/tests/baselines/reference/inlayHintsShouldWork54.baseline b/tests/baselines/reference/inlayHintsNoHintWhenArgumentMatchesName.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork54.baseline rename to tests/baselines/reference/inlayHintsNoHintWhenArgumentMatchesName.baseline diff --git a/tests/baselines/reference/inlayHintsShouldWork17.baseline b/tests/baselines/reference/inlayHintsNoParameterHints.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork17.baseline rename to tests/baselines/reference/inlayHintsNoParameterHints.baseline diff --git a/tests/baselines/reference/inlayHintsShouldWork18.baseline b/tests/baselines/reference/inlayHintsNoVariableTypeHints.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork18.baseline rename to tests/baselines/reference/inlayHintsNoVariableTypeHints.baseline diff --git a/tests/baselines/reference/inlayHintsOverloadCall.baseline b/tests/baselines/reference/inlayHintsOverloadCall.baseline new file mode 100644 index 0000000000000..8c9f5baed425d --- /dev/null +++ b/tests/baselines/reference/inlayHintsOverloadCall.baseline @@ -0,0 +1,89 @@ +call(1); + ^ +{ + "text": "a:", + "position": 131, + "kind": "Parameter", + "whitespaceAfter": true +} + +call(1, 2); + ^ +{ + "text": "b:", + "position": 140, + "kind": "Parameter", + "whitespaceAfter": true +} + +call(1, 2); + ^ +{ + "text": "c:", + "position": 143, + "kind": "Parameter", + "whitespaceAfter": true +} + +new call(1); + ^ +{ + "text": "d:", + "position": 156, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo(1) + ^ +{ + "text": "w:", + "position": 326, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo(1, 2) + ^ +{ + "text": "a:", + "position": 333, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo(1, 2) + ^ +{ + "text": "b:", + "position": 336, + "kind": "Parameter", + "whitespaceAfter": true +} + +new Class(1) + ^ +{ + "text": "a:", + "position": 475, + "kind": "Parameter", + "whitespaceAfter": true +} + +new Class(1, 2) + ^ +{ + "text": "b:", + "position": 488, + "kind": "Parameter", + "whitespaceAfter": true +} + +new Class(1, 2) + ^ +{ + "text": "c:", + "position": 491, + "kind": "Parameter", + "whitespaceAfter": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsParameterNames.baseline b/tests/baselines/reference/inlayHintsParameterNames.baseline new file mode 100644 index 0000000000000..bb7fd50b15c25 --- /dev/null +++ b/tests/baselines/reference/inlayHintsParameterNames.baseline @@ -0,0 +1,188 @@ + foo1(1, 2); + ^ +{ + "text": "a:", + "position": 47, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo1(1, 2); + ^ +{ + "text": "b:", + "position": 50, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo2(1, { c: 1 }); + ^ +{ + "text": "a:", + "position": 102, + "kind": "Parameter", + "whitespaceAfter": true +} + +const C1 = class extends foo3(1) { } + ^ +{ + "text": "a:", + "position": 180, + "kind": "Parameter", + "whitespaceAfter": true +} + +class C2 extends foo3(1) { } + ^ +{ + "text": "a:", + "position": 209, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo4(1, +1, -1, +"1"); + ^ +{ + "text": "a:", + "position": 282, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo4(1, +1, -1, +"1"); + ^ +{ + "text": "b:", + "position": 285, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo4(1, +1, -1, +"1"); + ^ +{ + "text": "c:", + "position": 289, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo4(1, +1, -1, +"1"); + ^ +{ + "text": "d:", + "position": 293, + "kind": "Parameter", + "whitespaceAfter": true +} + + "hello", + ^ +{ + "text": "a:", + "position": 484, + "kind": "Parameter", + "whitespaceAfter": true +} + + undefined, + ^ +{ + "text": "b:", + "position": 497, + "kind": "Parameter", + "whitespaceAfter": true +} + + null, + ^ +{ + "text": "c:", + "position": 512, + "kind": "Parameter", + "whitespaceAfter": true +} + + true, + ^ +{ + "text": "d:", + "position": 522, + "kind": "Parameter", + "whitespaceAfter": true +} + + false, + ^ +{ + "text": "e:", + "position": 532, + "kind": "Parameter", + "whitespaceAfter": true +} + + Infinity, + ^ +{ + "text": "f:", + "position": 543, + "kind": "Parameter", + "whitespaceAfter": true +} + + -Infinity, + ^ +{ + "text": "g:", + "position": 557, + "kind": "Parameter", + "whitespaceAfter": true +} + + NaN, + ^ +{ + "text": "h:", + "position": 572, + "kind": "Parameter", + "whitespaceAfter": true +} + + /hello/g, + ^ +{ + "text": "i:", + "position": 581, + "kind": "Parameter", + "whitespaceAfter": true +} + + 123n, + ^ +{ + "text": "j:", + "position": 595, + "kind": "Parameter", + "whitespaceAfter": true +} + +trace(`${1}`); + ^ +{ + "text": "message:", + "position": 694, + "kind": "Parameter", + "whitespaceAfter": true +} + +trace(``); + ^ +{ + "text": "message:", + "position": 709, + "kind": "Parameter", + "whitespaceAfter": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsParameterNamesInSpan1.baseline b/tests/baselines/reference/inlayHintsParameterNamesInSpan1.baseline new file mode 100644 index 0000000000000..888d50fcb5fc0 --- /dev/null +++ b/tests/baselines/reference/inlayHintsParameterNamesInSpan1.baseline @@ -0,0 +1,53 @@ +function c2 () { foo2(1, 2); } + ^ +{ + "text": "c:", + "position": 293, + "kind": "Parameter", + "whitespaceAfter": true +} + +function c2 () { foo2(1, 2); } + ^ +{ + "text": "d:", + "position": 296, + "kind": "Parameter", + "whitespaceAfter": true +} + +function c3 () { foo3(1, 2); } + ^ +{ + "text": "e:", + "position": 324, + "kind": "Parameter", + "whitespaceAfter": true +} + +function c3 () { foo3(1, 2); } + ^ +{ + "text": "f:", + "position": 327, + "kind": "Parameter", + "whitespaceAfter": true +} + +function c4 () { foo4(1, 2); } + ^ +{ + "text": "g:", + "position": 355, + "kind": "Parameter", + "whitespaceAfter": true +} + +function c4 () { foo4(1, 2); } + ^ +{ + "text": "h:", + "position": 358, + "kind": "Parameter", + "whitespaceAfter": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsParameterNamesInSpan2.baseline b/tests/baselines/reference/inlayHintsParameterNamesInSpan2.baseline new file mode 100644 index 0000000000000..f0484d4044d46 --- /dev/null +++ b/tests/baselines/reference/inlayHintsParameterNamesInSpan2.baseline @@ -0,0 +1,53 @@ +foo2(1, 2); + ^ +{ + "text": "c:", + "position": 257, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo2(1, 2); + ^ +{ + "text": "d:", + "position": 260, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo3(1, 2); + ^ +{ + "text": "e:", + "position": 269, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo3(1, 2); + ^ +{ + "text": "f:", + "position": 272, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo4(1, 2); + ^ +{ + "text": "g:", + "position": 281, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo4(1, 2); + ^ +{ + "text": "h:", + "position": 284, + "kind": "Parameter", + "whitespaceAfter": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork37.baseline b/tests/baselines/reference/inlayHintsPropertyDeclarations.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork37.baseline rename to tests/baselines/reference/inlayHintsPropertyDeclarations.baseline diff --git a/tests/baselines/reference/inlayHintsRestParameters1.baseline b/tests/baselines/reference/inlayHintsRestParameters1.baseline new file mode 100644 index 0000000000000..ee07967f75d1e --- /dev/null +++ b/tests/baselines/reference/inlayHintsRestParameters1.baseline @@ -0,0 +1,53 @@ +foo1(1, 1, 1, 1); + ^ +{ + "text": "a:", + "position": 49, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo1(1, 1, 1, 1); + ^ +{ + "text": "...b:", + "position": 52, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo2(1, 2, 3) + ^ +{ + "text": "c:", + "position": 153, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo2(1, 2, 3) + ^ +{ + "text": "a:", + "position": 156, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo2(1, 2, 3) + ^ +{ + "text": "b:", + "position": 159, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo3(1, 2, 3) + ^ +{ + "text": "c:", + "position": 247, + "kind": "Parameter", + "whitespaceAfter": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsRestParameters2.baseline b/tests/baselines/reference/inlayHintsRestParameters2.baseline new file mode 100644 index 0000000000000..79c2a63f63c25 --- /dev/null +++ b/tests/baselines/reference/inlayHintsRestParameters2.baseline @@ -0,0 +1,98 @@ + foo(...x, 3); + ^ +{ + "text": "a:", + "position": 113, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(...x, 3); + ^ +{ + "text": "c:", + "position": 119, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(...x, 1, 2, 3); + ^ +{ + "text": "a:", + "position": 165, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(...x, 1, 2, 3); + ^ +{ + "text": "b:", + "position": 168, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(...x, 1, 2, 3); + ^ +{ + "text": "c:", + "position": 171, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(1, ...x); + ^ +{ + "text": "a:", + "position": 226, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(1, ...x); + ^ +{ + "text": "b:", + "position": 229, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(...x, 3); + ^ +{ + "text": "a:", + "position": 287, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(...x, 3); + ^ +{ + "text": "b:", + "position": 293, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(...x, 3); + ^ +{ + "text": "a:", + "position": 347, + "kind": "Parameter", + "whitespaceAfter": true +} + + foo(...x, 3); + ^ +{ + "text": "c:", + "position": 353, + "kind": "Parameter", + "whitespaceAfter": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsReturnType.baseline b/tests/baselines/reference/inlayHintsReturnType.baseline new file mode 100644 index 0000000000000..1a17fa507217e --- /dev/null +++ b/tests/baselines/reference/inlayHintsReturnType.baseline @@ -0,0 +1,44 @@ +function foo1 () { + ^ +{ + "text": ": number", + "position": 16, + "kind": "Type", + "whitespaceBefore": true +} + + foo() { + ^ +{ + "text": ": number", + "position": 95, + "kind": "Type", + "whitespaceBefore": true +} + +const a = () => 1 + ^ +{ + "text": ": number", + "position": 135, + "kind": "Type", + "whitespaceBefore": true +} + +const b = function () { return 1 } + ^ +{ + "text": ": number", + "position": 162, + "kind": "Type", + "whitespaceBefore": true +} + +const c = (b) => 1 + ^ +{ + "text": ": number", + "position": 189, + "kind": "Type", + "whitespaceBefore": true +} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork1.baseline b/tests/baselines/reference/inlayHintsShouldWork1.baseline deleted file mode 100644 index a4ca2e72691ce..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork1.baseline +++ /dev/null @@ -1,43 +0,0 @@ -foo(1, 2); - ^ -{ - "text": "", - "position": 43, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 14, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork1.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, 2); - ^ -{ - "text": "", - "position": 46, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 25, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork1.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork11.baseline b/tests/baselines/reference/inlayHintsShouldWork11.baseline deleted file mode 100644 index 4253e6175a250..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork11.baseline +++ /dev/null @@ -1,43 +0,0 @@ -foo(1)(2); - ^ -{ - "text": "", - "position": 87, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 13, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork11.ts" - }, - { - "text": ":" - } - ] -} - -foo(1)(2); - ^ -{ - "text": "", - "position": 90, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 38, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork11.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork12.baseline b/tests/baselines/reference/inlayHintsShouldWork12.baseline deleted file mode 100644 index 8610811799358..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork12.baseline +++ /dev/null @@ -1,43 +0,0 @@ - return a(1) + 2 - ^ -{ - "text": "", - "position": 54, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 17, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork12.ts" - }, - { - "text": ":" - } - ] -} - -foo((c: number) => c + 1); - ^ -{ - "text": "", - "position": 67, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 13, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork12.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork13.baseline b/tests/baselines/reference/inlayHintsShouldWork13.baseline deleted file mode 100644 index 425f8294f6aa4..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork13.baseline +++ /dev/null @@ -1,21 +0,0 @@ -foo(a, 2); - ^ -{ - "text": "", - "position": 66, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 25, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork13.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork2.baseline b/tests/baselines/reference/inlayHintsShouldWork2.baseline deleted file mode 100644 index 0b4274fc30dbc..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork2.baseline +++ /dev/null @@ -1,21 +0,0 @@ -foo(1, { c: 1 }); - ^ -{ - "text": "", - "position": 44, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 14, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork2.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork21.baseline b/tests/baselines/reference/inlayHintsShouldWork21.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork21.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork22.baseline b/tests/baselines/reference/inlayHintsShouldWork22.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork22.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork24.baseline b/tests/baselines/reference/inlayHintsShouldWork24.baseline deleted file mode 100644 index eb17c4ad027f0..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork24.baseline +++ /dev/null @@ -1,17 +0,0 @@ -const f: F = (a, b) => { } - ^ -{ - "text": ": string", - "position": 55, - "kind": "Type", - "whitespaceBefore": true -} - -const f: F = (a, b) => { } - ^ -{ - "text": ": number", - "position": 58, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork25.baseline b/tests/baselines/reference/inlayHintsShouldWork25.baseline deleted file mode 100644 index d9161dfdccf03..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork25.baseline +++ /dev/null @@ -1,8 +0,0 @@ -foo((a) => { }) - ^ -{ - "text": ": string", - "position": 48, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork26.baseline b/tests/baselines/reference/inlayHintsShouldWork26.baseline deleted file mode 100644 index d2ef8170b62e3..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork26.baseline +++ /dev/null @@ -1,8 +0,0 @@ -foo((a) => { }) - ^ -{ - "text": ": 2 | 3", - "position": 63, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork27.baseline b/tests/baselines/reference/inlayHintsShouldWork27.baseline deleted file mode 100644 index f9dc800b3837e..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork27.baseline +++ /dev/null @@ -1,17 +0,0 @@ -foo(a => { - ^ -{ - "text": ": (c: (d: 2 | 3) => void) => ...", - "position": 87, - "kind": "Type", - "whitespaceBefore": true -} - - a(d => {}) - ^ -{ - "text": ": 2 | 3", - "position": 100, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork28.baseline b/tests/baselines/reference/inlayHintsShouldWork28.baseline deleted file mode 100644 index f0fc32c8e5655..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork28.baseline +++ /dev/null @@ -1,8 +0,0 @@ -const f: F = (a, b: number) => { } - ^ -{ - "text": ": string", - "position": 55, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork29.baseline b/tests/baselines/reference/inlayHintsShouldWork29.baseline deleted file mode 100644 index 8e2ad45030f9a..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork29.baseline +++ /dev/null @@ -1,35 +0,0 @@ -foo(a => { - ^ -{ - "text": "a:", - "position": 86, - "kind": "Parameter", - "whitespaceAfter": true -} - -foo(a => { - ^ -{ - "text": ": (c: (d: 2 | 3) => void) => ...", - "position": 87, - "kind": "Type", - "whitespaceBefore": true -} - - a(d => {}) - ^ -{ - "text": "c:", - "position": 99, - "kind": "Parameter", - "whitespaceAfter": true -} - - a(d => {}) - ^ -{ - "text": ": 2 | 3", - "position": 100, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork3.baseline b/tests/baselines/reference/inlayHintsShouldWork3.baseline deleted file mode 100644 index ea3e49735de65..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork3.baseline +++ /dev/null @@ -1,43 +0,0 @@ -foo(1, 1, 1, 1); - ^ -{ - "text": "", - "position": 48, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 14, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork3.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, 1, 1, 1); - ^ -{ - "text": "", - "position": 51, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "...b", - "span": { - "start": 28, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork3.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork30.baseline b/tests/baselines/reference/inlayHintsShouldWork30.baseline deleted file mode 100644 index 020b289310881..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork30.baseline +++ /dev/null @@ -1,8 +0,0 @@ -f(1, a => { }) - ^ -{ - "text": ": number", - "position": 48, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork31.baseline b/tests/baselines/reference/inlayHintsShouldWork31.baseline deleted file mode 100644 index 72ab45d03ae5b..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork31.baseline +++ /dev/null @@ -1,8 +0,0 @@ -const f: F = (a) => { } - ^ -{ - "text": ": { a: number; b: string; }", - "position": 69, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork36.baseline b/tests/baselines/reference/inlayHintsShouldWork36.baseline deleted file mode 100644 index d9e2b88aac5c3..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork36.baseline +++ /dev/null @@ -1,43 +0,0 @@ -foo(a, 2); - ^ -{ - "text": "", - "position": 63, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 14, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork36.ts" - }, - { - "text": ":" - } - ] -} - -foo(a, 2); - ^ -{ - "text": "", - "position": 66, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 25, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork36.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork38.baseline b/tests/baselines/reference/inlayHintsShouldWork38.baseline deleted file mode 100644 index 7ac6427df2f74..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork38.baseline +++ /dev/null @@ -1,8 +0,0 @@ -function foo () { - ^ -{ - "text": ": number", - "position": 15, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork39.baseline b/tests/baselines/reference/inlayHintsShouldWork39.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork39.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork4.baseline b/tests/baselines/reference/inlayHintsShouldWork4.baseline deleted file mode 100644 index c5b93f778b123..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork4.baseline +++ /dev/null @@ -1,65 +0,0 @@ -foo(1) - ^ -{ - "text": "", - "position": 166, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "w", - "span": { - "start": 21, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork4.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, 2) - ^ -{ - "text": "", - "position": 173, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 59, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork4.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, 2) - ^ -{ - "text": "", - "position": 176, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 70, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork4.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork40.baseline b/tests/baselines/reference/inlayHintsShouldWork40.baseline deleted file mode 100644 index cbc03446ba713..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork40.baseline +++ /dev/null @@ -1,8 +0,0 @@ - foo() { - ^ -{ - "text": ": number", - "position": 19, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork41.baseline b/tests/baselines/reference/inlayHintsShouldWork41.baseline deleted file mode 100644 index 78e6bb608dd2f..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork41.baseline +++ /dev/null @@ -1,8 +0,0 @@ -const a = () => 1 - ^ -{ - "text": ": number", - "position": 12, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork42.baseline b/tests/baselines/reference/inlayHintsShouldWork42.baseline deleted file mode 100644 index abe025f3032a9..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork42.baseline +++ /dev/null @@ -1,8 +0,0 @@ -const a = function () { return 1} - ^ -{ - "text": ": number", - "position": 21, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork43.baseline b/tests/baselines/reference/inlayHintsShouldWork43.baseline deleted file mode 100644 index 6bf0ef3fe56c4..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork43.baseline +++ /dev/null @@ -1,8 +0,0 @@ -const a = (b) => 1 - ^ -{ - "text": ": number", - "position": 13, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork45.baseline b/tests/baselines/reference/inlayHintsShouldWork45.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork45.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork48.baseline b/tests/baselines/reference/inlayHintsShouldWork48.baseline deleted file mode 100644 index da8af02454fbb..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork48.baseline +++ /dev/null @@ -1,8 +0,0 @@ -const x = foo(1) - ^ -{ - "text": ": 1", - "position": 55, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork49.baseline b/tests/baselines/reference/inlayHintsShouldWork49.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork49.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork5.baseline b/tests/baselines/reference/inlayHintsShouldWork5.baseline deleted file mode 100644 index 40fd6eab8dede..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork5.baseline +++ /dev/null @@ -1,65 +0,0 @@ -foo(1, 2, 3) - ^ -{ - "text": "", - "position": 87, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "c", - "span": { - "start": 56, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork5.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, 2, 3) - ^ -{ - "text": "", - "position": 90, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 13, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork5.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, 2, 3) - ^ -{ - "text": "", - "position": 93, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 24, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork5.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork53.baseline b/tests/baselines/reference/inlayHintsShouldWork53.baseline deleted file mode 100644 index 9c090239a9956..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork53.baseline +++ /dev/null @@ -1,21 +0,0 @@ -fn(/* nobody knows exactly what this param is */ 42); - ^ -{ - "text": "", - "position": 76, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "x", - "span": { - "start": 12, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork53.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork55.baseline b/tests/baselines/reference/inlayHintsShouldWork55.baseline deleted file mode 100644 index 9920c18238b50..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork55.baseline +++ /dev/null @@ -1,8 +0,0 @@ - get foo() { return 1; } - ^ -{ - "text": ": number", - "position": 25, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork57.baseline b/tests/baselines/reference/inlayHintsShouldWork57.baseline deleted file mode 100644 index 544dd4e8d35bb..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork57.baseline +++ /dev/null @@ -1,8 +0,0 @@ - set foo(value) { this.#value = value; } - ^ -{ - "text": ": number", - "position": 91, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork58.baseline b/tests/baselines/reference/inlayHintsShouldWork58.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork58.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork59.baseline b/tests/baselines/reference/inlayHintsShouldWork59.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork59.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork6.baseline b/tests/baselines/reference/inlayHintsShouldWork6.baseline deleted file mode 100644 index 3f8bbed8692c9..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork6.baseline +++ /dev/null @@ -1,21 +0,0 @@ -foo(1, 2, 3) - ^ -{ - "text": "", - "position": 81, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "c", - "span": { - "start": 50, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork6.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork60.baseline b/tests/baselines/reference/inlayHintsShouldWork60.baseline deleted file mode 100644 index 04fd07380ba82..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork60.baseline +++ /dev/null @@ -1,8 +0,0 @@ - set foo(value) { this.#value = value; } - ^ -{ - "text": ": number", - "position": 83, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork61.baseline b/tests/baselines/reference/inlayHintsShouldWork61.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork61.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork62.baseline b/tests/baselines/reference/inlayHintsShouldWork62.baseline deleted file mode 100644 index 3f8f62af0d31f..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork62.baseline +++ /dev/null @@ -1,43 +0,0 @@ -trace(`${1}`); - ^ -{ - "text": "", - "position": 41, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "message", - "span": { - "start": 15, - "length": 7 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork62.ts" - }, - { - "text": ":" - } - ] -} - -trace(``); - ^ -{ - "text": "", - "position": 56, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "message", - "span": { - "start": 15, - "length": 7 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork62.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork63.baseline b/tests/baselines/reference/inlayHintsShouldWork63.baseline deleted file mode 100644 index 674c1e4aea5c4..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork63.baseline +++ /dev/null @@ -1,87 +0,0 @@ -foo(1, +1, -1, +"1"); - ^ -{ - "text": "", - "position": 64, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 13, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork63.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, +1, -1, +"1"); - ^ -{ - "text": "", - "position": 67, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 24, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork63.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, +1, -1, +"1"); - ^ -{ - "text": "", - "position": 71, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "c", - "span": { - "start": 35, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork63.ts" - }, - { - "text": ":" - } - ] -} - -foo(1, +1, -1, +"1"); - ^ -{ - "text": "", - "position": 75, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "d", - "span": { - "start": 46, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork63.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork65.baseline b/tests/baselines/reference/inlayHintsShouldWork65.baseline deleted file mode 100644 index 458efc55a111d..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork65.baseline +++ /dev/null @@ -1,8 +0,0 @@ -const f: F = (a, b = 1) => { } - ^ -{ - "text": ": string", - "position": 55, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork66.baseline b/tests/baselines/reference/inlayHintsShouldWork66.baseline deleted file mode 100644 index a0bd945548d0d..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork66.baseline +++ /dev/null @@ -1,8 +0,0 @@ - bar: function (x?): void { - ^ -{ - "text": ": boolean", - "position": 87, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork67.baseline b/tests/baselines/reference/inlayHintsShouldWork67.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork67.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork68.baseline b/tests/baselines/reference/inlayHintsShouldWork68.baseline deleted file mode 100644 index 32b0560b803ca..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork68.baseline +++ /dev/null @@ -1,43 +0,0 @@ -const C1 = class extends foo(1) { } - ^ -{ - "text": "", - "position": 63, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 13, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork68.ts" - }, - { - "text": ":" - } - ] -} - -class C2 extends foo(1) { } - ^ -{ - "text": "", - "position": 91, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 13, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork68.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork69.baseline b/tests/baselines/reference/inlayHintsShouldWork69.baseline deleted file mode 100644 index 6136dbb8025a6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork69.baseline +++ /dev/null @@ -1 +0,0 @@ -=== No inlay hints === \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork7.baseline b/tests/baselines/reference/inlayHintsShouldWork7.baseline deleted file mode 100644 index 17d74b5d61cff..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork7.baseline +++ /dev/null @@ -1,65 +0,0 @@ -call(1); - ^ -{ - "text": "", - "position": 105, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 22, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork7.ts" - }, - { - "text": ":" - } - ] -} - -call(1, 2); - ^ -{ - "text": "", - "position": 114, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 44, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork7.ts" - }, - { - "text": ":" - } - ] -} - -call(1, 2); - ^ -{ - "text": "", - "position": 117, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "c", - "span": { - "start": 55, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork7.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork70.baseline b/tests/baselines/reference/inlayHintsShouldWork70.baseline deleted file mode 100644 index de71ef08ed62c..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork70.baseline +++ /dev/null @@ -1,17 +0,0 @@ - foo(...x, 3); - ^ -{ - "text": "a:", - "position": 100, - "kind": "Parameter", - "whitespaceAfter": true -} - - foo(...x, 3); - ^ -{ - "text": "c:", - "position": 106, - "kind": "Parameter", - "whitespaceAfter": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork71.baseline b/tests/baselines/reference/inlayHintsShouldWork71.baseline deleted file mode 100644 index f51373d5aaa8d..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork71.baseline +++ /dev/null @@ -1,17 +0,0 @@ - foo(...x, 3); - ^ -{ - "text": "a:", - "position": 120, - "kind": "Parameter", - "whitespaceAfter": true -} - - foo(...x, 3); - ^ -{ - "text": "d:", - "position": 126, - "kind": "Parameter", - "whitespaceAfter": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork72.baseline b/tests/baselines/reference/inlayHintsShouldWork72.baseline deleted file mode 100644 index 6b82bf61fe6d9..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork72.baseline +++ /dev/null @@ -1,17 +0,0 @@ - foo(...x, 3); - ^ -{ - "text": "a:", - "position": 101, - "kind": "Parameter", - "whitespaceAfter": true -} - - foo(...x, 3); - ^ -{ - "text": "b:", - "position": 107, - "kind": "Parameter", - "whitespaceAfter": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork73.baseline b/tests/baselines/reference/inlayHintsShouldWork73.baseline deleted file mode 100644 index 6b76be453b4cf..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork73.baseline +++ /dev/null @@ -1,17 +0,0 @@ - foo(1, ...x); - ^ -{ - "text": "a:", - "position": 101, - "kind": "Parameter", - "whitespaceAfter": true -} - - foo(1, ...x); - ^ -{ - "text": "b:", - "position": 104, - "kind": "Parameter", - "whitespaceAfter": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork74.baseline b/tests/baselines/reference/inlayHintsShouldWork74.baseline deleted file mode 100644 index e40d98f3ab4a0..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork74.baseline +++ /dev/null @@ -1,17 +0,0 @@ - foo(...x, 3); - ^ -{ - "text": "a:", - "position": 112, - "kind": "Parameter", - "whitespaceAfter": true -} - - foo(...x, 3); - ^ -{ - "text": "c:", - "position": 118, - "kind": "Parameter", - "whitespaceAfter": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork75.baseline b/tests/baselines/reference/inlayHintsShouldWork75.baseline deleted file mode 100644 index 97e0bea06a6a9..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork75.baseline +++ /dev/null @@ -1,26 +0,0 @@ - foo(...x, 1, 2, 3); - ^ -{ - "text": "a:", - "position": 92, - "kind": "Parameter", - "whitespaceAfter": true -} - - foo(...x, 1, 2, 3); - ^ -{ - "text": "b:", - "position": 95, - "kind": "Parameter", - "whitespaceAfter": true -} - - foo(...x, 1, 2, 3); - ^ -{ - "text": "c:", - "position": 98, - "kind": "Parameter", - "whitespaceAfter": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork76.baseline b/tests/baselines/reference/inlayHintsShouldWork76.baseline deleted file mode 100644 index 2ff1056ce72c6..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork76.baseline +++ /dev/null @@ -1,8 +0,0 @@ - foo(...x, 1); - ^ -{ - "text": "d:", - "position": 152, - "kind": "Parameter", - "whitespaceAfter": true -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork8.baseline b/tests/baselines/reference/inlayHintsShouldWork8.baseline deleted file mode 100644 index f7cb28571a277..0000000000000 --- a/tests/baselines/reference/inlayHintsShouldWork8.baseline +++ /dev/null @@ -1,65 +0,0 @@ -new Class(1) - ^ -{ - "text": "", - "position": 136, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "a", - "span": { - "start": 30, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork8.ts" - }, - { - "text": ":" - } - ] -} - -new Class(1, 2) - ^ -{ - "text": "", - "position": 149, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "b", - "span": { - "start": 58, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork8.ts" - }, - { - "text": ":" - } - ] -} - -new Class(1, 2) - ^ -{ - "text": "", - "position": 152, - "kind": "Parameter", - "whitespaceAfter": true, - "displayParts": [ - { - "text": "c", - "span": { - "start": 69, - "length": 1 - }, - "file": "/tests/cases/fourslash/inlayHintsShouldWork8.ts" - }, - { - "text": ":" - } - ] -} \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork20.baseline b/tests/baselines/reference/inlayHintsTypeMatchesName.baseline similarity index 100% rename from tests/baselines/reference/inlayHintsShouldWork20.baseline rename to tests/baselines/reference/inlayHintsTypeMatchesName.baseline diff --git a/tests/baselines/reference/inlayHintsShouldWork19.baseline b/tests/baselines/reference/inlayHintsVariableTypes1.baseline similarity index 59% rename from tests/baselines/reference/inlayHintsShouldWork19.baseline rename to tests/baselines/reference/inlayHintsVariableTypes1.baseline index 133fdf288bbf9..6cea19f330cc0 100644 --- a/tests/baselines/reference/inlayHintsShouldWork19.baseline +++ b/tests/baselines/reference/inlayHintsVariableTypes1.baseline @@ -1,8 +1,8 @@ -const a = () => 123; - ^ + const m = () => 123; + ^ { "text": ": () => number", - "position": 7, + "position": 331, "kind": "Type", "whitespaceBefore": true } \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsShouldWork56.baseline b/tests/baselines/reference/inlayHintsVariableTypes2.baseline similarity index 77% rename from tests/baselines/reference/inlayHintsShouldWork56.baseline rename to tests/baselines/reference/inlayHintsVariableTypes2.baseline index 0c1dd18626dcb..ff04dbe0e59cb 100644 --- a/tests/baselines/reference/inlayHintsShouldWork56.baseline +++ b/tests/baselines/reference/inlayHintsVariableTypes2.baseline @@ -23,4 +23,13 @@ const b = array; "position": 128, "kind": "Type", "whitespaceBefore": true +} + +const x = foo(1) + ^ +{ + "text": ": 1", + "position": 244, + "kind": "Type", + "whitespaceBefore": true } \ No newline at end of file diff --git a/tests/baselines/reference/inlayHintsWithClosures.baseline b/tests/baselines/reference/inlayHintsWithClosures.baseline new file mode 100644 index 0000000000000..4b2eade08442c --- /dev/null +++ b/tests/baselines/reference/inlayHintsWithClosures.baseline @@ -0,0 +1,35 @@ +foo1(1)(2); + ^ +{ + "text": "a:", + "position": 89, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo1(1)(2); + ^ +{ + "text": "b:", + "position": 92, + "kind": "Parameter", + "whitespaceAfter": true +} + + return a(1) + 2 + ^ +{ + "text": "b:", + "position": 151, + "kind": "Parameter", + "whitespaceAfter": true +} + +foo2((c: number) => c + 1); + ^ +{ + "text": "a:", + "position": 165, + "kind": "Parameter", + "whitespaceAfter": true +} \ No newline at end of file diff --git a/tests/cases/fourslash/inlayHintsShouldWork44.ts b/tests/cases/fourslash/inlayHintsEnumMemberValue.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork44.ts rename to tests/cases/fourslash/inlayHintsEnumMemberValue.ts diff --git a/tests/cases/fourslash/inlayHintsFunctionParameterTypes1.ts b/tests/cases/fourslash/inlayHintsFunctionParameterTypes1.ts new file mode 100644 index 0000000000000..8057fe0265bc3 --- /dev/null +++ b/tests/cases/fourslash/inlayHintsFunctionParameterTypes1.ts @@ -0,0 +1,29 @@ +/// + +//// type F1 = (a: string, b: number) => void +//// const f1: F1 = (a, b) => { } +//// const f2: F1 = (a, b: number) => { } + +//// function foo1 (cb: (a: string) => void) {} +//// foo1((a) => { }) + +//// function foo2 (cb: (a: Exclude<1 | 2 | 3, 1>) => void) {} +//// foo2((a) => { }) + +//// function foo3 (a: (b: (c: (d: Exclude<1 | 2 | 3, 1>) => void) => void) => void) {} +//// foo3(a => { +//// a(d => {}) +//// }) + +//// function foo4(v: T, a: (v: T) => void) {} +//// foo4(1, a => { }) + +//// type F2 = (a: { +//// a: number +//// b: string +//// }) => void +//// const foo5: F2 = (a) => { } + +verify.baselineInlayHints(undefined, { + includeInlayFunctionParameterTypeHints: true +}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork69.ts b/tests/cases/fourslash/inlayHintsFunctionParameterTypes2.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork69.ts rename to tests/cases/fourslash/inlayHintsFunctionParameterTypes2.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork66.ts b/tests/cases/fourslash/inlayHintsFunctionParameterTypes3.ts similarity index 66% rename from tests/cases/fourslash/inlayHintsShouldWork66.ts rename to tests/cases/fourslash/inlayHintsFunctionParameterTypes3.ts index 52f0eef1ba011..9254e4a3591b3 100644 --- a/tests/cases/fourslash/inlayHintsShouldWork66.ts +++ b/tests/cases/fourslash/inlayHintsFunctionParameterTypes3.ts @@ -10,6 +10,12 @@ //// } ////} +////class Foo { +//// #value = 0; +//// get foo(): number { return this.#value; } +//// set foo(value) { this.#value = value; } +////} + verify.baselineInlayHints(undefined, { includeInlayFunctionParameterTypeHints: true }); diff --git a/tests/cases/fourslash/inlayHintsShouldWork59.ts b/tests/cases/fourslash/inlayHintsFunctionParameterTypes4.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork59.ts rename to tests/cases/fourslash/inlayHintsFunctionParameterTypes4.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork45.ts b/tests/cases/fourslash/inlayHintsImportType1.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork45.ts rename to tests/cases/fourslash/inlayHintsImportType1.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork46.ts b/tests/cases/fourslash/inlayHintsImportType2.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork46.ts rename to tests/cases/fourslash/inlayHintsImportType2.ts diff --git a/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts b/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts new file mode 100644 index 0000000000000..fb2ad2c584ac1 --- /dev/null +++ b/tests/cases/fourslash/inlayHintsInteractiveOverloadCall.ts @@ -0,0 +1,30 @@ +/// + +//// interface Call { +//// (a: number): void +//// (b: number, c: number): void +//// new (d: number): Call +//// } +//// declare const call: Call; +//// call(1); +//// call(1, 2); +//// new call(1); + +//// declare function foo(w: number): void +//// declare function foo(a: number, b: number): void; +//// declare function foo(a: number | undefined, b: number | undefined): void; +//// foo(1) +//// foo(1, 2) + +//// class Class { +//// constructor(a: number); +//// constructor(b: number, c: number); +//// constructor(b: number, c?: number) { } +//// } +//// new Class(1) +//// new Class(1, 2) + +verify.baselineInlayHints(undefined, { + includeInlayParameterNameHints: "literals", + interactiveInlayHints: true +}); diff --git a/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts b/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts new file mode 100644 index 0000000000000..e8f8dd855fba0 --- /dev/null +++ b/tests/cases/fourslash/inlayHintsInteractiveParameterNames.ts @@ -0,0 +1,49 @@ +/// + +//// function foo1 (a: number, b: number) {} +//// foo1(1, 2); + +//// function foo2 (a: number, { c }: any) {} +//// foo2(1, { c: 1 }); + +////const foo3 = (a = 1) => class { } +////const C1 = class extends foo3(1) { } +////class C2 extends foo3(1) { } + +////function foo4(a: number, b: number, c: number, d: number) {} +////foo4(1, +1, -1, +"1"); + +////function foo5( +//// a: string, +//// b: undefined, +//// c: null, +//// d: boolean, +//// e: boolean, +//// f: number, +//// g: number, +//// h: number, +//// i: RegExp, +//// j: bigint, +////) { +////} +////foo5( +//// "hello", +//// undefined, +//// null, +//// true, +//// false, +//// Infinity, +//// -Infinity, +//// NaN, +//// /hello/g, +//// 123n, +////); + +//// declare const unknownCall: any; +//// unknownCall(); + +////function trace(message: string) {} +////trace(`${1}`); +////trace(``); + +verify.baselineInlayHints(undefined, { includeInlayParameterNameHints: "literals", interactiveInlayHints: true }); diff --git a/tests/cases/fourslash/inlayHintsShouldWork32.ts b/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan1.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork32.ts rename to tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan1.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork33.ts b/tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan2.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork33.ts rename to tests/cases/fourslash/inlayHintsInteractiveParameterNamesInSpan2.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork52.ts b/tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts similarity index 84% rename from tests/cases/fourslash/inlayHintsShouldWork52.ts rename to tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts index 0da52a56cd562..0c26ecb595027 100644 --- a/tests/cases/fourslash/inlayHintsShouldWork52.ts +++ b/tests/cases/fourslash/inlayHintsInteractiveParameterNamesWithComments.ts @@ -1,5 +1,8 @@ /// +//// const fn = (x: any) => { } +//// fn(/* nobody knows exactly what this param is */ 42); + //// function foo (aParameter: number, bParameter: number, cParameter: number) { } //// foo( @@ -35,6 +38,5 @@ verify.baselineInlayHints(undefined, { includeInlayParameterNameHints: "literals", - includeInlayFunctionLikeReturnTypeHints: true, interactiveInlayHints: true }); diff --git a/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts b/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts new file mode 100644 index 0000000000000..c65514372f09f --- /dev/null +++ b/tests/cases/fourslash/inlayHintsInteractiveRestParameters1.ts @@ -0,0 +1,14 @@ +/// + +//// function foo1(a: number, ...b: number[]) {} +//// foo1(1, 1, 1, 1); + +//// type Args2 = [a: number, b: number] +//// declare function foo2(c: number, ...args: Args2); +//// foo2(1, 2, 3) + +//// type Args3 = [number, number] +//// declare function foo3(c: number, ...args: Args3); +//// foo3(1, 2, 3) + +verify.baselineInlayHints(undefined, { includeInlayParameterNameHints: "literals", interactiveInlayHints: true }); diff --git a/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts b/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts new file mode 100644 index 0000000000000..6df4c91c7481b --- /dev/null +++ b/tests/cases/fourslash/inlayHintsInteractiveRestParameters2.ts @@ -0,0 +1,23 @@ +/// + +////function foo(a: unknown, b: unknown, c: unknown) { } +////function foo1(...x: [number, number | undefined]) { +//// foo(...x, 3); +////} +////function foo2(...x: []) { +//// foo(...x, 1, 2, 3); +////} +////function foo3(...x: [number, number?]) { +//// foo(1, ...x); +////} +////function foo4(...x: [number, number?]) { +//// foo(...x, 3); +////} +////function foo5(...x: [number, number]) { +//// foo(...x, 3); +////} + +verify.baselineInlayHints(undefined, { + includeInlayParameterNameHints: "all", + interactiveInlayHints: true, +}); diff --git a/tests/cases/fourslash/inlayHintsInteractiveWithClosures.ts b/tests/cases/fourslash/inlayHintsInteractiveWithClosures.ts new file mode 100644 index 0000000000000..e09cdbc980340 --- /dev/null +++ b/tests/cases/fourslash/inlayHintsInteractiveWithClosures.ts @@ -0,0 +1,18 @@ +/// + +//// function foo1(a: number) { +//// return (b: number) => { +//// return a + b +//// } +//// } +//// foo1(1)(2); + +//// function foo2(a: (b: number) => number) { +//// return a(1) + 2 +//// } +//// foo2((c: number) => c + 1); + +verify.baselineInlayHints(undefined, { + includeInlayParameterNameHints: "all", + interactiveInlayHints: true +}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork34.ts b/tests/cases/fourslash/inlayHintsInterativeAnyParameter1.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork34.ts rename to tests/cases/fourslash/inlayHintsInterativeAnyParameter1.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork35.ts b/tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork35.ts rename to tests/cases/fourslash/inlayHintsInterativeAnyParameter2.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork47.ts b/tests/cases/fourslash/inlayHintsJsDocParameterNames.ts similarity index 80% rename from tests/cases/fourslash/inlayHintsShouldWork47.ts rename to tests/cases/fourslash/inlayHintsJsDocParameterNames.ts index 8bfb526bf2bae..5e7676d239501 100644 --- a/tests/cases/fourslash/inlayHintsShouldWork47.ts +++ b/tests/cases/fourslash/inlayHintsJsDocParameterNames.ts @@ -13,6 +13,11 @@ //// var y //// y.foo(1, 2) +//// /** +//// * @type {string} +//// */ +//// var z = "" + goTo.file('/a.js') verify.baselineInlayHints(undefined, { includeInlayParameterNameHints: "literals" diff --git a/tests/cases/fourslash/inlayHintsShouldWork51.ts b/tests/cases/fourslash/inlayHintsMultifile1.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork51.ts rename to tests/cases/fourslash/inlayHintsMultifile1.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork54.ts b/tests/cases/fourslash/inlayHintsNoHintWhenArgumentMatchesName.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork54.ts rename to tests/cases/fourslash/inlayHintsNoHintWhenArgumentMatchesName.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork14.ts b/tests/cases/fourslash/inlayHintsNoParameterHints.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork14.ts rename to tests/cases/fourslash/inlayHintsNoParameterHints.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork20.ts b/tests/cases/fourslash/inlayHintsNoVariableTypeHints.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork20.ts rename to tests/cases/fourslash/inlayHintsNoVariableTypeHints.ts diff --git a/tests/cases/fourslash/inlayHintsOverloadCall.ts b/tests/cases/fourslash/inlayHintsOverloadCall.ts new file mode 100644 index 0000000000000..da2d231669d4b --- /dev/null +++ b/tests/cases/fourslash/inlayHintsOverloadCall.ts @@ -0,0 +1,30 @@ + +/// + +//// interface Call { +//// (a: number): void +//// (b: number, c: number): void +//// new (d: number): Call +//// } +//// declare const call: Call; +//// call(1); +//// call(1, 2); +//// new call(1); + +//// declare function foo(w: number): void +//// declare function foo(a: number, b: number): void; +//// declare function foo(a: number | undefined, b: number | undefined): void; +//// foo(1) +//// foo(1, 2) + +//// class Class { +//// constructor(a: number); +//// constructor(b: number, c: number); +//// constructor(b: number, c?: number) { } +//// } +//// new Class(1) +//// new Class(1, 2) + +verify.baselineInlayHints(undefined, { + includeInlayParameterNameHints: "literals", +}); diff --git a/tests/cases/fourslash/inlayHintsParameterNames.ts b/tests/cases/fourslash/inlayHintsParameterNames.ts new file mode 100644 index 0000000000000..abcea666a37e1 --- /dev/null +++ b/tests/cases/fourslash/inlayHintsParameterNames.ts @@ -0,0 +1,49 @@ +/// + +//// function foo1 (a: number, b: number) {} +//// foo1(1, 2); + +//// function foo2 (a: number, { c }: any) {} +//// foo2(1, { c: 1 }); + +////const foo3 = (a = 1) => class { } +////const C1 = class extends foo3(1) { } +////class C2 extends foo3(1) { } + +////function foo4(a: number, b: number, c: number, d: number) {} +////foo4(1, +1, -1, +"1"); + +////function foo5( +//// a: string, +//// b: undefined, +//// c: null, +//// d: boolean, +//// e: boolean, +//// f: number, +//// g: number, +//// h: number, +//// i: RegExp, +//// j: bigint, +////) { +////} +////foo5( +//// "hello", +//// undefined, +//// null, +//// true, +//// false, +//// Infinity, +//// -Infinity, +//// NaN, +//// /hello/g, +//// 123n, +////); + +//// declare const unknownCall: any; +//// unknownCall(); + +////function trace(message: string) {} +////trace(`${1}`); +////trace(``); + +verify.baselineInlayHints(undefined, { includeInlayParameterNameHints: "literals" }); diff --git a/tests/cases/fourslash/inlayHintsParameterNamesInSpan1.ts b/tests/cases/fourslash/inlayHintsParameterNamesInSpan1.ts new file mode 100644 index 0000000000000..6db9b21bee1c9 --- /dev/null +++ b/tests/cases/fourslash/inlayHintsParameterNamesInSpan1.ts @@ -0,0 +1,23 @@ +/// + +//// function foo1 (a: number, b: number) {} +//// function foo2 (c: number, d: number) {} +//// function foo3 (e: number, f: number) {} +//// function foo4 (g: number, h: number) {} +//// function foo5 (i: number, j: number) {} +//// function foo6 (k: number, i: number) {} + +//// function c1 () { foo1(/*a*/1, /*b*/2); } +//// function c2 () { foo2(/*c*/1, /*d*/2); } +//// function c3 () { foo3(/*e*/1, /*f*/2); } +//// function c4 () { foo4(/*g*/1, /*h*/2); } +//// function c5 () { foo5(/*i*/1, /*j*/2); } +//// function c6 () { foo6(/*k*/1, /*l*/2); } + +const start = test.markerByName('c'); +const end = test.markerByName('h'); +const span = { start: start.position, length: end.position - start.position }; + +verify.baselineInlayHints(span, { + includeInlayParameterNameHints: "literals", +}) diff --git a/tests/cases/fourslash/inlayHintsParameterNamesInSpan2.ts b/tests/cases/fourslash/inlayHintsParameterNamesInSpan2.ts new file mode 100644 index 0000000000000..7b9f4babead5b --- /dev/null +++ b/tests/cases/fourslash/inlayHintsParameterNamesInSpan2.ts @@ -0,0 +1,23 @@ +/// + +//// function foo1 (a: number, b: number) {} +//// function foo2 (c: number, d: number) {} +//// function foo3 (e: number, f: number) {} +//// function foo4 (g: number, h: number) {} +//// function foo5 (i: number, j: number) {} +//// function foo6 (k: number, l: number) {} + +//// foo1(/*a*/1, /*b*/2); +//// foo2(/*c*/1, /*d*/2); +//// foo3(/*e*/1, /*f*/2); +//// foo4(/*g*/1, /*h*/2); +//// foo5(/*i*/1, /*j*/2); +//// foo6(/*k*/1, /*l*/2); + +const start = test.markerByName('c'); +const end = test.markerByName('h'); +const span = { start: start.position, length: end.position - start.position }; + +verify.baselineInlayHints(span, { + includeInlayParameterNameHints: "literals", +}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork37.ts b/tests/cases/fourslash/inlayHintsPropertyDeclarations.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork37.ts rename to tests/cases/fourslash/inlayHintsPropertyDeclarations.ts diff --git a/tests/cases/fourslash/inlayHintsRestParameters1.ts b/tests/cases/fourslash/inlayHintsRestParameters1.ts new file mode 100644 index 0000000000000..9b0aaa4525821 --- /dev/null +++ b/tests/cases/fourslash/inlayHintsRestParameters1.ts @@ -0,0 +1,14 @@ +/// + +//// function foo1(a: number, ...b: number[]) {} +//// foo1(1, 1, 1, 1); + +//// type Args2 = [a: number, b: number] +//// declare function foo2(c: number, ...args: Args2); +//// foo2(1, 2, 3) + +//// type Args3 = [number, number] +//// declare function foo3(c: number, ...args: Args3); +//// foo3(1, 2, 3) + +verify.baselineInlayHints(undefined, { includeInlayParameterNameHints: "literals" }); diff --git a/tests/cases/fourslash/inlayHintsRestParameters2.ts b/tests/cases/fourslash/inlayHintsRestParameters2.ts new file mode 100644 index 0000000000000..acbccf5462e4d --- /dev/null +++ b/tests/cases/fourslash/inlayHintsRestParameters2.ts @@ -0,0 +1,22 @@ +/// + +////function foo(a: unknown, b: unknown, c: unknown) { } +////function foo1(...x: [number, number | undefined]) { +//// foo(...x, 3); +////} +////function foo2(...x: []) { +//// foo(...x, 1, 2, 3); +////} +////function foo3(...x: [number, number?]) { +//// foo(1, ...x); +////} +////function foo4(...x: [number, number?]) { +//// foo(...x, 3); +////} +////function foo5(...x: [number, number]) { +//// foo(...x, 3); +////} + +verify.baselineInlayHints(undefined, { + includeInlayParameterNameHints: "all" +}); diff --git a/tests/cases/fourslash/inlayHintsReturnType.ts b/tests/cases/fourslash/inlayHintsReturnType.ts new file mode 100644 index 0000000000000..6a22cd80fdb4d --- /dev/null +++ b/tests/cases/fourslash/inlayHintsReturnType.ts @@ -0,0 +1,26 @@ +/// + +//// function foo1 () { +//// return 1 +//// } + +//// function foo2 (): number { +//// return 1 +//// } + +//// class C { +//// foo() { +//// return 1 +//// } +//// } + +//// const a = () => 1 + +//// const b = function () { return 1 } + +//// const c = (b) => 1 +//// const d = b => 1 + +verify.baselineInlayHints(undefined, { + includeInlayFunctionLikeReturnTypeHints: true, +}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork1.ts b/tests/cases/fourslash/inlayHintsShouldWork1.ts deleted file mode 100644 index ee4db03b2f5bf..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork1.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// - -//// function foo (a: number, b: number) {} -//// foo(1, 2); - -verify.baselineInlayHints(undefined, { includeInlayParameterNameHints: "literals", interactiveInlayHints: true }); diff --git a/tests/cases/fourslash/inlayHintsShouldWork10.ts b/tests/cases/fourslash/inlayHintsShouldWork10.ts deleted file mode 100644 index 7731170b2d775..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork10.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// declare const unknownCall: any; -//// unknownCall(); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork11.ts b/tests/cases/fourslash/inlayHintsShouldWork11.ts deleted file mode 100644 index 66df531ce648e..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork11.ts +++ /dev/null @@ -1,13 +0,0 @@ -/// - -//// function foo(a: number) { -//// return (b: number) => { -//// return a + b -//// } -//// } -//// foo(1)(2); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork12.ts b/tests/cases/fourslash/inlayHintsShouldWork12.ts deleted file mode 100644 index 8ddcf14b07e09..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork12.ts +++ /dev/null @@ -1,12 +0,0 @@ -/// - -//// function foo(a: (b: number) => number) { -//// return a(1) + 2 -//// } - -//// foo((c: number) => c + 1); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork13.ts b/tests/cases/fourslash/inlayHintsShouldWork13.ts deleted file mode 100644 index 64d387df866ef..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork13.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -//// function foo (a: number, b: number) {} -//// declare const a: 1; -//// foo(a, 2); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all", - includeInlayParameterNameHintsWhenArgumentMatchesName: false, - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork17.ts b/tests/cases/fourslash/inlayHintsShouldWork17.ts deleted file mode 100644 index e8483d0cd8e1a..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork17.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -//// const a = { a: 123 }; - -verify.baselineInlayHints(undefined, { - includeInlayVariableTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork18.ts b/tests/cases/fourslash/inlayHintsShouldWork18.ts deleted file mode 100644 index 62c1481b83f77..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork18.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// class Class {} -//// const a = new Class(); - -verify.baselineInlayHints(undefined, { - includeInlayVariableTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork19.ts b/tests/cases/fourslash/inlayHintsShouldWork19.ts deleted file mode 100644 index 84ebc9abf4bd0..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork19.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -//// const a = () => 123; - -verify.baselineInlayHints(undefined, { - includeInlayVariableTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork2.ts b/tests/cases/fourslash/inlayHintsShouldWork2.ts deleted file mode 100644 index ddfac24869282..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork2.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// - -//// function foo (a: number, { c }: any) {} -//// foo(1, { c: 1 }); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork21.ts b/tests/cases/fourslash/inlayHintsShouldWork21.ts deleted file mode 100644 index 49a1bf8b0bb7e..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork21.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -//// const a; - -verify.baselineInlayHints(undefined, { - includeInlayVariableTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork22.ts b/tests/cases/fourslash/inlayHintsShouldWork22.ts deleted file mode 100644 index 02e5b5537e4a5..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork22.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -////const a = "I'm very very very very very very very very very long"; - -verify.baselineInlayHints(undefined, { - includeInlayVariableTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork24.ts b/tests/cases/fourslash/inlayHintsShouldWork24.ts deleted file mode 100644 index 70dd4f6e48739..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork24.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// type F = (a: string, b: number) => void -//// const f: F = (a, b) => { } - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork25.ts b/tests/cases/fourslash/inlayHintsShouldWork25.ts deleted file mode 100644 index 9a930646312a5..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork25.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// function foo (cb: (a: string) => void) {} -//// foo((a) => { }) - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork26.ts b/tests/cases/fourslash/inlayHintsShouldWork26.ts deleted file mode 100644 index 3cd976085d98f..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork26.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// function foo (cb: (a: Exclude<1 | 2 | 3, 1>) => void) {} -//// foo((a) => { }) - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork27.ts b/tests/cases/fourslash/inlayHintsShouldWork27.ts deleted file mode 100644 index 1ef281b2a1fc0..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork27.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -//// function foo (a: (b: (c: (d: Exclude<1 | 2 | 3, 1>) => void) => void) => void) {} -//// foo(a => { -//// a(d => {}) -//// }) - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork28.ts b/tests/cases/fourslash/inlayHintsShouldWork28.ts deleted file mode 100644 index 92debc5023431..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork28.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// type F = (a: string, b: number) => void -//// const f: F = (a, b: number) => { } - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork29.ts b/tests/cases/fourslash/inlayHintsShouldWork29.ts deleted file mode 100644 index bd91185d11570..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork29.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -//// function foo (a: (b: (c: (d: Exclude<1 | 2 | 3, 1>) => void) => void) => void) {} -//// foo(a => { -//// a(d => {}) -//// }) - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all", - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork3.ts b/tests/cases/fourslash/inlayHintsShouldWork3.ts deleted file mode 100644 index e5206d92fe437..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork3.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// - -//// function foo (a: number, ...b: number[]) {} -//// foo(1, 1, 1, 1); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork30.ts b/tests/cases/fourslash/inlayHintsShouldWork30.ts deleted file mode 100644 index 49e1140234776..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork30.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// function f(v: T, a: (v: T) => void) {} -//// f(1, a => { }) - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork31.ts b/tests/cases/fourslash/inlayHintsShouldWork31.ts deleted file mode 100644 index ad5cb8564d6a1..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork31.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -//// type F = (a: { -//// a: number -//// b: string -//// }) => void -//// const f: F = (a) => { } - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork36.ts b/tests/cases/fourslash/inlayHintsShouldWork36.ts deleted file mode 100644 index 92b425029e1cf..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork36.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -//// function foo (a: number, b: number) {} -//// declare const a: 1; -//// foo(a, 2); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all", - includeInlayParameterNameHintsWhenArgumentMatchesName: true, - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork38.ts b/tests/cases/fourslash/inlayHintsShouldWork38.ts deleted file mode 100644 index a5e66f07c9b59..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork38.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// - -//// function foo () { -//// return 1 -//// } - -verify.baselineInlayHints(undefined, { - includeInlayFunctionLikeReturnTypeHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork39.ts b/tests/cases/fourslash/inlayHintsShouldWork39.ts deleted file mode 100644 index 4a20875cc43b2..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork39.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// - -//// function foo (): number { -//// return 1 -//// } - -verify.baselineInlayHints(undefined, { - includeInlayFunctionLikeReturnTypeHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork4.ts b/tests/cases/fourslash/inlayHintsShouldWork4.ts deleted file mode 100644 index 84b4cef862f2a..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork4.ts +++ /dev/null @@ -1,13 +0,0 @@ -/// - -//// declare function foo(w: number): void -//// declare function foo(a: number, b: number): void; -//// declare function foo(a: number | undefined, b: number | undefined): void; - -//// foo(1) -//// foo(1, 2) - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork40.ts b/tests/cases/fourslash/inlayHintsShouldWork40.ts deleted file mode 100644 index 3cef398828d39..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork40.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -//// class C { -//// foo() { -//// return 1 -//// } -//// } - -verify.baselineInlayHints(undefined, { - includeInlayFunctionLikeReturnTypeHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork41.ts b/tests/cases/fourslash/inlayHintsShouldWork41.ts deleted file mode 100644 index 81037d2946a6f..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork41.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -//// const a = () => 1 - -verify.baselineInlayHints(undefined, { - includeInlayFunctionLikeReturnTypeHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork42.ts b/tests/cases/fourslash/inlayHintsShouldWork42.ts deleted file mode 100644 index 5b736dc03e435..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork42.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -//// const a = function () { return 1} - -verify.baselineInlayHints(undefined, { - includeInlayFunctionLikeReturnTypeHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork43.ts b/tests/cases/fourslash/inlayHintsShouldWork43.ts deleted file mode 100644 index 56b57d23e2fc1..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork43.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// const a = (b) => 1 -//// const aa = b => 1 - -verify.baselineInlayHints(undefined, { - includeInlayFunctionLikeReturnTypeHints: true, -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork48.ts b/tests/cases/fourslash/inlayHintsShouldWork48.ts deleted file mode 100644 index 74d5504eea322..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork48.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// declare function foo(t: T): T -//// const x = foo(1) - -verify.baselineInlayHints(undefined, { - includeInlayVariableTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork49.ts b/tests/cases/fourslash/inlayHintsShouldWork49.ts deleted file mode 100644 index 1646b358c099f..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork49.ts +++ /dev/null @@ -1,16 +0,0 @@ -/// - -// @allowJs: true -// @checkJs: true - -// @Filename: /a.js -//// /** -//// * @type {string} -//// */ -//// var x = "" - - -goTo.file('/a.js') -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork5.ts b/tests/cases/fourslash/inlayHintsShouldWork5.ts deleted file mode 100644 index 879299e69fa52..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork5.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -//// type Args = [a: number, b: number] -//// declare function foo(c: number, ...args: Args); -//// foo(1, 2, 3) - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork50.ts b/tests/cases/fourslash/inlayHintsShouldWork50.ts deleted file mode 100644 index c3c6355076f3e..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork50.ts +++ /dev/null @@ -1,12 +0,0 @@ -/// - -//// type T = [a: string, b: boolean, ...c: number[]] -//// declare function foo(f: number, ...args: T):void -//// declare function foo1(f1: number, ...args: string[]): void -//// foo(1, '', false, 1, 2) -//// foo1(1, "", "") - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork53.ts b/tests/cases/fourslash/inlayHintsShouldWork53.ts deleted file mode 100644 index 1ff73c959f756..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork53.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// - -//// const fn = (x: any) => { } -//// fn(/* nobody knows exactly what this param is */ 42); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork55.ts b/tests/cases/fourslash/inlayHintsShouldWork55.ts deleted file mode 100644 index cd08695a76896..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork55.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// - -////class Foo { -//// get foo() { return 1; } -////} - -verify.baselineInlayHints(undefined, { - includeInlayFunctionLikeReturnTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork57.ts b/tests/cases/fourslash/inlayHintsShouldWork57.ts deleted file mode 100644 index 93ec9b1412cb6..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork57.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -////class Foo { -//// #value = 0; -//// get foo(): number { return this.#value; } -//// set foo(value) { this.#value = value; } -////} - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork58.ts b/tests/cases/fourslash/inlayHintsShouldWork58.ts deleted file mode 100644 index 0647f60dc8d50..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork58.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -////class Foo { -//// #value = 0; -//// get foo(): number { return this.#value; } -//// set foo(value: number) { this.#value = value; } -////} - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork6.ts b/tests/cases/fourslash/inlayHintsShouldWork6.ts deleted file mode 100644 index 49bcf7146fa2d..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork6.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -//// type Args = [number, number] -//// declare function foo(c: number, ...args: Args); -//// foo(1, 2, 3) - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork60.ts b/tests/cases/fourslash/inlayHintsShouldWork60.ts deleted file mode 100644 index db851815825d7..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork60.ts +++ /dev/null @@ -1,14 +0,0 @@ -/// - -// @allowJs: true -// @checkJs: true -// @Filename: /a.js -////class Foo { -//// #value = 0; -//// get foo() { return this.#value; } -//// set foo(value) { this.#value = value; } -////} - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork61.ts b/tests/cases/fourslash/inlayHintsShouldWork61.ts deleted file mode 100644 index 8729e198f9a9e..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork61.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// - -////class Foo { -//// set foo(value: number) {} -////} - -verify.baselineInlayHints(undefined, { - includeInlayFunctionLikeReturnTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork62.ts b/tests/cases/fourslash/inlayHintsShouldWork62.ts deleted file mode 100644 index 33325804ab69a..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork62.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -////function trace(message: string) {} -////trace(`${1}`); -////trace(``); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork63.ts b/tests/cases/fourslash/inlayHintsShouldWork63.ts deleted file mode 100644 index 7be2c0627afe6..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork63.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// - -////function foo(a: number, b: number, c: number, d: number) {} -////foo(1, +1, -1, +"1"); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork64.ts b/tests/cases/fourslash/inlayHintsShouldWork64.ts deleted file mode 100644 index 0196ccc8cf32e..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork64.ts +++ /dev/null @@ -1,33 +0,0 @@ -/// - -////function foo( -//// a: string, -//// b: undefined, -//// c: null, -//// d: boolean, -//// e: boolean, -//// f: number, -//// g: number, -//// h: number, -//// i: RegExp, -//// j: bigint, -////) { -////} -//// -////foo( -//// "hello", -//// undefined, -//// null, -//// true, -//// false, -//// Infinity, -//// -Infinity, -//// NaN, -//// /hello/g, -//// 123n, -////); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork65.ts b/tests/cases/fourslash/inlayHintsShouldWork65.ts deleted file mode 100644 index 6e3491b59fc68..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork65.ts +++ /dev/null @@ -1,8 +0,0 @@ -/// - -//// type F = (a: string, b: number) => void -//// const f: F = (a, b = 1) => { } - -verify.baselineInlayHints(undefined, { - includeInlayFunctionParameterTypeHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork68.ts b/tests/cases/fourslash/inlayHintsShouldWork68.ts deleted file mode 100644 index 0ccecf97ba532..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork68.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -////const foo = (a = 1) => class { } -//// -////const C1 = class extends foo(1) { } -////class C2 extends foo(1) { } - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork7.ts b/tests/cases/fourslash/inlayHintsShouldWork7.ts deleted file mode 100644 index ec1a32545c2a6..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork7.ts +++ /dev/null @@ -1,14 +0,0 @@ -/// - -//// interface Call { -//// (a: number): void -//// (b: number, c: number): void -//// } -//// declare const call: Call; -//// call(1); -//// call(1, 2); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork70.ts b/tests/cases/fourslash/inlayHintsShouldWork70.ts deleted file mode 100644 index 6b99d98ee3424..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork70.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -////function foo(a: unknown, b: unknown, c: unknown) { } -////function bar(...x: [number, number]) { -//// foo(...x, 3); -////} - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork71.ts b/tests/cases/fourslash/inlayHintsShouldWork71.ts deleted file mode 100644 index d0fe31b37b631..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork71.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -////function foo(a: unknown, b: unknown, c: unknown, d: unknown) { } -////function bar(...x: [number, number, number]) { -//// foo(...x, 3); -////} - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork72.ts b/tests/cases/fourslash/inlayHintsShouldWork72.ts deleted file mode 100644 index 8e7a927616a46..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork72.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -////function foo(a: unknown, b: unknown, c: unknown) { } -////function bar(...x: [number, number?]) { -//// foo(...x, 3); -////} - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork73.ts b/tests/cases/fourslash/inlayHintsShouldWork73.ts deleted file mode 100644 index b533daf67d619..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork73.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -////function foo(a: unknown, b: unknown, c: unknown) { } -////function bar(...x: [number, number?]) { -//// foo(1, ...x); -////} - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork74.ts b/tests/cases/fourslash/inlayHintsShouldWork74.ts deleted file mode 100644 index 920de7202bf21..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork74.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -////function foo(a: unknown, b: unknown, c: unknown) { } -////function bar(...x: [number, number | undefined]) { -//// foo(...x, 3); -////} - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork75.ts b/tests/cases/fourslash/inlayHintsShouldWork75.ts deleted file mode 100644 index 413f34d39e6e4..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork75.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -////function foo(a: unknown, b: unknown, c: unknown) { } -////function bar(...x: []) { -//// foo(...x, 1, 2, 3); -////} - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork76.ts b/tests/cases/fourslash/inlayHintsShouldWork76.ts deleted file mode 100644 index 3ebfcd588d8e8..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork76.ts +++ /dev/null @@ -1,10 +0,0 @@ -/// - -////function foo({ a, b }: { a: unknown, b: unknown }, c: unknown, d: unknown) { } -////function bar(...x: [{ a: unknown, b: unknown }, number]) { -//// foo(...x, 1); -////} - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "all" -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork8.ts b/tests/cases/fourslash/inlayHintsShouldWork8.ts deleted file mode 100644 index 59ec8b1cd3a87..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork8.ts +++ /dev/null @@ -1,14 +0,0 @@ -/// - -//// class Class { -//// constructor(a: number); -//// constructor(b: number, c: number); -//// constructor(b: number, c?: number) { } -//// } -//// new Class(1) -//// new Class(1, 2) - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork9.ts b/tests/cases/fourslash/inlayHintsShouldWork9.ts deleted file mode 100644 index 71ada9ddf3c49..0000000000000 --- a/tests/cases/fourslash/inlayHintsShouldWork9.ts +++ /dev/null @@ -1,16 +0,0 @@ -/// - -//// interface Call { -//// (a: number): void -//// (b: number, c: number): void -//// new (d: number): Call -//// } -//// declare const call: Call; -//// call(1); -//// call(1, 2); -//// new call(1); - -verify.baselineInlayHints(undefined, { - includeInlayParameterNameHints: "literals", - interactiveInlayHints: true -}); diff --git a/tests/cases/fourslash/inlayHintsShouldWork67.ts b/tests/cases/fourslash/inlayHintsTypeMatchesName.ts similarity index 100% rename from tests/cases/fourslash/inlayHintsShouldWork67.ts rename to tests/cases/fourslash/inlayHintsTypeMatchesName.ts diff --git a/tests/cases/fourslash/inlayHintsShouldWork15.ts b/tests/cases/fourslash/inlayHintsVariableTypes1.ts similarity index 87% rename from tests/cases/fourslash/inlayHintsShouldWork15.ts rename to tests/cases/fourslash/inlayHintsVariableTypes1.ts index b19bfc34fc64d..3faeaeb05d68c 100644 --- a/tests/cases/fourslash/inlayHintsShouldWork15.ts +++ b/tests/cases/fourslash/inlayHintsVariableTypes1.ts @@ -7,19 +7,22 @@ ////const a = "a"; ////const b = 1; ////const c = true; -//// + ////const d = {} as Foo; ////const e = {}; ////const f = {} as const; ////const g = (({} as const)); -//// + ////const h = new C(); ////const i = new N.C(); ////const j = ((((new C())))); -//// + ////const k = { a: 1, b: 1 }; ////const l = ((({ a: 1, b: 1 }))); +//// const m = () => 123; +//// const n; + verify.baselineInlayHints(undefined, { includeInlayVariableTypeHints: true }); diff --git a/tests/cases/fourslash/inlayHintsShouldWork56.ts b/tests/cases/fourslash/inlayHintsVariableTypes2.ts similarity index 79% rename from tests/cases/fourslash/inlayHintsShouldWork56.ts rename to tests/cases/fourslash/inlayHintsVariableTypes2.ts index 78b64dd24b695..244d9eb71d4dc 100644 --- a/tests/cases/fourslash/inlayHintsShouldWork56.ts +++ b/tests/cases/fourslash/inlayHintsVariableTypes2.ts @@ -9,6 +9,9 @@ //// const [ first, second ] = array; //// const [] = array; +//// declare function foo(t: T): T +//// const x = foo(1) + verify.baselineInlayHints(undefined, { includeInlayVariableTypeHints: true }); diff --git a/tests/cases/fourslash/inlayHintsWithClosures.ts b/tests/cases/fourslash/inlayHintsWithClosures.ts new file mode 100644 index 0000000000000..50a09bec313ce --- /dev/null +++ b/tests/cases/fourslash/inlayHintsWithClosures.ts @@ -0,0 +1,17 @@ +/// + +//// function foo1(a: number) { +//// return (b: number) => { +//// return a + b +//// } +//// } +//// foo1(1)(2); + +//// function foo2(a: (b: number) => number) { +//// return a(1) + 2 +//// } +//// foo2((c: number) => c + 1); + +verify.baselineInlayHints(undefined, { + includeInlayParameterNameHints: "all", +}); From 5725506c6ff4305bd5a4d35be06a0b44936b2a45 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Mon, 14 Aug 2023 15:20:03 -0700 Subject: [PATCH 14/81] Fix unused baseline failure on main (#55379) --- .../inlayHintsInteractiveReturnType.baseline | 205 ------------------ 1 file changed, 205 deletions(-) delete mode 100644 tests/baselines/reference/inlayHintsInteractiveReturnType.baseline diff --git a/tests/baselines/reference/inlayHintsInteractiveReturnType.baseline b/tests/baselines/reference/inlayHintsInteractiveReturnType.baseline deleted file mode 100644 index 24d374144aece..0000000000000 --- a/tests/baselines/reference/inlayHintsInteractiveReturnType.baseline +++ /dev/null @@ -1,205 +0,0 @@ -function numberLiteral() { return 1; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "number" - } - ], - "position": 52, - "kind": "Type", - "whitespaceBefore": true -} - -function stringLiteral() { return "foo"; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "string" - } - ], - "position": 91, - "kind": "Type", - "whitespaceBefore": true -} - -function nothing() { } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "void" - } - ], - "position": 128, - "kind": "Type", - "whitespaceBefore": true -} - -function closure() { return () => 1; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "(" - }, - { - "text": ")" - }, - { - "text": " => " - }, - { - "text": "number" - } - ], - "position": 151, - "kind": "Type", - "whitespaceBefore": true -} - -function closure() { return () => 1; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "number" - } - ], - "position": 163, - "kind": "Type", - "whitespaceBefore": true -} - -function fooClosure() { return (foo: Foo) => foo.bar; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "(" - }, - { - "text": ")" - }, - { - "text": " => " - }, - { - "text": "number" - } - ], - "position": 193, - "kind": "Type", - "whitespaceBefore": true -} - -function fooClosure() { return (foo: Foo) => foo.bar; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "number" - } - ], - "position": 213, - "kind": "Type", - "whitespaceBefore": true -} - -function returnFoo(foo: Foo) { return foo; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "Foo", - "span": { - "start": 5, - "length": 3 - }, - "file": "/tests/cases/fourslash/inlayHintsInteractiveReturnType.ts" - } - ], - "position": 256, - "kind": "Type", - "whitespaceBefore": true -} - -function returnMaybeFoo(foo: Foo) { if (Math.random()) return foo; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "Foo", - "span": { - "start": 5, - "length": 3 - }, - "file": "/tests/cases/fourslash/inlayHintsInteractiveReturnType.ts" - } - ], - "position": 306, - "kind": "Type", - "whitespaceBefore": true -} - -function returnFoos(foo: Foo) { return [foo, foo]; } - ^ -{ - "text": "", - "displayParts": [ - { - "text": ": " - }, - { - "text": "Foo", - "span": { - "start": 5, - "length": 3 - }, - "file": "/tests/cases/fourslash/inlayHintsInteractiveReturnType.ts" - }, - { - "text": "[]" - } - ], - "position": 371, - "kind": "Type", - "whitespaceBefore": true -} \ No newline at end of file From 9261ca7a13423d93d8c5c6b6b15908fdc7a5abce Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 14 Aug 2023 18:46:55 -0700 Subject: [PATCH 15/81] Share redirects cache key calculation between multiple caches used for module resolution and type reference directive (#55376) --- src/compiler/moduleNameResolver.ts | 66 ++++++++++++++++++++++++++---- src/compiler/program.ts | 8 +++- src/compiler/resolutionCache.ts | 1 + src/compiler/tsbuildPublic.ts | 8 +++- 4 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 3049f8b742d9d..c229d42be1b36 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -854,6 +854,7 @@ export interface PerNonRelativeNameCache { export interface ModuleResolutionCache extends PerDirectoryResolutionCache, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache { getPackageJsonInfoCache(): PackageJsonInfoCache; /** @internal */ clearAllExceptPackageJsonInfoCache(): void; + /** @internal */ optionsToRedirectsKey: Map; } /** @@ -905,10 +906,11 @@ export interface CacheWithRedirects { } /** @internal */ -export function createCacheWithRedirects(ownOptions: CompilerOptions | undefined): CacheWithRedirects { - type RedirectsCacheKey = string & { __compilerOptionsKey: any; }; +export type RedirectsCacheKey = string & { __compilerOptionsKey: any; }; + +/** @internal */ +export function createCacheWithRedirects(ownOptions: CompilerOptions | undefined, optionsToRedirectsKey: Map): CacheWithRedirects { const redirectsMap = new Map>(); - const optionsToRedirectsKey = new Map(); const redirectsKeyToMap = new Map>(); let ownMap = new Map(); if (ownOptions) redirectsMap.set(ownOptions, ownMap); @@ -1011,8 +1013,13 @@ function getOrCreateCache(cacheWithRedirects: CacheWithRedirects, re return result; } -function createPerDirectoryResolutionCache(currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, options: CompilerOptions | undefined): PerDirectoryResolutionCache { - const directoryToModuleNameMap = createCacheWithRedirects>(options); +function createPerDirectoryResolutionCache( + currentDirectory: string, + getCanonicalFileName: GetCanonicalFileName, + options: CompilerOptions | undefined, + optionsToRedirectsKey: Map, +): PerDirectoryResolutionCache { + const directoryToModuleNameMap = createCacheWithRedirects>(options, optionsToRedirectsKey); return { getFromDirectoryCache, getOrCreateCacheForDirectory, @@ -1114,8 +1121,9 @@ function createNonRelativeNameResolutionCache( getCanonicalFileName: (s: string) => string, options: CompilerOptions | undefined, getResolvedFileName: (result: T) => string | undefined, + optionsToRedirectsKey: Map, ): NonRelativeNameResolutionCache { - const moduleNameToDirectoryMap = createCacheWithRedirects>(options); + const moduleNameToDirectoryMap = createCacheWithRedirects>(options, optionsToRedirectsKey); return { getFromNonRelativeNameCache, getOrCreateCacheForNonRelativeName, @@ -1216,6 +1224,7 @@ function createNonRelativeNameResolutionCache( interface ModuleOrTypeReferenceResolutionCache extends PerDirectoryResolutionCache, NonRelativeNameResolutionCache, PackageJsonInfoCache { getPackageJsonInfoCache(): PackageJsonInfoCache; clearAllExceptPackageJsonInfoCache(): void; + optionsToRedirectsKey: Map; } function createModuleOrTypeReferenceResolutionCache( currentDirectory: string, @@ -1223,13 +1232,21 @@ function createModuleOrTypeReferenceResolutionCache( options: CompilerOptions | undefined, packageJsonInfoCache: PackageJsonInfoCache | undefined, getResolvedFileName: (result: T) => string | undefined, + optionsToRedirectsKey: Map | undefined, ): ModuleOrTypeReferenceResolutionCache { - const perDirectoryResolutionCache = createPerDirectoryResolutionCache(currentDirectory, getCanonicalFileName, options); + optionsToRedirectsKey ??= new Map(); + const perDirectoryResolutionCache = createPerDirectoryResolutionCache( + currentDirectory, + getCanonicalFileName, + options, + optionsToRedirectsKey, + ); const nonRelativeNameResolutionCache = createNonRelativeNameResolutionCache( currentDirectory, getCanonicalFileName, options, getResolvedFileName, + optionsToRedirectsKey, ); packageJsonInfoCache ??= createPackageJsonInfoCache(currentDirectory, getCanonicalFileName); @@ -1241,6 +1258,7 @@ function createModuleOrTypeReferenceResolutionCache( update, getPackageJsonInfoCache: () => packageJsonInfoCache!, clearAllExceptPackageJsonInfoCache, + optionsToRedirectsKey, }; function clear() { @@ -1264,6 +1282,21 @@ export function createModuleResolutionCache( getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache, +): ModuleResolutionCache; +/** @internal */ +export function createModuleResolutionCache( + currentDirectory: string, + getCanonicalFileName: (s: string) => string, + options?: CompilerOptions, + packageJsonInfoCache?: PackageJsonInfoCache, + optionsToRedirectsKey?: Map, +): ModuleResolutionCache; +export function createModuleResolutionCache( + currentDirectory: string, + getCanonicalFileName: (s: string) => string, + options?: CompilerOptions, + packageJsonInfoCache?: PackageJsonInfoCache, + optionsToRedirectsKey?: Map, ): ModuleResolutionCache { const result = createModuleOrTypeReferenceResolutionCache( currentDirectory, @@ -1271,6 +1304,7 @@ export function createModuleResolutionCache( options, packageJsonInfoCache, getOriginalOrResolvedModuleFileName, + optionsToRedirectsKey, ) as ModuleResolutionCache; result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); return result; @@ -1281,13 +1315,29 @@ export function createTypeReferenceDirectiveResolutionCache( getCanonicalFileName: (s: string) => string, options?: CompilerOptions, packageJsonInfoCache?: PackageJsonInfoCache, +): TypeReferenceDirectiveResolutionCache; +/** @internal */ +export function createTypeReferenceDirectiveResolutionCache( + currentDirectory: string, + getCanonicalFileName: (s: string) => string, + options?: CompilerOptions, + packageJsonInfoCache?: PackageJsonInfoCache, + optionsToRedirectsKey?: Map, +): TypeReferenceDirectiveResolutionCache; +export function createTypeReferenceDirectiveResolutionCache( + currentDirectory: string, + getCanonicalFileName: (s: string) => string, + options?: CompilerOptions, + packageJsonInfoCache?: PackageJsonInfoCache, + optionsToRedirectsKey?: Map, ): TypeReferenceDirectiveResolutionCache { return createModuleOrTypeReferenceResolutionCache( currentDirectory, getCanonicalFileName, options, packageJsonInfoCache, - getOriginalOrResolvedTypeReferenceFileName + getOriginalOrResolvedTypeReferenceFileName, + optionsToRedirectsKey, ); } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 227d3b5a3983f..9d1c258cec3e5 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1621,7 +1621,13 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg ).map(resolvedTypeReferenceDirective => ({ resolvedTypeReferenceDirective })); } else { - const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache?.getPackageJsonInfoCache()); + const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( + currentDirectory, + getCanonicalFileName, + /*options*/ undefined, + moduleResolutionCache?.getPackageJsonInfoCache(), + moduleResolutionCache?.optionsToRedirectsKey, + ); actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, options, containingSourceFile) => loadWithModeAwareCache( typeDirectiveNames, diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index bf7972763a568..7d6ac150c05e8 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -452,6 +452,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD resolutionHost.getCanonicalFileName, resolutionHost.getCompilationSettings(), moduleResolutionCache.getPackageJsonInfoCache(), + moduleResolutionCache.optionsToRedirectsKey, ); const resolvedLibraries = new Map(); diff --git a/src/compiler/tsbuildPublic.ts b/src/compiler/tsbuildPublic.ts index 3bc998eb7dc26..b734ca7eed949 100644 --- a/src/compiler/tsbuildPublic.ts +++ b/src/compiler/tsbuildPublic.ts @@ -455,7 +455,13 @@ function createSolutionBuilderState(watch: boolean, ho compilerHost.getModuleResolutionCache = () => moduleResolutionCache; } if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { - typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, /*options*/ undefined, moduleResolutionCache?.getPackageJsonInfoCache()); + typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache( + compilerHost.getCurrentDirectory(), + compilerHost.getCanonicalFileName, + /*options*/ undefined, + moduleResolutionCache?.getPackageJsonInfoCache(), + moduleResolutionCache?.optionsToRedirectsKey, + ); compilerHost.resolveTypeReferenceDirectiveReferences = (typeDirectiveNames, containingFile, redirectedReference, options, containingSourceFile) => loadWithModeAwareCache( typeDirectiveNames, From c5281bf7003abc09164a093ce643ae8ba422c40f Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Tue, 15 Aug 2023 06:19:25 +0000 Subject: [PATCH 16/81] Update package-lock.json --- package-lock.json | 182 +++++++++++++++++++++------------------------- 1 file changed, 84 insertions(+), 98 deletions(-) diff --git a/package-lock.json b/package-lock.json index e2c485674307d..c661d8d85002d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -897,21 +897,20 @@ "dev": true }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.3.0.tgz", - "integrity": "sha512-IZYjYZ0ifGSLZbwMqIip/nOamFiWJ9AH+T/GYNZBWkVcyNQOFGtSMoWV7RvY4poYCMZ/4lHzNl796WOSNxmk8A==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.4.0.tgz", + "integrity": "sha512-62o2Hmc7Gs3p8SLfbXcipjWAa6qk2wZGChXG2JbBtYpwSRmti/9KHLqfbLs9uDigOexG+3PaQ9G2g3201FWLKg==", "dev": true, "dependencies": { "@eslint-community/regexpp": "^4.5.1", - "@typescript-eslint/scope-manager": "6.3.0", - "@typescript-eslint/type-utils": "6.3.0", - "@typescript-eslint/utils": "6.3.0", - "@typescript-eslint/visitor-keys": "6.3.0", + "@typescript-eslint/scope-manager": "6.4.0", + "@typescript-eslint/type-utils": "6.4.0", + "@typescript-eslint/utils": "6.4.0", + "@typescript-eslint/visitor-keys": "6.4.0", "debug": "^4.3.4", "graphemer": "^1.4.0", "ignore": "^5.2.4", "natural-compare": "^1.4.0", - "natural-compare-lite": "^1.4.0", "semver": "^7.5.4", "ts-api-utils": "^1.0.1" }, @@ -933,15 +932,15 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.3.0.tgz", - "integrity": "sha512-ibP+y2Gr6p0qsUkhs7InMdXrwldjxZw66wpcQq9/PzAroM45wdwyu81T+7RibNCh8oc0AgrsyCwJByncY0Ongg==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.4.0.tgz", + "integrity": "sha512-I1Ah1irl033uxjxO9Xql7+biL3YD7w9IU8zF+xlzD/YxY6a4b7DYA08PXUUCbm2sEljwJF6ERFy2kTGAGcNilg==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "6.3.0", - "@typescript-eslint/types": "6.3.0", - "@typescript-eslint/typescript-estree": "6.3.0", - "@typescript-eslint/visitor-keys": "6.3.0", + "@typescript-eslint/scope-manager": "6.4.0", + "@typescript-eslint/types": "6.4.0", + "@typescript-eslint/typescript-estree": "6.4.0", + "@typescript-eslint/visitor-keys": "6.4.0", "debug": "^4.3.4" }, "engines": { @@ -961,13 +960,13 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.3.0.tgz", - "integrity": "sha512-WlNFgBEuGu74ahrXzgefiz/QlVb+qg8KDTpknKwR7hMH+lQygWyx0CQFoUmMn1zDkQjTBBIn75IxtWss77iBIQ==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.4.0.tgz", + "integrity": "sha512-TUS7vaKkPWDVvl7GDNHFQMsMruD+zhkd3SdVW0d7b+7Zo+bd/hXJQ8nsiUZMi1jloWo6c9qt3B7Sqo+flC1nig==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.3.0", - "@typescript-eslint/visitor-keys": "6.3.0" + "@typescript-eslint/types": "6.4.0", + "@typescript-eslint/visitor-keys": "6.4.0" }, "engines": { "node": "^16.0.0 || >=18.0.0" @@ -978,13 +977,13 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.3.0.tgz", - "integrity": "sha512-7Oj+1ox1T2Yc8PKpBvOKWhoI/4rWFd1j7FA/rPE0lbBPXTKjdbtC+7Ev0SeBjEKkIhKWVeZSP+mR7y1Db1CdfQ==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.4.0.tgz", + "integrity": "sha512-TvqrUFFyGY0cX3WgDHcdl2/mMCWCDv/0thTtx/ODMY1QhEiyFtv/OlLaNIiYLwRpAxAtOLOY9SUf1H3Q3dlwAg==", "dev": true, "dependencies": { - "@typescript-eslint/typescript-estree": "6.3.0", - "@typescript-eslint/utils": "6.3.0", + "@typescript-eslint/typescript-estree": "6.4.0", + "@typescript-eslint/utils": "6.4.0", "debug": "^4.3.4", "ts-api-utils": "^1.0.1" }, @@ -1005,9 +1004,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.3.0.tgz", - "integrity": "sha512-K6TZOvfVyc7MO9j60MkRNWyFSf86IbOatTKGrpTQnzarDZPYPVy0oe3myTMq7VjhfsUAbNUW8I5s+2lZvtx1gg==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.4.0.tgz", + "integrity": "sha512-+FV9kVFrS7w78YtzkIsNSoYsnOtrYVnKWSTVXoL1761CsCRv5wpDOINgsXpxD67YCLZtVQekDDyaxfjVWUJmmg==", "dev": true, "engines": { "node": "^16.0.0 || >=18.0.0" @@ -1018,13 +1017,13 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.3.0.tgz", - "integrity": "sha512-Xh4NVDaC4eYKY4O3QGPuQNp5NxBAlEvNQYOqJquR2MePNxO11E5K3t5x4M4Mx53IZvtpW+mBxIT0s274fLUocg==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.4.0.tgz", + "integrity": "sha512-iDPJArf/K2sxvjOR6skeUCNgHR/tCQXBsa+ee1/clRKr3olZjZ/dSkXPZjG6YkPtnW6p5D1egeEPMCW6Gn4yLA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.3.0", - "@typescript-eslint/visitor-keys": "6.3.0", + "@typescript-eslint/types": "6.4.0", + "@typescript-eslint/visitor-keys": "6.4.0", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -1045,17 +1044,17 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.3.0.tgz", - "integrity": "sha512-hLLg3BZE07XHnpzglNBG8P/IXq/ZVXraEbgY7FM0Cnc1ehM8RMdn9mat3LubJ3KBeYXXPxV1nugWbQPjGeJk6Q==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.4.0.tgz", + "integrity": "sha512-BvvwryBQpECPGo8PwF/y/q+yacg8Hn/2XS+DqL/oRsOPK+RPt29h5Ui5dqOKHDlbXrAeHUTnyG3wZA0KTDxRZw==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", "@types/json-schema": "^7.0.12", "@types/semver": "^7.5.0", - "@typescript-eslint/scope-manager": "6.3.0", - "@typescript-eslint/types": "6.3.0", - "@typescript-eslint/typescript-estree": "6.3.0", + "@typescript-eslint/scope-manager": "6.4.0", + "@typescript-eslint/types": "6.4.0", + "@typescript-eslint/typescript-estree": "6.4.0", "semver": "^7.5.4" }, "engines": { @@ -1070,12 +1069,12 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.3.0.tgz", - "integrity": "sha512-kEhRRj7HnvaSjux1J9+7dBen15CdWmDnwrpyiHsFX6Qx2iW5LOBUgNefOFeh2PjWPlNwN8TOn6+4eBU3J/gupw==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.4.0.tgz", + "integrity": "sha512-yJSfyT+uJm+JRDWYRYdCm2i+pmvXJSMtPR9Cq5/XQs4QIgNoLcoRtDdzsLbLsFM/c6um6ohQkg/MLxWvoIndJA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "6.3.0", + "@typescript-eslint/types": "6.4.0", "eslint-visitor-keys": "^3.4.1" }, "engines": { @@ -2950,12 +2949,6 @@ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", "dev": true }, - "node_modules/natural-compare-lite": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz", - "integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==", - "dev": true - }, "node_modules/node-domexception": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", @@ -4451,74 +4444,73 @@ "dev": true }, "@typescript-eslint/eslint-plugin": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.3.0.tgz", - "integrity": "sha512-IZYjYZ0ifGSLZbwMqIip/nOamFiWJ9AH+T/GYNZBWkVcyNQOFGtSMoWV7RvY4poYCMZ/4lHzNl796WOSNxmk8A==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.4.0.tgz", + "integrity": "sha512-62o2Hmc7Gs3p8SLfbXcipjWAa6qk2wZGChXG2JbBtYpwSRmti/9KHLqfbLs9uDigOexG+3PaQ9G2g3201FWLKg==", "dev": true, "requires": { "@eslint-community/regexpp": "^4.5.1", - "@typescript-eslint/scope-manager": "6.3.0", - "@typescript-eslint/type-utils": "6.3.0", - "@typescript-eslint/utils": "6.3.0", - "@typescript-eslint/visitor-keys": "6.3.0", + "@typescript-eslint/scope-manager": "6.4.0", + "@typescript-eslint/type-utils": "6.4.0", + "@typescript-eslint/utils": "6.4.0", + "@typescript-eslint/visitor-keys": "6.4.0", "debug": "^4.3.4", "graphemer": "^1.4.0", "ignore": "^5.2.4", "natural-compare": "^1.4.0", - "natural-compare-lite": "^1.4.0", "semver": "^7.5.4", "ts-api-utils": "^1.0.1" } }, "@typescript-eslint/parser": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.3.0.tgz", - "integrity": "sha512-ibP+y2Gr6p0qsUkhs7InMdXrwldjxZw66wpcQq9/PzAroM45wdwyu81T+7RibNCh8oc0AgrsyCwJByncY0Ongg==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.4.0.tgz", + "integrity": "sha512-I1Ah1irl033uxjxO9Xql7+biL3YD7w9IU8zF+xlzD/YxY6a4b7DYA08PXUUCbm2sEljwJF6ERFy2kTGAGcNilg==", "dev": true, "requires": { - "@typescript-eslint/scope-manager": "6.3.0", - "@typescript-eslint/types": "6.3.0", - "@typescript-eslint/typescript-estree": "6.3.0", - "@typescript-eslint/visitor-keys": "6.3.0", + "@typescript-eslint/scope-manager": "6.4.0", + "@typescript-eslint/types": "6.4.0", + "@typescript-eslint/typescript-estree": "6.4.0", + "@typescript-eslint/visitor-keys": "6.4.0", "debug": "^4.3.4" } }, "@typescript-eslint/scope-manager": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.3.0.tgz", - "integrity": "sha512-WlNFgBEuGu74ahrXzgefiz/QlVb+qg8KDTpknKwR7hMH+lQygWyx0CQFoUmMn1zDkQjTBBIn75IxtWss77iBIQ==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.4.0.tgz", + "integrity": "sha512-TUS7vaKkPWDVvl7GDNHFQMsMruD+zhkd3SdVW0d7b+7Zo+bd/hXJQ8nsiUZMi1jloWo6c9qt3B7Sqo+flC1nig==", "dev": true, "requires": { - "@typescript-eslint/types": "6.3.0", - "@typescript-eslint/visitor-keys": "6.3.0" + "@typescript-eslint/types": "6.4.0", + "@typescript-eslint/visitor-keys": "6.4.0" } }, "@typescript-eslint/type-utils": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.3.0.tgz", - "integrity": "sha512-7Oj+1ox1T2Yc8PKpBvOKWhoI/4rWFd1j7FA/rPE0lbBPXTKjdbtC+7Ev0SeBjEKkIhKWVeZSP+mR7y1Db1CdfQ==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.4.0.tgz", + "integrity": "sha512-TvqrUFFyGY0cX3WgDHcdl2/mMCWCDv/0thTtx/ODMY1QhEiyFtv/OlLaNIiYLwRpAxAtOLOY9SUf1H3Q3dlwAg==", "dev": true, "requires": { - "@typescript-eslint/typescript-estree": "6.3.0", - "@typescript-eslint/utils": "6.3.0", + "@typescript-eslint/typescript-estree": "6.4.0", + "@typescript-eslint/utils": "6.4.0", "debug": "^4.3.4", "ts-api-utils": "^1.0.1" } }, "@typescript-eslint/types": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.3.0.tgz", - "integrity": "sha512-K6TZOvfVyc7MO9j60MkRNWyFSf86IbOatTKGrpTQnzarDZPYPVy0oe3myTMq7VjhfsUAbNUW8I5s+2lZvtx1gg==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.4.0.tgz", + "integrity": "sha512-+FV9kVFrS7w78YtzkIsNSoYsnOtrYVnKWSTVXoL1761CsCRv5wpDOINgsXpxD67YCLZtVQekDDyaxfjVWUJmmg==", "dev": true }, "@typescript-eslint/typescript-estree": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.3.0.tgz", - "integrity": "sha512-Xh4NVDaC4eYKY4O3QGPuQNp5NxBAlEvNQYOqJquR2MePNxO11E5K3t5x4M4Mx53IZvtpW+mBxIT0s274fLUocg==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.4.0.tgz", + "integrity": "sha512-iDPJArf/K2sxvjOR6skeUCNgHR/tCQXBsa+ee1/clRKr3olZjZ/dSkXPZjG6YkPtnW6p5D1egeEPMCW6Gn4yLA==", "dev": true, "requires": { - "@typescript-eslint/types": "6.3.0", - "@typescript-eslint/visitor-keys": "6.3.0", + "@typescript-eslint/types": "6.4.0", + "@typescript-eslint/visitor-keys": "6.4.0", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -4527,27 +4519,27 @@ } }, "@typescript-eslint/utils": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.3.0.tgz", - "integrity": "sha512-hLLg3BZE07XHnpzglNBG8P/IXq/ZVXraEbgY7FM0Cnc1ehM8RMdn9mat3LubJ3KBeYXXPxV1nugWbQPjGeJk6Q==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.4.0.tgz", + "integrity": "sha512-BvvwryBQpECPGo8PwF/y/q+yacg8Hn/2XS+DqL/oRsOPK+RPt29h5Ui5dqOKHDlbXrAeHUTnyG3wZA0KTDxRZw==", "dev": true, "requires": { "@eslint-community/eslint-utils": "^4.4.0", "@types/json-schema": "^7.0.12", "@types/semver": "^7.5.0", - "@typescript-eslint/scope-manager": "6.3.0", - "@typescript-eslint/types": "6.3.0", - "@typescript-eslint/typescript-estree": "6.3.0", + "@typescript-eslint/scope-manager": "6.4.0", + "@typescript-eslint/types": "6.4.0", + "@typescript-eslint/typescript-estree": "6.4.0", "semver": "^7.5.4" } }, "@typescript-eslint/visitor-keys": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.3.0.tgz", - "integrity": "sha512-kEhRRj7HnvaSjux1J9+7dBen15CdWmDnwrpyiHsFX6Qx2iW5LOBUgNefOFeh2PjWPlNwN8TOn6+4eBU3J/gupw==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.4.0.tgz", + "integrity": "sha512-yJSfyT+uJm+JRDWYRYdCm2i+pmvXJSMtPR9Cq5/XQs4QIgNoLcoRtDdzsLbLsFM/c6um6ohQkg/MLxWvoIndJA==", "dev": true, "requires": { - "@typescript-eslint/types": "6.3.0", + "@typescript-eslint/types": "6.4.0", "eslint-visitor-keys": "^3.4.1" } }, @@ -5932,12 +5924,6 @@ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", "dev": true }, - "natural-compare-lite": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz", - "integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==", - "dev": true - }, "node-domexception": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", From 3607acedb766da86292097079109f9fcea6b1d8b Mon Sep 17 00:00:00 2001 From: Hardik Date: Tue, 15 Aug 2023 14:16:10 +0530 Subject: [PATCH 17/81] updating the Unit Test Case --- tests/cases/fourslash/autoImportNonModules.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/cases/fourslash/autoImportNonModules.ts b/tests/cases/fourslash/autoImportNonModules.ts index 3cdd8ac4f47fe..fc7781a5d547f 100644 --- a/tests/cases/fourslash/autoImportNonModules.ts +++ b/tests/cases/fourslash/autoImportNonModules.ts @@ -7,4 +7,9 @@ //// /**/ goTo.marker(""); -verify.completions(); \ No newline at end of file +verify.completions({ + excludes: ["f"], + preferences: { + includeCompletionsForModuleExports: true + } + }); \ No newline at end of file From f37d2ad6693bbe1d697619c709bd29f17d526fd7 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 15 Aug 2023 08:29:36 -0700 Subject: [PATCH 18/81] Prevent detached diagnostics from running off the end of the file (#55381) --- src/compiler/parser.ts | 12 +++++------ src/compiler/utilities.ts | 21 ++++++++++--------- .../parseUnmatchedTypeAssertion.errors.txt | 21 +++++++++++++++++++ .../reference/parseUnmatchedTypeAssertion.js | 8 +++++++ .../parseUnmatchedTypeAssertion.symbols | 6 ++++++ .../parseUnmatchedTypeAssertion.types | 9 ++++++++ .../compiler/parseUnmatchedTypeAssertion.ts | 1 + 7 files changed, 62 insertions(+), 16 deletions(-) create mode 100644 tests/baselines/reference/parseUnmatchedTypeAssertion.errors.txt create mode 100644 tests/baselines/reference/parseUnmatchedTypeAssertion.js create mode 100644 tests/baselines/reference/parseUnmatchedTypeAssertion.symbols create mode 100644 tests/baselines/reference/parseUnmatchedTypeAssertion.types create mode 100644 tests/cases/compiler/parseUnmatchedTypeAssertion.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index bd8081d1267a1..103a1b08fa837 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1803,7 +1803,7 @@ namespace Parser { return sourceFile; function reportPragmaDiagnostic(pos: number, end: number, diagnostic: DiagnosticMessage) { - parseDiagnostics.push(createDetachedDiagnostic(fileName, pos, end, diagnostic)); + parseDiagnostics.push(createDetachedDiagnostic(fileName, sourceText, pos, end, diagnostic)); } } @@ -2118,7 +2118,7 @@ namespace Parser { const lastError = lastOrUndefined(parseDiagnostics); let result: DiagnosticWithDetachedLocation | undefined; if (!lastError || start !== lastError.start) { - result = createDetachedDiagnostic(fileName, start, length, message, ...args); + result = createDetachedDiagnostic(fileName, sourceText, start, length, message, ...args); parseDiagnostics.push(result); } @@ -2470,7 +2470,7 @@ namespace Parser { if (lastError) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)) + createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)) ); } } @@ -4486,7 +4486,7 @@ namespace Parser { if (lastError && lastError.code === Diagnostics._0_expected.code) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") + createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") ); } } @@ -8326,7 +8326,7 @@ namespace Parser { if (lastError && lastError.code === Diagnostics._0_expected.code) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") + createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") ); } } @@ -9429,7 +9429,7 @@ namespace Parser { if (childTypeTag) { const lastError = parseErrorAtCurrentToken(Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); if (lastError) { - addRelatedInfo(lastError, createDetachedDiagnostic(fileName, 0, 0, Diagnostics.The_tag_was_first_specified_here)); + addRelatedInfo(lastError, createDetachedDiagnostic(fileName, sourceText, 0, 0, Diagnostics.The_tag_was_first_specified_here)); } break; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 75e1f55abc6f6..4eb8cc9d52aeb 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2150,19 +2150,16 @@ export function createDiagnosticForNodeArrayFromMessageChain(sourceFile: SourceF return createFileDiagnosticFromMessageChain(sourceFile, start, nodes.end - start, messageChain, relatedInformation); } -function assertDiagnosticLocation(file: SourceFile | undefined, start: number, length: number) { +function assertDiagnosticLocation(sourceText: string, start: number, length: number) { Debug.assertGreaterThanOrEqual(start, 0); Debug.assertGreaterThanOrEqual(length, 0); - - if (file) { - Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(start + length, file.text.length); - } + Debug.assertLessThanOrEqual(start, sourceText.length); + Debug.assertLessThanOrEqual(start + length, sourceText.length); } /** @internal */ export function createFileDiagnosticFromMessageChain(file: SourceFile, start: number, length: number, messageChain: DiagnosticMessageChain, relatedInformation?: DiagnosticRelatedInformation[]): DiagnosticWithLocation { - assertDiagnosticLocation(file, start, length); + assertDiagnosticLocation(file.text, start, length); return { file, start, @@ -8152,8 +8149,12 @@ export function getLocaleSpecificMessage(message: DiagnosticMessage) { } /** @internal */ -export function createDetachedDiagnostic(fileName: string, start: number, length: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithDetachedLocation { - assertDiagnosticLocation(/*file*/ undefined, start, length); +export function createDetachedDiagnostic(fileName: string, sourceText: string, start: number, length: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithDetachedLocation { + if ((start + length) > sourceText.length) { + length = sourceText.length - start; + } + + assertDiagnosticLocation(sourceText, start, length); let text = getLocaleSpecificMessage(message); if (some(args)) { @@ -8222,7 +8223,7 @@ export function attachFileToDiagnostics(diagnostics: DiagnosticWithDetachedLocat /** @internal */ export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithLocation { - assertDiagnosticLocation(file, start, length); + assertDiagnosticLocation(file.text, start, length); let text = getLocaleSpecificMessage(message); diff --git a/tests/baselines/reference/parseUnmatchedTypeAssertion.errors.txt b/tests/baselines/reference/parseUnmatchedTypeAssertion.errors.txt new file mode 100644 index 0000000000000..112a51fb92e93 --- /dev/null +++ b/tests/baselines/reference/parseUnmatchedTypeAssertion.errors.txt @@ -0,0 +1,21 @@ +parseUnmatchedTypeAssertion.ts(1,2): error TS1109: Expression expected. +parseUnmatchedTypeAssertion.ts(1,12): error TS1141: String literal expected. +parseUnmatchedTypeAssertion.ts(1,12): error TS2304: Cannot find name 'obju2c77'. +parseUnmatchedTypeAssertion.ts(1,21): error TS1109: Expression expected. +parseUnmatchedTypeAssertion.ts(2,1): error TS1005: '{' expected. + + +==== parseUnmatchedTypeAssertion.ts (5 errors) ==== + @<[[import(obju2c77, + ~ +!!! error TS1109: Expression expected. + ~~~~~~~~ +!!! error TS1141: String literal expected. + ~~~~~~~~ +!!! error TS2304: Cannot find name 'obju2c77'. + +!!! error TS1109: Expression expected. + + +!!! error TS1005: '{' expected. +!!! related TS1007 parseUnmatchedTypeAssertion.ts:2:1: The parser expected to find a '}' to match the '{' token here. \ No newline at end of file diff --git a/tests/baselines/reference/parseUnmatchedTypeAssertion.js b/tests/baselines/reference/parseUnmatchedTypeAssertion.js new file mode 100644 index 0000000000000..1400afd182e9f --- /dev/null +++ b/tests/baselines/reference/parseUnmatchedTypeAssertion.js @@ -0,0 +1,8 @@ +//// [tests/cases/compiler/parseUnmatchedTypeAssertion.ts] //// + +//// [parseUnmatchedTypeAssertion.ts] +@<[[import(obju2c77, + + +//// [parseUnmatchedTypeAssertion.js] +; diff --git a/tests/baselines/reference/parseUnmatchedTypeAssertion.symbols b/tests/baselines/reference/parseUnmatchedTypeAssertion.symbols new file mode 100644 index 0000000000000..6cd1af0bb28b4 --- /dev/null +++ b/tests/baselines/reference/parseUnmatchedTypeAssertion.symbols @@ -0,0 +1,6 @@ +//// [tests/cases/compiler/parseUnmatchedTypeAssertion.ts] //// + +=== parseUnmatchedTypeAssertion.ts === +@<[[import(obju2c77, +>obju2c77 : Symbol(obju2c77) + diff --git a/tests/baselines/reference/parseUnmatchedTypeAssertion.types b/tests/baselines/reference/parseUnmatchedTypeAssertion.types new file mode 100644 index 0000000000000..764b3105c6244 --- /dev/null +++ b/tests/baselines/reference/parseUnmatchedTypeAssertion.types @@ -0,0 +1,9 @@ +//// [tests/cases/compiler/parseUnmatchedTypeAssertion.ts] //// + +=== parseUnmatchedTypeAssertion.ts === +@<[[import(obju2c77, +> : any +><[[import(obju2c77, : [[any]] + +> : any + diff --git a/tests/cases/compiler/parseUnmatchedTypeAssertion.ts b/tests/cases/compiler/parseUnmatchedTypeAssertion.ts new file mode 100644 index 0000000000000..8247772f3c9a7 --- /dev/null +++ b/tests/cases/compiler/parseUnmatchedTypeAssertion.ts @@ -0,0 +1 @@ +@<[[import(obju2c77, From defb504be69422b8d4ca1c47a5aae9b46a171aeb Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 15 Aug 2023 08:54:21 -0700 Subject: [PATCH 19/81] Remove allowComplexConstraintInference in inferTypes (#54815) --- src/compiler/checker.ts | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 33441d618d79a..14b99c264518e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -24491,7 +24491,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let bivariant = false; let propagationType: Type; let inferencePriority: number = InferencePriority.MaxValue; - let allowComplexConstraintInference = true; let visited: Map; let sourceStack: Type[]; let targetStack: Type[]; @@ -24697,15 +24696,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` // with the simplified source. - if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (TypeFlags.Object | TypeFlags.Intersection))) { - // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! - // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference - // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves - // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations - // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. - // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just - // remove this `allowComplexConstraintInference` flag. - allowComplexConstraintInference = false; + if (apparentSource !== source && !(apparentSource.flags & (TypeFlags.Object | TypeFlags.Intersection))) { return inferFromTypes(apparentSource, target); } source = apparentSource; From 8863e2f57a741b21a23034ef740c1231ea318757 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Tue, 15 Aug 2023 17:58:59 +0200 Subject: [PATCH 20/81] Discriminate contextual types using shorthand properties (#55151) --- src/compiler/checker.ts | 23 ++++++++++++++----- .../contextuallyTypedByDiscriminableUnion.js | 15 ++++++++++++ ...textuallyTypedByDiscriminableUnion.symbols | 18 +++++++++++++++ ...ontextuallyTypedByDiscriminableUnion.types | 22 ++++++++++++++++++ .../contextuallyTypedByDiscriminableUnion.ts | 8 +++++++ 5 files changed, 80 insertions(+), 6 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 14b99c264518e..51cee644b170d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22785,7 +22785,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: [() => Type, __String][], related: (source: Type, target: Type) => boolean | Ternary) { + function discriminateTypeByDiscriminableItems(target: UnionType, discriminators: (readonly [() => Type, __String])[], related: (source: Type, target: Type) => boolean | Ternary) { const types = target.types; const include: Ternary[] = types.map(t => t.flags & TypeFlags.Primitive ? Ternary.False : Ternary.True); for (const [getDiscriminatingType, propertyName] of discriminators) { @@ -29438,12 +29438,23 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, concatenate( map( - filter(node.properties, p => !!p.symbol && p.kind === SyntaxKind.PropertyAssignment && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName)), - prop => ([() => getContextFreeTypeOfExpression((prop as PropertyAssignment).initializer), prop.symbol.escapedName] as [() => Type, __String]) + filter(node.properties, (p): p is PropertyAssignment | ShorthandPropertyAssignment => { + if (!p.symbol) { + return false; + } + if (p.kind === SyntaxKind.PropertyAssignment) { + return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); + } + if (p.kind === SyntaxKind.ShorthandPropertyAssignment) { + return isDiscriminantProperty(contextualType, p.symbol.escapedName); + } + return false; + }), + prop => ([() => getContextFreeTypeOfExpression(prop.kind === SyntaxKind.PropertyAssignment ? prop.initializer : prop.name), prop.symbol.escapedName] as const) ), map( filter(getPropertiesOfType(contextualType), s => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)), - s => [() => undefinedType, s.escapedName] as [() => Type, __String] + s => [() => undefinedType, s.escapedName] as const ) ), isTypeAssignableTo @@ -29456,7 +29467,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { concatenate( map( filter(node.properties, p => !!p.symbol && p.kind === SyntaxKind.JsxAttribute && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), - prop => ([!(prop as JsxAttribute).initializer ? (() => trueType) : (() => getContextFreeTypeOfExpression((prop as JsxAttribute).initializer!)), prop.symbol.escapedName] as [() => Type, __String]) + prop => ([!(prop as JsxAttribute).initializer ? (() => trueType) : (() => getContextFreeTypeOfExpression((prop as JsxAttribute).initializer!)), prop.symbol.escapedName] as const) ), map( filter(getPropertiesOfType(contextualType), s => { @@ -29469,7 +29480,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), - s => [() => undefinedType, s.escapedName] as [() => Type, __String] + s => [() => undefinedType, s.escapedName] as const ) ), isTypeAssignableTo diff --git a/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.js b/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.js index a579ea475fe54..fa95921349075 100644 --- a/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.js +++ b/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.js @@ -25,6 +25,14 @@ invoke({ return +a; } }); + +const kind = "a" +invoke({ + kind, + method(a) { + return +a; + } +}) //// [contextuallyTypedByDiscriminableUnion.js] @@ -42,3 +50,10 @@ invoke({ return +a; } }); +var kind = "a"; +invoke({ + kind: kind, + method: function (a) { + return +a; + } +}); diff --git a/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.symbols b/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.symbols index fdc04d2d71560..42919a16fb713 100644 --- a/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.symbols +++ b/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.symbols @@ -60,3 +60,21 @@ invoke({ } }); +const kind = "a" +>kind : Symbol(kind, Decl(contextuallyTypedByDiscriminableUnion.ts, 25, 5)) + +invoke({ +>invoke : Symbol(invoke, Decl(contextuallyTypedByDiscriminableUnion.ts, 6, 2)) + + kind, +>kind : Symbol(kind, Decl(contextuallyTypedByDiscriminableUnion.ts, 26, 8)) + + method(a) { +>method : Symbol(method, Decl(contextuallyTypedByDiscriminableUnion.ts, 27, 9)) +>a : Symbol(a, Decl(contextuallyTypedByDiscriminableUnion.ts, 28, 11)) + + return +a; +>a : Symbol(a, Decl(contextuallyTypedByDiscriminableUnion.ts, 28, 11)) + } +}) + diff --git a/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.types b/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.types index ee40ce1a95e0e..a10b904822187 100644 --- a/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.types +++ b/tests/baselines/reference/contextuallyTypedByDiscriminableUnion.types @@ -69,3 +69,25 @@ invoke({ } }); +const kind = "a" +>kind : "a" +>"a" : "a" + +invoke({ +>invoke({ kind, method(a) { return +a; }}) : void +>invoke : (item: ADT) => void +>{ kind, method(a) { return +a; }} : { kind: "a"; method(a: string): number; } + + kind, +>kind : "a" + + method(a) { +>method : (a: string) => number +>a : string + + return +a; +>+a : number +>a : string + } +}) + diff --git a/tests/cases/compiler/contextuallyTypedByDiscriminableUnion.ts b/tests/cases/compiler/contextuallyTypedByDiscriminableUnion.ts index 5fbcd2dbbc55e..03504aec9dd09 100644 --- a/tests/cases/compiler/contextuallyTypedByDiscriminableUnion.ts +++ b/tests/cases/compiler/contextuallyTypedByDiscriminableUnion.ts @@ -23,3 +23,11 @@ invoke({ return +a; } }); + +const kind = "a" +invoke({ + kind, + method(a) { + return +a; + } +}) From 0099e42451b39ac0dc0816a31659820a0f014d31 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Tue, 15 Aug 2023 21:41:00 +0300 Subject: [PATCH 21/81] fix(55374): Invalid Parameter Inlay Hint (#55384) --- src/services/inlayHints.ts | 4 +- .../inlayHintsParameterNames.baseline | 45 +++++++++++-------- .../fourslash/inlayHintsParameterNames.ts | 3 ++ 3 files changed, 33 insertions(+), 19 deletions(-) diff --git a/src/services/inlayHints.ts b/src/services/inlayHints.ts index 062cc87f72f20..b7c8f87b7250a 100644 --- a/src/services/inlayHints.ts +++ b/src/services/inlayHints.ts @@ -247,11 +247,13 @@ export function provideInlayHints(context: InlayHintsContext): InlayHint[] { return; } - let signatureParamPos = 0; const sourceFile = shouldUseInteractiveInlayHints(preferences) ? expr.getSourceFile() : undefined; + + let signatureParamPos = 0; for (const originalArg of args) { const arg = skipParentheses(originalArg); if (shouldShowLiteralParameterNameHintsOnly(preferences) && !isHintableLiteral(arg)) { + signatureParamPos++; continue; } diff --git a/tests/baselines/reference/inlayHintsParameterNames.baseline b/tests/baselines/reference/inlayHintsParameterNames.baseline index bb7fd50b15c25..3be094c27bea4 100644 --- a/tests/baselines/reference/inlayHintsParameterNames.baseline +++ b/tests/baselines/reference/inlayHintsParameterNames.baseline @@ -25,11 +25,20 @@ "whitespaceAfter": true } +foo3({}, 1); + ^ +{ + "text": "b:", + "position": 161, + "kind": "Parameter", + "whitespaceAfter": true +} + const C1 = class extends foo3(1) { } ^ { "text": "a:", - "position": 180, + "position": 229, "kind": "Parameter", "whitespaceAfter": true } @@ -38,7 +47,7 @@ class C2 extends foo3(1) { } ^ { "text": "a:", - "position": 209, + "position": 258, "kind": "Parameter", "whitespaceAfter": true } @@ -47,7 +56,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "a:", - "position": 282, + "position": 331, "kind": "Parameter", "whitespaceAfter": true } @@ -56,7 +65,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "b:", - "position": 285, + "position": 334, "kind": "Parameter", "whitespaceAfter": true } @@ -65,7 +74,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "c:", - "position": 289, + "position": 338, "kind": "Parameter", "whitespaceAfter": true } @@ -74,7 +83,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "d:", - "position": 293, + "position": 342, "kind": "Parameter", "whitespaceAfter": true } @@ -83,7 +92,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "a:", - "position": 484, + "position": 533, "kind": "Parameter", "whitespaceAfter": true } @@ -92,7 +101,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "b:", - "position": 497, + "position": 546, "kind": "Parameter", "whitespaceAfter": true } @@ -101,7 +110,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "c:", - "position": 512, + "position": 561, "kind": "Parameter", "whitespaceAfter": true } @@ -110,7 +119,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "d:", - "position": 522, + "position": 571, "kind": "Parameter", "whitespaceAfter": true } @@ -119,7 +128,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "e:", - "position": 532, + "position": 581, "kind": "Parameter", "whitespaceAfter": true } @@ -128,7 +137,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "f:", - "position": 543, + "position": 592, "kind": "Parameter", "whitespaceAfter": true } @@ -137,7 +146,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "g:", - "position": 557, + "position": 606, "kind": "Parameter", "whitespaceAfter": true } @@ -146,7 +155,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "h:", - "position": 572, + "position": 621, "kind": "Parameter", "whitespaceAfter": true } @@ -155,7 +164,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "i:", - "position": 581, + "position": 630, "kind": "Parameter", "whitespaceAfter": true } @@ -164,7 +173,7 @@ foo4(1, +1, -1, +"1"); ^ { "text": "j:", - "position": 595, + "position": 644, "kind": "Parameter", "whitespaceAfter": true } @@ -173,7 +182,7 @@ trace(`${1}`); ^ { "text": "message:", - "position": 694, + "position": 743, "kind": "Parameter", "whitespaceAfter": true } @@ -182,7 +191,7 @@ trace(``); ^ { "text": "message:", - "position": 709, + "position": 758, "kind": "Parameter", "whitespaceAfter": true } \ No newline at end of file diff --git a/tests/cases/fourslash/inlayHintsParameterNames.ts b/tests/cases/fourslash/inlayHintsParameterNames.ts index abcea666a37e1..1c1f8fa21be16 100644 --- a/tests/cases/fourslash/inlayHintsParameterNames.ts +++ b/tests/cases/fourslash/inlayHintsParameterNames.ts @@ -6,6 +6,9 @@ //// function foo2 (a: number, { c }: any) {} //// foo2(1, { c: 1 }); +////function foo3(a: any, b: number) {} +////foo3({}, 1); + ////const foo3 = (a = 1) => class { } ////const C1 = class extends foo3(1) { } ////class C2 extends foo3(1) { } From b8b0d26cb9b9b0573affc6cb2faaa6227db9f49b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Tue, 15 Aug 2023 21:01:21 +0200 Subject: [PATCH 22/81] Display write type for property accesses in write locations (#54777) --- src/compiler/checker.ts | 8 ++++++-- .../quickInfoOnPropertyAccessInWriteLocation1.ts | 8 ++++++++ .../quickInfoOnPropertyAccessInWriteLocation2.ts | 8 ++++++++ .../quickInfoOnPropertyAccessInWriteLocation3.ts | 8 ++++++++ .../quickInfoOnPropertyAccessInWriteLocation4.ts | 11 +++++++++++ .../quickInfoOnPropertyAccessInWriteLocation5.ts | 11 +++++++++++ 6 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation1.ts create mode 100644 tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation2.ts create mode 100644 tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation3.ts create mode 100644 tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation4.ts create mode 100644 tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation5.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 51cee644b170d..06c2808a3932f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11541,7 +11541,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { getWriteTypeOfSymbolWithDeferredType(symbol) || getTypeOfSymbolWithDeferredType(symbol) : // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty (symbol as TransientSymbol).links.writeType || (symbol as TransientSymbol).links.type! : - getTypeOfSymbol(symbol); + removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & SymbolFlags.Optional)); } if (symbol.flags & SymbolFlags.Accessor) { return checkFlags & CheckFlags.Instantiated ? @@ -27703,7 +27703,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { location = location.parent; } if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) { - const type = removeOptionalTypeMarker(getTypeOfExpression(location as Expression)); + const type = removeOptionalTypeMarker( + isWriteAccess(location) && location.kind === SyntaxKind.PropertyAccessExpression ? + checkPropertyAccessExpression(location as PropertyAccessExpression, /*checkMode*/ undefined, /*writeOnly*/ true) : + getTypeOfExpression(location as Expression) + ); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; } diff --git a/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation1.ts b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation1.ts new file mode 100644 index 0000000000000..81299002a12e5 --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation1.ts @@ -0,0 +1,8 @@ +/// + +// @strict: true +// @exactOptionalPropertyTypes: true +//// declare const xx: { prop?: number }; +//// xx.prop/*1*/ = 1; + +verify.quickInfoAt('1', '(property) prop?: number'); diff --git a/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation2.ts b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation2.ts new file mode 100644 index 0000000000000..02babc99c2250 --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation2.ts @@ -0,0 +1,8 @@ +/// + +// @strict: true +// @exactOptionalPropertyTypes: true +//// declare const xx: { prop?: number }; +//// xx.prop/*1*/ += 1; + +verify.quickInfoAt('1', '(property) prop?: number'); diff --git a/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation3.ts b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation3.ts new file mode 100644 index 0000000000000..6b2e7092c33b2 --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation3.ts @@ -0,0 +1,8 @@ +/// + +// @strict: true +// @exactOptionalPropertyTypes: true +//// declare const xx: { prop?: number }; +//// xx.prop/*1*/ ??= 1; + +verify.quickInfoAt('1', '(property) prop?: number'); diff --git a/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation4.ts b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation4.ts new file mode 100644 index 0000000000000..acf55817c39ee --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation4.ts @@ -0,0 +1,11 @@ +/// + +// @strict: true +//// interface Serializer { +//// set value(v: string | number | boolean); +//// get value(): string; +//// } +//// declare let box: Serializer; +//// box.value/*1*/ = true; + +verify.quickInfoAt('1', '(property) Serializer.value: string | number | boolean'); diff --git a/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation5.ts b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation5.ts new file mode 100644 index 0000000000000..06ea4ba9166d3 --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnPropertyAccessInWriteLocation5.ts @@ -0,0 +1,11 @@ +/// + +// @strict: true +//// interface Serializer { +//// set value(v: string | number); +//// get value(): string; +//// } +//// declare let box: Serializer; +//// box.value/*1*/ += 10; + +verify.quickInfoAt('1', '(property) Serializer.value: string | number'); From cac899d44d19a2753e6cae9ebc8bd291fa571c76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Wed, 16 Aug 2023 01:53:11 +0200 Subject: [PATCH 23/81] Widen widening literal types through compound-like assignments (#52493) --- src/compiler/checker.ts | 10 +- src/compiler/factory/utilities.ts | 3 +- src/compiler/utilities.ts | 78 +++++--- ...ideningWithCompoundLikeAssignments.symbols | 135 ++++++++++++++ ...lWideningWithCompoundLikeAssignments.types | 169 ++++++++++++++++++ ...eralWideningWithCompoundLikeAssignments.ts | 52 ++++++ 6 files changed, 421 insertions(+), 26 deletions(-) create mode 100644 tests/baselines/reference/literalWideningWithCompoundLikeAssignments.symbols create mode 100644 tests/baselines/reference/literalWideningWithCompoundLikeAssignments.types create mode 100644 tests/cases/compiler/literalWideningWithCompoundLikeAssignments.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 06c2808a3932f..918da100936a7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -554,6 +554,7 @@ import { isImportOrExportSpecifier, isImportSpecifier, isImportTypeNode, + isInCompoundLikeAssignment, isIndexedAccessTypeNode, isInExpressionContext, isInfinityOrNaNString, @@ -26729,10 +26730,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & TypeFlags.Union) { - return getAssignmentReducedType(declaredType as UnionType, getInitialOrAssignedType(flow)); + const t = isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(declaredType) : declaredType; + if (t.flags & TypeFlags.Union) { + return getAssignmentReducedType(t as UnionType, getInitialOrAssignedType(flow)); } - return declaredType; + return t; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -28079,7 +28081,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // entities we simply return the declared type. if (localOrExportSymbol.flags & SymbolFlags.Variable) { if (assignmentKind === AssignmentKind.Definite) { - return type; + return isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(type) : type; } } else if (isAlias) { diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts index 3aa6f5e654834..221d4874d5226 100644 --- a/src/compiler/factory/utilities.ts +++ b/src/compiler/factory/utilities.ts @@ -1222,7 +1222,8 @@ function isShiftOperator(kind: SyntaxKind): kind is ShiftOperator { || kind === SyntaxKind.GreaterThanGreaterThanGreaterThanToken; } -function isShiftOperatorOrHigher(kind: SyntaxKind): kind is ShiftOperatorOrHigher { +/** @internal */ +export function isShiftOperatorOrHigher(kind: SyntaxKind): kind is ShiftOperatorOrHigher { return isShiftOperator(kind) || isAdditiveOperatorOrHigher(kind); } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 4eb8cc9d52aeb..f00b10dbc7bb6 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -152,8 +152,6 @@ import { forEachChild, forEachChildRecursively, ForInOrOfStatement, - ForInStatement, - ForOfStatement, ForStatement, FunctionBody, FunctionDeclaration, @@ -331,6 +329,7 @@ import { isQualifiedName, isRootedDiskPath, isSetAccessorDeclaration, + isShiftOperatorOrHigher, isShorthandPropertyAssignment, isSourceFile, isString, @@ -3418,9 +3417,9 @@ export function isInExpressionContext(node: Node): boolean { forStatement.incrementor === node; case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: - const forInStatement = parent as ForInStatement | ForOfStatement; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) || - forInStatement.expression === node; + const forInOrOfStatement = parent as ForInOrOfStatement; + return (forInOrOfStatement.initializer === node && forInOrOfStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) || + forInOrOfStatement.expression === node; case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: return node === (parent as AssertionExpression).expression; @@ -4468,23 +4467,29 @@ export const enum AssignmentKind { None, Definite, Compound } -/** @internal */ -export function getAssignmentTargetKind(node: Node): AssignmentKind { +type AssignmentTarget = + | BinaryExpression + | PrefixUnaryExpression + | PostfixUnaryExpression + | ForInOrOfStatement; + +function getAssignmentTarget(node: Node): AssignmentTarget | undefined { let parent = node.parent; while (true) { switch (parent.kind) { case SyntaxKind.BinaryExpression: - const binaryOperator = (parent as BinaryExpression).operatorToken.kind; - return isAssignmentOperator(binaryOperator) && (parent as BinaryExpression).left === node ? - binaryOperator === SyntaxKind.EqualsToken || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? AssignmentKind.Definite : AssignmentKind.Compound : - AssignmentKind.None; + const binaryExpression = parent as BinaryExpression; + const binaryOperator = binaryExpression.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && binaryExpression.left === node ? binaryExpression : undefined; case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: - const unaryOperator = (parent as PrefixUnaryExpression | PostfixUnaryExpression).operator; - return unaryOperator === SyntaxKind.PlusPlusToken || unaryOperator === SyntaxKind.MinusMinusToken ? AssignmentKind.Compound : AssignmentKind.None; + const unaryExpression = (parent as PrefixUnaryExpression | PostfixUnaryExpression); + const unaryOperator = unaryExpression.operator; + return unaryOperator === SyntaxKind.PlusPlusToken || unaryOperator === SyntaxKind.MinusMinusToken ? unaryExpression : undefined; case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: - return (parent as ForInOrOfStatement).initializer === node ? AssignmentKind.Definite : AssignmentKind.None; + const forInOrOfStatement = parent as ForInOrOfStatement; + return forInOrOfStatement.initializer === node ? forInOrOfStatement : undefined; case SyntaxKind.ParenthesizedExpression: case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.SpreadElement: @@ -4496,30 +4501,62 @@ export function getAssignmentTargetKind(node: Node): AssignmentKind { break; case SyntaxKind.ShorthandPropertyAssignment: if ((parent as ShorthandPropertyAssignment).name !== node) { - return AssignmentKind.None; + return undefined; } node = parent.parent; break; case SyntaxKind.PropertyAssignment: - if ((parent as ShorthandPropertyAssignment).name === node) { - return AssignmentKind.None; + if ((parent as PropertyAssignment).name === node) { + return undefined; } node = parent.parent; break; default: - return AssignmentKind.None; + return undefined; } parent = node.parent; } } +/** @internal */ +export function getAssignmentTargetKind(node: Node): AssignmentKind { + const target = getAssignmentTarget(node); + if (!target) { + return AssignmentKind.None; + } + switch (target.kind) { + case SyntaxKind.BinaryExpression: + const binaryOperator = target.operatorToken.kind; + return binaryOperator === SyntaxKind.EqualsToken || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? + AssignmentKind.Definite : + AssignmentKind.Compound; + case SyntaxKind.PrefixUnaryExpression: + case SyntaxKind.PostfixUnaryExpression: + return AssignmentKind.Compound; + case SyntaxKind.ForInStatement: + case SyntaxKind.ForOfStatement: + return AssignmentKind.Definite; + } +} + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'. // (Note that `p` is not a target in the above examples, only `a`.) /** @internal */ export function isAssignmentTarget(node: Node): boolean { - return getAssignmentTargetKind(node) !== AssignmentKind.None; + return !!getAssignmentTarget(node); +} + +function isCompoundLikeAssignment(assignment: AssignmentExpression): boolean { + const right = skipParentheses(assignment.right); + return right.kind === SyntaxKind.BinaryExpression && isShiftOperatorOrHigher((right as BinaryExpression).operatorToken.kind); +} + +/** @internal */ +export function isInCompoundLikeAssignment(node: Node): boolean { + const target = getAssignmentTarget(node); + return !!target && isAssignmentExpression(target, /*excludeCompoundAssignment*/ true) && isCompoundLikeAssignment(target); } /** @internal */ @@ -4534,8 +4571,7 @@ export type NodeWithPossibleHoistedDeclaration = | DefaultClause | LabeledStatement | ForStatement - | ForInStatement - | ForOfStatement + | ForInOrOfStatement | DoStatement | WhileStatement | TryStatement diff --git a/tests/baselines/reference/literalWideningWithCompoundLikeAssignments.symbols b/tests/baselines/reference/literalWideningWithCompoundLikeAssignments.symbols new file mode 100644 index 0000000000000..599027e35ffc5 --- /dev/null +++ b/tests/baselines/reference/literalWideningWithCompoundLikeAssignments.symbols @@ -0,0 +1,135 @@ +//// [tests/cases/compiler/literalWideningWithCompoundLikeAssignments.ts] //// + +=== literalWideningWithCompoundLikeAssignments.ts === +// repro from #13865 + +const empty: "" = ""; +>empty : Symbol(empty, Decl(literalWideningWithCompoundLikeAssignments.ts, 2, 5)) + +let foo = empty; +>foo : Symbol(foo, Decl(literalWideningWithCompoundLikeAssignments.ts, 3, 3)) +>empty : Symbol(empty, Decl(literalWideningWithCompoundLikeAssignments.ts, 2, 5)) + +foo = foo + "bar" +>foo : Symbol(foo, Decl(literalWideningWithCompoundLikeAssignments.ts, 3, 3)) +>foo : Symbol(foo, Decl(literalWideningWithCompoundLikeAssignments.ts, 3, 3)) + +foo // string +>foo : Symbol(foo, Decl(literalWideningWithCompoundLikeAssignments.ts, 3, 3)) + +declare const numLiteral: 0; +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +let t1 = numLiteral; +>t1 : Symbol(t1, Decl(literalWideningWithCompoundLikeAssignments.ts, 9, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t1 = t1 + 42 +>t1 : Symbol(t1, Decl(literalWideningWithCompoundLikeAssignments.ts, 9, 3)) +>t1 : Symbol(t1, Decl(literalWideningWithCompoundLikeAssignments.ts, 9, 3)) + +t1 // number +>t1 : Symbol(t1, Decl(literalWideningWithCompoundLikeAssignments.ts, 9, 3)) + +let t2 = numLiteral; +>t2 : Symbol(t2, Decl(literalWideningWithCompoundLikeAssignments.ts, 13, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t2 = t2 - 42 +>t2 : Symbol(t2, Decl(literalWideningWithCompoundLikeAssignments.ts, 13, 3)) +>t2 : Symbol(t2, Decl(literalWideningWithCompoundLikeAssignments.ts, 13, 3)) + +t2 // number +>t2 : Symbol(t2, Decl(literalWideningWithCompoundLikeAssignments.ts, 13, 3)) + +let t3 = numLiteral; +>t3 : Symbol(t3, Decl(literalWideningWithCompoundLikeAssignments.ts, 17, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t3 = t3 * 42 +>t3 : Symbol(t3, Decl(literalWideningWithCompoundLikeAssignments.ts, 17, 3)) +>t3 : Symbol(t3, Decl(literalWideningWithCompoundLikeAssignments.ts, 17, 3)) + +t3 // number +>t3 : Symbol(t3, Decl(literalWideningWithCompoundLikeAssignments.ts, 17, 3)) + +let t4 = numLiteral; +>t4 : Symbol(t4, Decl(literalWideningWithCompoundLikeAssignments.ts, 21, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t4 = t4 ** 42 +>t4 : Symbol(t4, Decl(literalWideningWithCompoundLikeAssignments.ts, 21, 3)) +>t4 : Symbol(t4, Decl(literalWideningWithCompoundLikeAssignments.ts, 21, 3)) + +t4 // number +>t4 : Symbol(t4, Decl(literalWideningWithCompoundLikeAssignments.ts, 21, 3)) + +let t5 = numLiteral; +>t5 : Symbol(t5, Decl(literalWideningWithCompoundLikeAssignments.ts, 25, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t5 = t5 / 42 +>t5 : Symbol(t5, Decl(literalWideningWithCompoundLikeAssignments.ts, 25, 3)) +>t5 : Symbol(t5, Decl(literalWideningWithCompoundLikeAssignments.ts, 25, 3)) + +t5 // number +>t5 : Symbol(t5, Decl(literalWideningWithCompoundLikeAssignments.ts, 25, 3)) + +let t6 = numLiteral; +>t6 : Symbol(t6, Decl(literalWideningWithCompoundLikeAssignments.ts, 29, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t6 = t6 % 42 +>t6 : Symbol(t6, Decl(literalWideningWithCompoundLikeAssignments.ts, 29, 3)) +>t6 : Symbol(t6, Decl(literalWideningWithCompoundLikeAssignments.ts, 29, 3)) + +t6 // number +>t6 : Symbol(t6, Decl(literalWideningWithCompoundLikeAssignments.ts, 29, 3)) + +let t7 = numLiteral; +>t7 : Symbol(t7, Decl(literalWideningWithCompoundLikeAssignments.ts, 33, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t7 = t7 >> 0 +>t7 : Symbol(t7, Decl(literalWideningWithCompoundLikeAssignments.ts, 33, 3)) +>t7 : Symbol(t7, Decl(literalWideningWithCompoundLikeAssignments.ts, 33, 3)) + +t7 // number +>t7 : Symbol(t7, Decl(literalWideningWithCompoundLikeAssignments.ts, 33, 3)) + +let t8 = numLiteral; +>t8 : Symbol(t8, Decl(literalWideningWithCompoundLikeAssignments.ts, 37, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t8 = t8 >>> 0 +>t8 : Symbol(t8, Decl(literalWideningWithCompoundLikeAssignments.ts, 37, 3)) +>t8 : Symbol(t8, Decl(literalWideningWithCompoundLikeAssignments.ts, 37, 3)) + +t8 // number +>t8 : Symbol(t8, Decl(literalWideningWithCompoundLikeAssignments.ts, 37, 3)) + +let t9 = numLiteral; +>t9 : Symbol(t9, Decl(literalWideningWithCompoundLikeAssignments.ts, 41, 3)) +>numLiteral : Symbol(numLiteral, Decl(literalWideningWithCompoundLikeAssignments.ts, 7, 13)) + +t9 = t9 << 0 +>t9 : Symbol(t9, Decl(literalWideningWithCompoundLikeAssignments.ts, 41, 3)) +>t9 : Symbol(t9, Decl(literalWideningWithCompoundLikeAssignments.ts, 41, 3)) + +t9 // number +>t9 : Symbol(t9, Decl(literalWideningWithCompoundLikeAssignments.ts, 41, 3)) + +declare const literalUnion: "a" | 0; +>literalUnion : Symbol(literalUnion, Decl(literalWideningWithCompoundLikeAssignments.ts, 45, 13)) + +let t10 = literalUnion; +>t10 : Symbol(t10, Decl(literalWideningWithCompoundLikeAssignments.ts, 46, 3)) +>literalUnion : Symbol(literalUnion, Decl(literalWideningWithCompoundLikeAssignments.ts, 45, 13)) + +t10 = t10 + 'b' +>t10 : Symbol(t10, Decl(literalWideningWithCompoundLikeAssignments.ts, 46, 3)) +>t10 : Symbol(t10, Decl(literalWideningWithCompoundLikeAssignments.ts, 46, 3)) + +t10 // string +>t10 : Symbol(t10, Decl(literalWideningWithCompoundLikeAssignments.ts, 46, 3)) + diff --git a/tests/baselines/reference/literalWideningWithCompoundLikeAssignments.types b/tests/baselines/reference/literalWideningWithCompoundLikeAssignments.types new file mode 100644 index 0000000000000..b605622a24b9c --- /dev/null +++ b/tests/baselines/reference/literalWideningWithCompoundLikeAssignments.types @@ -0,0 +1,169 @@ +//// [tests/cases/compiler/literalWideningWithCompoundLikeAssignments.ts] //// + +=== literalWideningWithCompoundLikeAssignments.ts === +// repro from #13865 + +const empty: "" = ""; +>empty : "" +>"" : "" + +let foo = empty; +>foo : "" +>empty : "" + +foo = foo + "bar" +>foo = foo + "bar" : string +>foo : string +>foo + "bar" : string +>foo : "" +>"bar" : "bar" + +foo // string +>foo : string + +declare const numLiteral: 0; +>numLiteral : 0 + +let t1 = numLiteral; +>t1 : 0 +>numLiteral : 0 + +t1 = t1 + 42 +>t1 = t1 + 42 : number +>t1 : number +>t1 + 42 : number +>t1 : 0 +>42 : 42 + +t1 // number +>t1 : number + +let t2 = numLiteral; +>t2 : 0 +>numLiteral : 0 + +t2 = t2 - 42 +>t2 = t2 - 42 : number +>t2 : number +>t2 - 42 : number +>t2 : 0 +>42 : 42 + +t2 // number +>t2 : number + +let t3 = numLiteral; +>t3 : 0 +>numLiteral : 0 + +t3 = t3 * 42 +>t3 = t3 * 42 : number +>t3 : number +>t3 * 42 : number +>t3 : 0 +>42 : 42 + +t3 // number +>t3 : number + +let t4 = numLiteral; +>t4 : 0 +>numLiteral : 0 + +t4 = t4 ** 42 +>t4 = t4 ** 42 : number +>t4 : number +>t4 ** 42 : number +>t4 : 0 +>42 : 42 + +t4 // number +>t4 : number + +let t5 = numLiteral; +>t5 : 0 +>numLiteral : 0 + +t5 = t5 / 42 +>t5 = t5 / 42 : number +>t5 : number +>t5 / 42 : number +>t5 : 0 +>42 : 42 + +t5 // number +>t5 : number + +let t6 = numLiteral; +>t6 : 0 +>numLiteral : 0 + +t6 = t6 % 42 +>t6 = t6 % 42 : number +>t6 : number +>t6 % 42 : number +>t6 : 0 +>42 : 42 + +t6 // number +>t6 : number + +let t7 = numLiteral; +>t7 : 0 +>numLiteral : 0 + +t7 = t7 >> 0 +>t7 = t7 >> 0 : number +>t7 : number +>t7 >> 0 : number +>t7 : 0 +>0 : 0 + +t7 // number +>t7 : number + +let t8 = numLiteral; +>t8 : 0 +>numLiteral : 0 + +t8 = t8 >>> 0 +>t8 = t8 >>> 0 : number +>t8 : number +>t8 >>> 0 : number +>t8 : 0 +>0 : 0 + +t8 // number +>t8 : number + +let t9 = numLiteral; +>t9 : 0 +>numLiteral : 0 + +t9 = t9 << 0 +>t9 = t9 << 0 : number +>t9 : number +>t9 << 0 : number +>t9 : 0 +>0 : 0 + +t9 // number +>t9 : number + +declare const literalUnion: "a" | 0; +>literalUnion : 0 | "a" + +let t10 = literalUnion; +>t10 : 0 | "a" +>literalUnion : 0 | "a" + +t10 = t10 + 'b' +>t10 = t10 + 'b' : string +>t10 : string | number +>t10 + 'b' : string +>t10 : 0 | "a" +>'b' : "b" + +t10 // string +>t10 : string + diff --git a/tests/cases/compiler/literalWideningWithCompoundLikeAssignments.ts b/tests/cases/compiler/literalWideningWithCompoundLikeAssignments.ts new file mode 100644 index 0000000000000..e61b19c228058 --- /dev/null +++ b/tests/cases/compiler/literalWideningWithCompoundLikeAssignments.ts @@ -0,0 +1,52 @@ +// @strict: true +// @noEmit: true + +// repro from #13865 + +const empty: "" = ""; +let foo = empty; +foo = foo + "bar" +foo // string + +declare const numLiteral: 0; + +let t1 = numLiteral; +t1 = t1 + 42 +t1 // number + +let t2 = numLiteral; +t2 = t2 - 42 +t2 // number + +let t3 = numLiteral; +t3 = t3 * 42 +t3 // number + +let t4 = numLiteral; +t4 = t4 ** 42 +t4 // number + +let t5 = numLiteral; +t5 = t5 / 42 +t5 // number + +let t6 = numLiteral; +t6 = t6 % 42 +t6 // number + +let t7 = numLiteral; +t7 = t7 >> 0 +t7 // number + +let t8 = numLiteral; +t8 = t8 >>> 0 +t8 // number + +let t9 = numLiteral; +t9 = t9 << 0 +t9 // number + +declare const literalUnion: "a" | 0; +let t10 = literalUnion; +t10 = t10 + 'b' +t10 // string From 08b2566e5b1beee5ff011d3e786ddd68ca81cbcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Wed, 16 Aug 2023 22:04:35 +0200 Subject: [PATCH 24/81] Add extra tests for type and value symbol merging (#55387) --- .../reference/typeValueMerge1.symbols | 33 +++++++++++++++++ .../baselines/reference/typeValueMerge1.types | 35 +++++++++++++++++++ .../externalModules/typeValueMerge1.ts | 17 +++++++++ 3 files changed, 85 insertions(+) create mode 100644 tests/baselines/reference/typeValueMerge1.symbols create mode 100644 tests/baselines/reference/typeValueMerge1.types create mode 100644 tests/cases/conformance/externalModules/typeValueMerge1.ts diff --git a/tests/baselines/reference/typeValueMerge1.symbols b/tests/baselines/reference/typeValueMerge1.symbols new file mode 100644 index 0000000000000..26ff1a4798c52 --- /dev/null +++ b/tests/baselines/reference/typeValueMerge1.symbols @@ -0,0 +1,33 @@ +//// [tests/cases/conformance/externalModules/typeValueMerge1.ts] //// + +=== other.ts === +export type A = string; +>A : Symbol(A, Decl(other.ts, 0, 0), Decl(other.ts, 2, 8)) + +function A() {} +>A : Symbol(A, Decl(other.ts, 0, 23), Decl(other.ts, 0, 0)) + +export { A }; +>A : Symbol(A, Decl(other.ts, 0, 0), Decl(other.ts, 2, 8)) + +export type B = string; +>B : Symbol(B, Decl(other.ts, 2, 13), Decl(other.ts, 6, 8)) + +var B = 10; +>B : Symbol(B, Decl(other.ts, 2, 13), Decl(other.ts, 5, 3)) + +export { B }; +>B : Symbol(B, Decl(other.ts, 2, 13), Decl(other.ts, 6, 8)) + +=== main.ts === +import { A, B } from "./other"; +>A : Symbol(A, Decl(main.ts, 0, 8)) +>B : Symbol(B, Decl(main.ts, 0, 11)) + +A(); +>A : Symbol(A, Decl(main.ts, 0, 8)) + +export const C = B; +>C : Symbol(C, Decl(main.ts, 4, 12)) +>B : Symbol(B, Decl(main.ts, 0, 11)) + diff --git a/tests/baselines/reference/typeValueMerge1.types b/tests/baselines/reference/typeValueMerge1.types new file mode 100644 index 0000000000000..6cb59009d5ed9 --- /dev/null +++ b/tests/baselines/reference/typeValueMerge1.types @@ -0,0 +1,35 @@ +//// [tests/cases/conformance/externalModules/typeValueMerge1.ts] //// + +=== other.ts === +export type A = string; +>A : string + +function A() {} +>A : () => void + +export { A }; +>A : () => void + +export type B = string; +>B : string + +var B = 10; +>B : number +>10 : 10 + +export { B }; +>B : number + +=== main.ts === +import { A, B } from "./other"; +>A : () => void +>B : number + +A(); +>A() : void +>A : () => void + +export const C = B; +>C : number +>B : number + diff --git a/tests/cases/conformance/externalModules/typeValueMerge1.ts b/tests/cases/conformance/externalModules/typeValueMerge1.ts new file mode 100644 index 0000000000000..c875af795ac1f --- /dev/null +++ b/tests/cases/conformance/externalModules/typeValueMerge1.ts @@ -0,0 +1,17 @@ +// @noEmit: true + +// @Filename: other.ts +export type A = string; +function A() {} +export { A }; + +export type B = string; +var B = 10; +export { B }; + +// @Filename: main.ts +import { A, B } from "./other"; + +A(); + +export const C = B; From ffec968d796b3aed7f15ef4dec93f7ae89d68352 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 16 Aug 2023 14:13:45 -0700 Subject: [PATCH 25/81] Don't track private symbol roots in other files during js declaration emit (#55390) --- src/compiler/checker.ts | 8 ++- .../jsDeclarationEmitDoesNotRenameImport.js | 62 +++++++++++++++++++ ...DeclarationEmitDoesNotRenameImport.symbols | 59 ++++++++++++++++++ ...jsDeclarationEmitDoesNotRenameImport.types | 62 +++++++++++++++++++ .../jsDeclarationEmitDoesNotRenameImport.ts | 34 ++++++++++ 5 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.js create mode 100644 tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.symbols create mode 100644 tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.types create mode 100644 tests/cases/compiler/jsDeclarationEmitDoesNotRenameImport.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 918da100936a7..d23a2c35a3f51 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8456,7 +8456,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Lookup the root symbol of the chain of refs we'll use to access it and serialize it const chain = lookupSymbolChainWorker(sym, context, meaning); if (!(sym.flags & SymbolFlags.Property)) { - includePrivateSymbol(chain[0]); + // Only include referenced privates in the same file. Weird JS aliases may expose privates + // from other files - assume JS transforms will make those available via expected means + const root = chain[0]; + const contextFile = getSourceFileOfNode(oldcontext.enclosingDeclaration); + if (some(root.declarations, d => getSourceFileOfNode(d) === contextFile)) { + includePrivateSymbol(root); + } } } else if (oldcontext.tracker.inner?.trackSymbol) { diff --git a/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.js b/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.js new file mode 100644 index 0000000000000..c519ea52a7c7d --- /dev/null +++ b/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.js @@ -0,0 +1,62 @@ +//// [tests/cases/compiler/jsDeclarationEmitDoesNotRenameImport.ts] //// + +//// [Test.js] +/** @module test/Test */ +class Test {} +export default Test; +//// [Test.js] +/** @module Test */ +class Test {} +export default Test; +//// [index.js] +import Test from './test/Test.js' + +/** + * @typedef {Object} Options + * @property {typeof import("./Test.js").default} [test] + */ + +class X extends Test { + /** + * @param {Options} options + */ + constructor(options) { + super(); + if (options.test) { + this.test = new options.test(); + } + } +} + +export default X; + + + + +//// [Test.d.ts] +export default Test; +/** @module test/Test */ +declare class Test { +} +//// [Test.d.ts] +export default Test; +/** @module Test */ +declare class Test { +} +//// [index.d.ts] +export default X; +export type Options = { + test?: typeof import("./Test.js").default | undefined; +}; +/** + * @typedef {Object} Options + * @property {typeof import("./Test.js").default} [test] + */ +declare class X extends Test { + /** + * @param {Options} options + */ + constructor(options: Options); + test: import("./Test.js").default | undefined; +} +import Test from './test/Test.js'; diff --git a/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.symbols b/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.symbols new file mode 100644 index 0000000000000..1fd52084b4bb5 --- /dev/null +++ b/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.symbols @@ -0,0 +1,59 @@ +//// [tests/cases/compiler/jsDeclarationEmitDoesNotRenameImport.ts] //// + +=== test/Test.js === +/** @module test/Test */ +class Test {} +>Test : Symbol(Test, Decl(Test.js, 0, 0)) + +export default Test; +>Test : Symbol(Test, Decl(Test.js, 0, 0)) + +=== Test.js === +/** @module Test */ +class Test {} +>Test : Symbol(Test, Decl(Test.js, 0, 0)) + +export default Test; +>Test : Symbol(Test, Decl(Test.js, 0, 0)) + +=== index.js === +import Test from './test/Test.js' +>Test : Symbol(Test, Decl(index.js, 0, 6)) + +/** + * @typedef {Object} Options + * @property {typeof import("./Test.js").default} [test] + */ + +class X extends Test { +>X : Symbol(X, Decl(index.js, 0, 33)) +>Test : Symbol(Test, Decl(index.js, 0, 6)) + + /** + * @param {Options} options + */ + constructor(options) { +>options : Symbol(options, Decl(index.js, 11, 16)) + + super(); +>super : Symbol(Test, Decl(Test.js, 0, 0)) + + if (options.test) { +>options.test : Symbol(test, Decl(index.js, 4, 3)) +>options : Symbol(options, Decl(index.js, 11, 16)) +>test : Symbol(test, Decl(index.js, 4, 3)) + + this.test = new options.test(); +>this.test : Symbol(X.test, Decl(index.js, 13, 27)) +>this : Symbol(X, Decl(index.js, 0, 33)) +>test : Symbol(X.test, Decl(index.js, 13, 27)) +>options.test : Symbol(test, Decl(index.js, 4, 3)) +>options : Symbol(options, Decl(index.js, 11, 16)) +>test : Symbol(test, Decl(index.js, 4, 3)) + } + } +} + +export default X; +>X : Symbol(X, Decl(index.js, 0, 33)) + diff --git a/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.types b/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.types new file mode 100644 index 0000000000000..5ba95ac54198d --- /dev/null +++ b/tests/baselines/reference/jsDeclarationEmitDoesNotRenameImport.types @@ -0,0 +1,62 @@ +//// [tests/cases/compiler/jsDeclarationEmitDoesNotRenameImport.ts] //// + +=== test/Test.js === +/** @module test/Test */ +class Test {} +>Test : Test + +export default Test; +>Test : Test + +=== Test.js === +/** @module Test */ +class Test {} +>Test : Test + +export default Test; +>Test : Test + +=== index.js === +import Test from './test/Test.js' +>Test : typeof Test + +/** + * @typedef {Object} Options + * @property {typeof import("./Test.js").default} [test] + */ + +class X extends Test { +>X : X +>Test : Test + + /** + * @param {Options} options + */ + constructor(options) { +>options : Options + + super(); +>super() : void +>super : typeof Test + + if (options.test) { +>options.test : typeof import("Test").default | undefined +>options : Options +>test : typeof import("Test").default | undefined + + this.test = new options.test(); +>this.test = new options.test() : import("Test").default +>this.test : any +>this : this +>test : any +>new options.test() : import("Test").default +>options.test : typeof import("Test").default +>options : Options +>test : typeof import("Test").default + } + } +} + +export default X; +>X : X + diff --git a/tests/cases/compiler/jsDeclarationEmitDoesNotRenameImport.ts b/tests/cases/compiler/jsDeclarationEmitDoesNotRenameImport.ts new file mode 100644 index 0000000000000..85efc76026ee3 --- /dev/null +++ b/tests/cases/compiler/jsDeclarationEmitDoesNotRenameImport.ts @@ -0,0 +1,34 @@ +// @allowJs: true +// @declaration: true +// @emitDeclarationOnly: true +// @strict: false +// @strictNullChecks: true +// @filename: test/Test.js +/** @module test/Test */ +class Test {} +export default Test; +// @filename: Test.js +/** @module Test */ +class Test {} +export default Test; +// @filename: index.js +import Test from './test/Test.js' + +/** + * @typedef {Object} Options + * @property {typeof import("./Test.js").default} [test] + */ + +class X extends Test { + /** + * @param {Options} options + */ + constructor(options) { + super(); + if (options.test) { + this.test = new options.test(); + } + } +} + +export default X; From 5e8c261b6ab746213f19ee3501eb8c48a6215dd7 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Wed, 16 Aug 2023 14:26:38 -0700 Subject: [PATCH 26/81] dprint the codebase (#54820) --- .dprint.jsonc | 55 + .eslintplugin.js | 6 +- .eslintrc.json | 28 +- .github/ISSUE_TEMPLATE/bug_report.yml | 14 +- .github/ISSUE_TEMPLATE/config.yml | 26 +- .github/ISSUE_TEMPLATE/feature_request.yml | 46 +- .github/ISSUE_TEMPLATE/lib_change.yml | 26 +- .github/ISSUE_TEMPLATE/module_resolution.yml | 12 +- .github/ISSUE_TEMPLATE/other.yml | 8 +- .github/codeql/codeql-configuration.yml | 2 +- .../workflows/accept-baselines-fix-lints.yaml | 30 +- .github/workflows/ci.yml | 344 +- .github/workflows/codeql.yml | 2 +- .../ensure-related-repos-run-crons.yml | 64 +- .github/workflows/error-deltas-watchdog.yaml | 40 +- .github/workflows/new-release-branch.yaml | 58 +- .github/workflows/nightly.yaml | 44 +- .../workflows/release-branch-artifact.yaml | 52 +- .github/workflows/rich-navigation.yml | 4 +- .github/workflows/scorecard.yml | 10 +- .github/workflows/set-version.yaml | 70 +- .github/workflows/sync-branch.yaml | 32 +- .github/workflows/sync-wiki.yml | 26 +- .github/workflows/twoslash-repros.yaml | 26 +- .github/workflows/update-lkg.yml | 26 +- .github/workflows/update-package-lock.yaml | 66 +- .vscode/extensions.json | 3 +- .vscode/settings.template.json | 5 + Herebyfile.mjs | 110 +- package-lock.json | 153 + package.json | 2 + scripts/browserIntegrationTest.mjs | 8 +- scripts/build/findUpDir.mjs | 10 +- scripts/build/options.mjs | 22 +- scripts/build/projects.mjs | 29 +- scripts/build/tests.mjs | 21 +- scripts/build/utils.mjs | 35 +- scripts/checkModuleFormat.mjs | 19 +- scripts/checkPackageSize.mjs | 3 +- scripts/configurePrerelease.mjs | 14 +- scripts/dtsBundler.mjs | 36 +- scripts/eslint/rules/argument-trivia.cjs | 20 +- scripts/eslint/rules/debug-assert.cjs | 14 +- scripts/eslint/rules/jsdoc-format.cjs | 65 +- scripts/eslint/rules/no-double-space.cjs | 72 - scripts/eslint/rules/no-in-operator.cjs | 2 +- scripts/eslint/rules/no-keywords.cjs | 10 +- .../rules/no-type-assertion-whitespace.cjs | 42 - .../object-literal-surrounding-space.cjs | 71 - scripts/eslint/rules/only-arrow-functions.cjs | 7 +- scripts/eslint/rules/simple-indent.cjs | 68 - .../eslint/rules/type-operator-spacing.cjs | 43 - scripts/eslint/tests/argument-trivia.test.cjs | 4 +- scripts/eslint/tests/debug-assert.test.cjs | 2 +- scripts/eslint/tests/no-double-space.test.cjs | 154 - scripts/eslint/tests/no-keywords.test.cjs | 6 +- .../no-type-assertion-whitespace.test.cjs | 39 - .../object-literal-surrounding-space.test.cjs | 49 - scripts/eslint/tests/simple-indent.test.cjs | 333 -- .../tests/type-operator-spacing.test.cjs | 45 - scripts/failed-tests.cjs | 4 +- scripts/find-unused-diganostic-messages.mjs | 12 +- .../generateLocalizedDiagnosticMessages.mjs | 11 +- scripts/link-hooks.mjs | 8 +- scripts/open-cherry-pick-pr.mjs | 39 +- scripts/open-user-pr.mjs | 17 +- scripts/perf-result-post.mjs | 13 +- scripts/post-vsts-artifact-comment.mjs | 12 +- scripts/processDiagnosticMessages.mjs | 5 +- scripts/produceLKG.mjs | 4 +- .../regenerate-unicode-identifier-parts.mjs | 1 - scripts/request-pr-review.mjs | 10 +- scripts/update-experimental-branches.mjs | 15 +- src/cancellationToken/cancellationToken.ts | 6 +- src/compiler/binder.ts | 140 +- src/compiler/builder.ts | 194 +- src/compiler/builderState.ts | 46 +- src/compiler/checker.ts | 4465 ++++++++++------- src/compiler/commandLineParser.ts | 280 +- src/compiler/core.ts | 50 +- src/compiler/corePublic.ts | 6 +- src/compiler/debug.ts | 229 +- src/compiler/emitter.ts | 248 +- src/compiler/factory/baseNodeFactory.ts | 2 +- src/compiler/factory/emitHelpers.ts | 199 +- src/compiler/factory/nodeConverters.ts | 16 +- src/compiler/factory/nodeFactory.ts | 1381 ++--- src/compiler/factory/parenthesizerRules.ts | 27 +- src/compiler/factory/utilities.ts | 147 +- src/compiler/factory/utilitiesPublic.ts | 2 +- src/compiler/moduleNameResolver.ts | 133 +- src/compiler/moduleSpecifiers.ts | 158 +- src/compiler/parser.ts | 508 +- src/compiler/path.ts | 10 +- src/compiler/perfLogger.ts | 1 - src/compiler/performance.ts | 2 +- src/compiler/performanceCore.ts | 15 +- src/compiler/program.ts | 291 +- src/compiler/resolutionCache.ts | 120 +- src/compiler/scanner.ts | 63 +- src/compiler/semver.ts | 74 +- src/compiler/sourcemap.ts | 71 +- src/compiler/symbolWalker.ts | 5 +- src/compiler/sys.ts | 169 +- src/compiler/tracing.ts | 19 +- src/compiler/transformer.ts | 30 +- src/compiler/transformers/classFields.ts | 375 +- src/compiler/transformers/classThis.ts | 33 +- src/compiler/transformers/declarations.ts | 305 +- .../transformers/declarations/diagnostics.ts | 30 +- src/compiler/transformers/destructuring.ts | 53 +- src/compiler/transformers/es2015.ts | 676 +-- src/compiler/transformers/es2016.ts | 22 +- src/compiler/transformers/es2017.ts | 119 +- src/compiler/transformers/es2018.ts | 241 +- src/compiler/transformers/es2019.ts | 2 +- src/compiler/transformers/es2020.ts | 39 +- src/compiler/transformers/es2021.ts | 20 +- src/compiler/transformers/esDecorators.ts | 193 +- src/compiler/transformers/esnext.ts | 79 +- src/compiler/transformers/generators.ts | 300 +- src/compiler/transformers/jsx.ts | 57 +- src/compiler/transformers/legacyDecorators.ts | 132 +- .../transformers/module/esnextAnd2015.ts | 61 +- src/compiler/transformers/module/module.ts | 509 +- src/compiler/transformers/module/node.ts | 2 +- src/compiler/transformers/module/system.ts | 219 +- src/compiler/transformers/namedEvaluation.ts | 59 +- src/compiler/transformers/taggedTemplate.ts | 15 +- src/compiler/transformers/ts.ts | 252 +- src/compiler/transformers/typeSerializer.ts | 101 +- src/compiler/transformers/utilities.ts | 62 +- src/compiler/tsbuild.ts | 2 +- src/compiler/tsbuildPublic.ts | 375 +- src/compiler/types.ts | 755 ++- src/compiler/utilities.ts | 767 +-- src/compiler/utilitiesPublic.ts | 18 +- src/compiler/visitorPublic.ts | 881 ++-- src/compiler/watch.ts | 154 +- src/compiler/watchPublic.ts | 238 +- src/compiler/watchUtilities.ts | 120 +- .../5.0/identifierProperties.ts | 12 +- src/deprecatedCompat/deprecate.ts | 2 +- src/deprecatedCompat/deprecations.ts | 13 +- src/executeCommandLine/executeCommandLine.ts | 127 +- src/harness/client.ts | 92 +- src/harness/collectionsImpl.ts | 12 +- src/harness/compilerImpl.ts | 17 +- src/harness/documentsUtil.ts | 5 +- src/harness/evaluatorImpl.ts | 29 +- src/harness/fakesHosts.ts | 27 +- src/harness/findUpDir.ts | 7 +- src/harness/fourslashImpl.ts | 665 +-- src/harness/fourslashInterfaceImpl.ts | 126 +- src/harness/harnessGlobals.ts | 2 +- src/harness/harnessIO.ts | 76 +- src/harness/harnessLanguageService.ts | 233 +- src/harness/harnessUtils.ts | 71 +- src/harness/incrementalUtils.ts | 50 +- src/harness/runnerbase.ts | 2 +- src/harness/sourceMapRecorder.ts | 5 +- src/harness/typeWriter.ts | 12 +- src/harness/util.ts | 3 +- src/harness/vfsUtil.ts | 87 +- src/jsTyping/jsTyping.ts | 16 +- src/lib/decorators.d.ts | 9 +- src/lib/dom.iterable.d.ts | 2 - src/lib/es2015.collection.d.ts | 3 +- src/lib/es2015.core.d.ts | 2 +- src/lib/es2015.iterable.d.ts | 9 +- src/lib/es2015.promise.d.ts | 2 +- src/lib/es2015.symbol.d.ts | 2 +- src/lib/es2016.array.include.d.ts | 2 +- src/lib/es2016.d.ts | 2 +- src/lib/es2016.full.d.ts | 2 +- src/lib/es2017.full.d.ts | 2 +- src/lib/es2017.intl.d.ts | 23 +- src/lib/es2017.object.d.ts | 6 +- src/lib/es2018.asynciterable.d.ts | 2 +- src/lib/es2018.full.d.ts | 2 +- src/lib/es2018.intl.d.ts | 3 +- src/lib/es2018.promise.d.ts | 2 +- src/lib/es2018.regexp.d.ts | 10 +- src/lib/es2019.array.d.ts | 32 +- src/lib/es2019.intl.d.ts | 2 +- src/lib/es2019.object.d.ts | 2 +- src/lib/es2020.bigint.d.ts | 14 +- src/lib/es2020.date.d.ts | 2 +- src/lib/es2020.intl.d.ts | 24 +- src/lib/es2020.promise.d.ts | 2 +- src/lib/es2021.intl.d.ts | 11 +- src/lib/es2021.promise.d.ts | 6 +- src/lib/es2021.weakref.d.ts | 4 +- src/lib/es2022.error.d.ts | 4 +- src/lib/es2022.intl.d.ts | 3 +- src/lib/es2022.sharedmemory.d.ts | 4 +- src/lib/es2023.array.d.ts | 122 +- src/lib/es5.d.ts | 162 +- src/lib/esnext.disposable.d.ts | 20 +- src/lib/esnext.full.d.ts | 2 +- src/lib/esnext.intl.d.ts | 14 +- src/lib/scripthost.d.ts | 5 +- src/lib/webworker.importscripts.d.ts | 1 - src/server/editorServices.ts | 479 +- src/server/moduleSpecifierCache.ts | 2 +- src/server/packageJsonCache.ts | 4 +- src/server/project.ts | 317 +- src/server/protocol.ts | 30 +- src/server/scriptInfo.ts | 62 +- src/server/scriptVersionCache.ts | 35 +- src/server/session.ts | 384 +- src/server/types.ts | 2 +- src/server/typingsCache.ts | 12 +- src/server/utilitiesPublic.ts | 8 +- src/services/breakpoints.ts | 51 +- src/services/callHierarchy.ts | 33 +- src/services/classifier.ts | 157 +- src/services/classifier2020.ts | 35 +- src/services/codeFixProvider.ts | 2 +- ...dConvertToUnknownForNonOverlappingTypes.ts | 13 +- .../codefixes/addEmptyExportDeclaration.ts | 4 +- src/services/codefixes/addMissingAsync.ts | 8 +- src/services/codefixes/addMissingAwait.ts | 28 +- src/services/codefixes/addMissingConst.ts | 11 +- .../codefixes/addMissingDeclareProperty.ts | 6 +- .../codefixes/addNameToNamelessParameter.ts | 3 +- .../codefixes/addOptionalPropertyUndefined.ts | 12 +- .../codefixes/annotateWithTypeFromJSDoc.ts | 15 +- src/services/codefixes/convertConstToLet.ts | 2 +- .../codefixes/convertFunctionToEs6Class.ts | 42 +- .../convertLiteralTypeToMappedType.ts | 34 +- .../codefixes/convertToAsyncFunction.ts | 54 +- src/services/codefixes/convertToEsModule.ts | 44 +- .../codefixes/convertToMappedObjectType.ts | 17 +- .../codefixes/convertToTypeOnlyExport.ts | 11 +- .../codefixes/convertToTypeOnlyImport.ts | 17 +- .../codefixes/convertTypedefToType.ts | 48 +- ...correctQualifiedNameToIndexedAccessType.ts | 20 +- .../codefixes/disableJsDiagnostics.ts | 12 +- .../codefixes/fixAddMissingConstraint.ts | 2 +- src/services/codefixes/fixAddMissingMember.ts | 50 +- .../codefixes/fixAddMissingNewOperator.ts | 3 +- .../fixAddModuleReferTypeMissingTypeof.ts | 3 +- src/services/codefixes/fixAddVoidToPromise.ts | 4 +- .../codefixes/fixAwaitInSyncFunction.ts | 16 +- ...sDoesntImplementInheritedAbstractMember.ts | 3 +- .../fixClassIncorrectlyImplementsInterface.ts | 2 +- .../fixClassSuperMustPrecedeThisAccess.ts | 10 +- .../fixConstructorForDerivedNeedSuperCall.ts | 3 +- src/services/codefixes/fixEnableJsxFlag.ts | 8 +- src/services/codefixes/fixExpectedComma.ts | 17 +- .../fixExtendsInterfaceBecomesImplements.ts | 16 +- .../fixForgottenThisPropertyAccess.ts | 9 +- src/services/codefixes/fixImplicitThis.ts | 7 +- .../codefixes/fixImportNonExportedMember.ts | 25 +- .../codefixes/fixIncorrectNamedTupleSyntax.ts | 6 +- .../codefixes/fixInvalidImportSyntax.ts | 21 +- .../codefixes/fixInvalidJsxCharacters.ts | 6 +- src/services/codefixes/fixJSDocTypes.ts | 13 +- .../codefixes/fixMissingCallParentheses.ts | 11 +- .../codefixes/fixModuleAndTargetOptions.ts | 2 +- src/services/codefixes/fixNaNEquality.ts | 16 +- .../fixNoPropertyAccessFromIndexSignature.ts | 7 +- src/services/codefixes/fixOverrideModifier.ts | 14 +- .../codefixes/fixPropertyAssignment.ts | 5 +- .../codefixes/fixPropertyOverrideAccessor.ts | 15 +- .../codefixes/fixReturnTypeInAsyncFunction.ts | 23 +- src/services/codefixes/fixSpelling.ts | 24 +- .../codefixes/fixStrictClassInitialization.ts | 4 +- .../codefixes/fixUnmatchedParameter.ts | 15 +- src/services/codefixes/fixUnreachableCode.ts | 2 +- src/services/codefixes/fixUnusedIdentifier.ts | 28 +- src/services/codefixes/generateAccessors.ts | 35 +- src/services/codefixes/helpers.ts | 85 +- src/services/codefixes/importFixes.ts | 236 +- src/services/codefixes/inferFromUsage.ts | 39 +- src/services/codefixes/requireInTs.ts | 25 +- src/services/codefixes/returnValueCorrect.ts | 72 +- src/services/codefixes/splitTypeOnlyImport.ts | 37 +- src/services/codefixes/useDefaultImport.ts | 9 +- src/services/codefixes/wrapJsxInFragment.ts | 11 +- src/services/completions.ts | 599 ++- src/services/documentHighlights.ts | 12 +- src/services/documentRegistry.ts | 15 +- src/services/exportInfoMap.ts | 36 +- src/services/findAllReferences.ts | 271 +- src/services/formatting/formatting.ts | 194 +- src/services/formatting/formattingContext.ts | 8 +- src/services/formatting/formattingScanner.ts | 2 +- src/services/formatting/rule.ts | 5 +- src/services/formatting/rules.ts | 63 +- src/services/formatting/rulesMap.ts | 6 +- src/services/formatting/smartIndenter.ts | 25 +- src/services/getEditsForFileRename.ts | 51 +- src/services/goToDefinition.ts | 34 +- src/services/importTracker.ts | 34 +- src/services/inlayHints.ts | 2 +- src/services/jsDoc.ts | 41 +- src/services/navigationBar.ts | 86 +- src/services/organizeImports.ts | 69 +- src/services/patternMatcher.ts | 28 +- src/services/preProcess.ts | 20 +- src/services/refactorProvider.ts | 8 +- .../addOrRemoveBracesToArrowFunction.ts | 14 +- ...onvertArrowFunctionOrFunctionExpression.ts | 11 +- src/services/refactors/convertExport.ts | 21 +- src/services/refactors/convertImport.ts | 26 +- .../convertOverloadListToSingleSignature.ts | 37 +- .../convertParamsToDestructuredObject.ts | 65 +- .../convertStringOrTemplateLiteral.ts | 33 +- .../convertToOptionalChainExpression.ts | 28 +- src/services/refactors/extractSymbol.ts | 179 +- src/services/refactors/extractType.ts | 38 +- .../generateGetAccessorAndSetAccessor.ts | 2 +- src/services/refactors/helpers.ts | 3 +- .../refactors/inferFunctionReturnType.ts | 8 +- src/services/refactors/inlineVariable.ts | 17 +- src/services/refactors/moveToFile.ts | 127 +- src/services/refactors/moveToNewFile.ts | 19 +- src/services/rename.ts | 17 +- src/services/services.ts | 111 +- src/services/shims.ts | 179 +- src/services/signatureHelp.ts | 72 +- src/services/smartSelection.ts | 47 +- src/services/sourcemaps.ts | 7 +- src/services/stringCompletions.ts | 120 +- src/services/suggestionDiagnostics.ts | 29 +- src/services/symbolDisplay.ts | 60 +- src/services/textChanges.ts | 65 +- src/services/transpile.ts | 10 +- src/services/types.ts | 28 +- src/services/utilities.ts | 238 +- src/testRunner/compilerRunner.ts | 21 +- src/testRunner/parallel/host.ts | 56 +- src/testRunner/parallel/shared.ts | 10 +- src/testRunner/parallel/worker.ts | 21 +- src/testRunner/projectsRunner.ts | 35 +- src/testRunner/runner.ts | 13 +- src/testRunner/unittests/asserts.ts | 2 +- src/testRunner/unittests/builder.ts | 7 +- src/testRunner/unittests/canWatch.ts | 7 +- .../unittests/config/commandLineParsing.ts | 33 +- .../config/configurationExtension.ts | 152 +- .../config/convertCompilerOptionsFromJson.ts | 143 +- .../config/convertTypeAcquisitionFromJson.ts | 114 +- src/testRunner/unittests/config/helpers.ts | 4 +- src/testRunner/unittests/config/matchFiles.ts | 1363 +++-- src/testRunner/unittests/config/showConfig.ts | 36 +- .../unittests/config/tsconfigParsing.ts | 110 +- .../config/tsconfigParsingWatchOptions.ts | 86 +- src/testRunner/unittests/customTransforms.ts | 110 +- src/testRunner/unittests/debugDeprecation.ts | 26 +- .../unittests/evaluation/arraySpread.ts | 2 +- .../unittests/evaluation/asyncGenerator.ts | 20 +- .../unittests/evaluation/autoAccessors.ts | 46 +- .../evaluation/awaitUsingDeclarations.ts | 346 +- .../unittests/evaluation/destructuring.ts | 49 +- .../unittests/evaluation/esDecorators.ts | 36 +- .../evaluation/esDecoratorsMetadata.ts | 4 +- .../unittests/evaluation/externalModules.ts | 10 +- .../unittests/evaluation/forAwaitOf.ts | 77 +- src/testRunner/unittests/evaluation/forOf.ts | 53 +- .../unittests/evaluation/generator.ts | 14 +- .../evaluation/superInStaticInitializer.ts | 58 +- .../evaluation/updateExpressionInModule.ts | 90 +- .../unittests/evaluation/usingDeclarations.ts | 363 +- src/testRunner/unittests/factory.ts | 1 - src/testRunner/unittests/helpers.ts | 8 +- src/testRunner/unittests/helpers/baseline.ts | 31 +- src/testRunner/unittests/helpers/contents.ts | 6 +- src/testRunner/unittests/helpers/extends.ts | 8 +- .../unittests/helpers/libraryResolution.ts | 26 +- .../unittests/helpers/node10Result.ts | 72 +- .../unittests/helpers/solutionBuilder.ts | 24 +- src/testRunner/unittests/helpers/tsc.ts | 112 +- src/testRunner/unittests/helpers/tscWatch.ts | 55 +- src/testRunner/unittests/helpers/tsserver.ts | 103 +- src/testRunner/unittests/helpers/vfs.ts | 52 +- .../helpers/virtualFileSystemWithWatch.ts | 53 +- src/testRunner/unittests/incrementalParser.ts | 36 +- src/testRunner/unittests/jsDocParsing.ts | 307 +- .../unittests/jsonParserRecovery.ts | 12 +- src/testRunner/unittests/moduleResolution.ts | 151 +- src/testRunner/unittests/parsePseudoBigInt.ts | 10 +- src/testRunner/unittests/paths.ts | 8 +- src/testRunner/unittests/printer.ts | 404 +- src/testRunner/unittests/programApi.ts | 38 +- src/testRunner/unittests/publicApi.ts | 22 +- .../unittests/reuseProgramStructure.ts | 101 +- .../cancellableLanguageServiceOperations.ts | 38 +- .../unittests/services/colorization.ts | 283 +- .../services/convertToAsyncFunction.ts | 1013 ++-- .../unittests/services/documentRegistry.ts | 1 - .../unittests/services/extract/constants.ts | 280 +- .../unittests/services/extract/functions.ts | 400 +- .../unittests/services/extract/helpers.ts | 19 +- .../unittests/services/extract/ranges.ts | 255 +- .../services/extract/symbolWalker.ts | 62 +- .../unittests/services/hostNewLineSupport.ts | 10 +- .../unittests/services/languageService.ts | 60 +- .../unittests/services/organizeImports.ts | 627 ++- .../unittests/services/preProcessFile.ts | 1133 +++-- .../unittests/services/textChanges.ts | 68 +- .../unittests/services/transpile.ts | 506 +- .../unittests/services/utilities.ts | 9 +- src/testRunner/unittests/transform.ts | 408 +- .../unittests/tsbuild/amdModulesWithOut.ts | 33 +- src/testRunner/unittests/tsbuild/clean.ts | 19 +- .../unittests/tsbuild/commandLine.ts | 17 +- .../unittests/tsbuild/configFileErrors.ts | 49 +- .../unittests/tsbuild/configFileExtends.ts | 20 +- .../tsbuild/containerOnlyReferenced.ts | 46 +- .../unittests/tsbuild/declarationEmit.ts | 82 +- src/testRunner/unittests/tsbuild/demo.ts | 32 +- .../unittests/tsbuild/emitDeclarationOnly.ts | 13 +- .../unittests/tsbuild/emptyFiles.ts | 4 +- .../unittests/tsbuild/exitCodeOnBogusFile.ts | 6 +- src/testRunner/unittests/tsbuild/extends.ts | 10 +- .../unittests/tsbuild/fileDelete.ts | 18 +- .../unittests/tsbuild/graphOrdering.ts | 16 +- .../inferredTypeFromTransitiveModule.ts | 22 +- .../tsbuild/javascriptProjectEmit.ts | 79 +- .../unittests/tsbuild/lateBoundSymbol.ts | 4 +- .../unittests/tsbuild/libraryResolution.ts | 8 +- .../unittests/tsbuild/moduleResolution.ts | 96 +- .../unittests/tsbuild/moduleSpecifiers.ts | 70 +- src/testRunner/unittests/tsbuild/noEmit.ts | 19 +- .../unittests/tsbuild/noEmitOnError.ts | 58 +- src/testRunner/unittests/tsbuild/outFile.ts | 186 +- .../unittests/tsbuild/outputPaths.ts | 109 +- src/testRunner/unittests/tsbuild/publicApi.ts | 16 +- .../tsbuild/referencesWithRootDirInParent.ts | 42 +- .../unittests/tsbuild/resolveJsonModule.ts | 18 +- src/testRunner/unittests/tsbuild/roots.ts | 100 +- src/testRunner/unittests/tsbuild/sample.ts | 236 +- .../unittests/tsbuild/transitiveReferences.ts | 30 +- .../tsbuildWatch/configFileErrors.ts | 62 +- src/testRunner/unittests/tsbuildWatch/demo.ts | 46 +- .../tsbuildWatch/libraryResolution.ts | 8 +- .../tsbuildWatch/moduleResolution.ts | 327 +- .../unittests/tsbuildWatch/noEmit.ts | 31 +- .../unittests/tsbuildWatch/noEmitOnError.ts | 46 +- .../unittests/tsbuildWatch/programUpdates.ts | 414 +- .../tsbuildWatch/projectsBuilding.ts | 74 +- .../unittests/tsbuildWatch/publicApi.ts | 26 +- .../unittests/tsbuildWatch/reexport.ts | 42 +- .../tsbuildWatch/watchEnvironment.ts | 31 +- .../unittests/tsc/cancellationToken.ts | 32 +- src/testRunner/unittests/tsc/composite.ts | 59 +- .../unittests/tsc/declarationEmit.ts | 59 +- src/testRunner/unittests/tsc/extends.ts | 10 +- .../tsc/forceConsistentCasingInFileNames.ts | 15 +- src/testRunner/unittests/tsc/incremental.ts | 399 +- .../unittests/tsc/libraryResolution.ts | 11 +- src/testRunner/unittests/tsc/listFilesOnly.ts | 35 +- .../unittests/tsc/moduleResolution.ts | 19 +- .../unittests/tsc/projectReferences.ts | 58 +- .../unittests/tsc/projectReferencesConfig.ts | 295 +- src/testRunner/unittests/tsc/redirect.ts | 53 +- .../unittests/tsc/runWithoutArgs.ts | 9 +- .../unittests/tscWatch/consoleClearing.ts | 8 +- src/testRunner/unittests/tscWatch/emit.ts | 186 +- .../unittests/tscWatch/emitAndErrorUpdates.ts | 158 +- src/testRunner/unittests/tscWatch/extends.ts | 10 +- .../forceConsistentCasingInFileNames.ts | 263 +- .../unittests/tscWatch/incremental.ts | 93 +- .../unittests/tscWatch/libraryResolution.ts | 60 +- .../unittests/tscWatch/moduleResolution.ts | 486 +- .../unittests/tscWatch/nodeNextWatch.ts | 31 +- .../unittests/tscWatch/programUpdates.ts | 795 +-- .../tscWatch/projectsWithReferences.ts | 441 +- .../unittests/tscWatch/resolutionCache.ts | 264 +- .../resolveJsonModuleWithIncremental.ts | 19 +- .../sourceOfProjectReferenceRedirect.ts | 54 +- src/testRunner/unittests/tscWatch/watchApi.ts | 171 +- .../unittests/tscWatch/watchEnvironment.ts | 252 +- .../tsserver/applyChangesToOpenFiles.ts | 64 +- .../unittests/tsserver/autoImportProvider.ts | 59 +- .../unittests/tsserver/auxiliaryProject.ts | 6 +- .../tsserver/cachingFileSystemInformation.ts | 126 +- .../unittests/tsserver/cancellationToken.ts | 52 +- .../unittests/tsserver/compileOnSave.ts | 282 +- .../unittests/tsserver/completions.ts | 42 +- .../tsserver/completionsIncomplete.ts | 27 +- .../unittests/tsserver/configFileSearch.ts | 20 +- .../unittests/tsserver/configuredProjects.ts | 329 +- .../unittests/tsserver/declarationFileMaps.ts | 62 +- .../unittests/tsserver/documentRegistry.ts | 22 +- .../unittests/tsserver/duplicatePackages.ts | 2 +- .../unittests/tsserver/dynamicFiles.ts | 30 +- .../tsserver/events/largeFileReferenced.ts | 8 +- .../events/projectLanguageServiceState.ts | 17 +- .../tsserver/events/projectLoading.ts | 49 +- .../events/projectUpdatedInBackground.ts | 86 +- .../unittests/tsserver/exportMapCache.ts | 32 +- src/testRunner/unittests/tsserver/extends.ts | 6 +- .../unittests/tsserver/externalProjects.ts | 190 +- .../unittests/tsserver/findAllReferences.ts | 70 +- .../forceConsistentCasingInFileNames.ts | 40 +- .../unittests/tsserver/formatSettings.ts | 19 +- .../tsserver/getApplicableRefactors.ts | 2 +- .../tsserver/getEditsForFileRename.ts | 4 +- .../unittests/tsserver/getFileReferences.ts | 8 +- .../getMoveToRefactoringFileSuggestions.ts | 28 +- .../unittests/tsserver/goToDefinition.ts | 53 +- .../unittests/tsserver/importHelpers.ts | 8 +- .../tsserver/inconsistentErrorInEditor.ts | 24 +- .../unittests/tsserver/inferredProjects.ts | 66 +- .../unittests/tsserver/inlayHints.ts | 22 +- src/testRunner/unittests/tsserver/jsdocTag.ts | 36 +- .../unittests/tsserver/languageService.ts | 31 +- .../unittests/tsserver/libraryResolution.ts | 88 +- .../tsserver/maxNodeModuleJsDepth.ts | 8 +- .../unittests/tsserver/metadataInResponse.ts | 16 +- .../unittests/tsserver/moduleResolution.ts | 49 +- .../tsserver/moduleSpecifierCache.ts | 14 +- src/testRunner/unittests/tsserver/navTo.ts | 36 +- .../unittests/tsserver/occurences.ts | 8 +- src/testRunner/unittests/tsserver/openFile.ts | 48 +- .../unittests/tsserver/packageJsonInfo.ts | 27 +- .../tsserver/partialSemanticServer.ts | 40 +- src/testRunner/unittests/tsserver/plugins.ts | 75 +- .../unittests/tsserver/pluginsAsync.ts | 23 +- .../unittests/tsserver/projectErrors.ts | 186 +- .../tsserver/projectReferenceCompileOnSave.ts | 500 +- .../tsserver/projectReferenceErrors.ts | 30 +- .../unittests/tsserver/projectReferences.ts | 523 +- .../tsserver/projectReferencesSourcemap.ts | 515 +- src/testRunner/unittests/tsserver/projects.ts | 396 +- .../tsserver/projectsWithReferences.ts | 35 +- .../unittests/tsserver/refactors.ts | 28 +- src/testRunner/unittests/tsserver/reload.ts | 20 +- .../unittests/tsserver/reloadProjects.ts | 34 +- src/testRunner/unittests/tsserver/rename.ts | 34 +- .../unittests/tsserver/resolutionCache.ts | 125 +- src/testRunner/unittests/tsserver/session.ts | 129 +- .../unittests/tsserver/skipLibCheck.ts | 62 +- .../unittests/tsserver/smartSelection.ts | 14 +- src/testRunner/unittests/tsserver/symLinks.ts | 58 +- .../unittests/tsserver/symlinkCache.ts | 16 +- .../unittests/tsserver/syntacticServer.ts | 30 +- .../unittests/tsserver/syntaxOperations.ts | 14 +- .../unittests/tsserver/telemetry.ts | 35 +- .../unittests/tsserver/textStorage.ts | 21 +- .../unittests/tsserver/typeAquisition.ts | 18 +- .../tsserver/typeOnlyImportChains.ts | 56 +- .../tsserver/typeReferenceDirectives.ts | 24 +- .../unittests/tsserver/typingsInstaller.ts | 1018 +++- .../unittests/tsserver/versionCache.ts | 2 +- .../unittests/tsserver/watchEnvironment.ts | 122 +- .../typeParameterIsPossiblyReferenced.ts | 56 +- src/tsc/tsc.ts | 2 +- src/tsserver/common.ts | 4 +- src/tsserver/nodeServer.ts | 36 +- src/tsserver/server.ts | 6 +- src/typescript/typescript.ts | 14 +- src/typingsInstaller/nodeTypingsInstaller.ts | 7 +- src/typingsInstallerCore/typingsInstaller.ts | 17 +- tests/baselines/reference/api/typescript.d.ts | 456 +- ...oToTypeDefinition_arrayType.baseline.jsonc | 4 +- 560 files changed, 28486 insertions(+), 23296 deletions(-) create mode 100644 .dprint.jsonc delete mode 100644 scripts/eslint/rules/no-double-space.cjs delete mode 100644 scripts/eslint/rules/no-type-assertion-whitespace.cjs delete mode 100644 scripts/eslint/rules/object-literal-surrounding-space.cjs delete mode 100644 scripts/eslint/rules/simple-indent.cjs delete mode 100644 scripts/eslint/rules/type-operator-spacing.cjs delete mode 100644 scripts/eslint/tests/no-double-space.test.cjs delete mode 100644 scripts/eslint/tests/no-type-assertion-whitespace.test.cjs delete mode 100644 scripts/eslint/tests/object-literal-surrounding-space.test.cjs delete mode 100644 scripts/eslint/tests/simple-indent.test.cjs delete mode 100644 scripts/eslint/tests/type-operator-spacing.test.cjs diff --git a/.dprint.jsonc b/.dprint.jsonc new file mode 100644 index 0000000000000..612772f8aa96c --- /dev/null +++ b/.dprint.jsonc @@ -0,0 +1,55 @@ +{ + "indentWidth": 4, + "lineWidth": 1000, + "newLineKind": "auto", + "useTabs": false, + "typescript": { + "semiColons": "always", + "quoteStyle": "preferDouble", + "quoteProps": "consistent", + "useBraces": "whenNotSingleLine", + "bracePosition": "sameLineUnlessHanging", + "singleBodyPosition": "sameLine", + "nextControlFlowPosition": "nextLine", // Stroustrup style braces. + "trailingCommas": "onlyMultiLine", + "preferHanging": false, + "operatorPosition": "maintain", + + "arrowFunction.useParentheses": "preferNone", + "conditionalExpression.linePerExpression": false, // Keep our "match/case"-ish conditionals. + "functionExpression.spaceAfterFunctionKeyword": true, + "importDeclaration.forceMultiLine": true, + "constructorType.spaceAfterNewKeyword": true, + "constructSignature.spaceAfterNewKeyword": true, + + // Let eslint-plugin-simple-import-sort handle this. + "module.sortImportDeclarations": "maintain", + "module.sortExportDeclarations": "maintain", + "exportDeclaration.sortNamedExports": "maintain", + "importDeclaration.sortNamedImports": "maintain" + }, + "prettier": { + "associations": [ + "**/*.{yaml,yml}" + ], + "yml.tabWidth": 2, + "yaml.tabWidth": 2, + "yml.singleQuote": true, + "yaml.singleQuote": true + }, + "excludes": [ + "**/node_modules", + "**/*-lock.json", + "coverage/**", + "lib/**", + "built/**", + "tests/**", + "internal/**", + "**/*.generated.*", + "scripts/*.d.*" + ], + "plugins": [ + "https://plugins.dprint.dev/typescript-0.86.1.wasm", + "https://plugins.dprint.dev/prettier-0.27.0.json@3557a62b4507c55a47d8cde0683195b14d13c41dda66d0f0b0e111aed107e2fe" + ] +} diff --git a/.eslintplugin.js b/.eslintplugin.js index 97525acf6ffd3..c950681b24cb4 100644 --- a/.eslintplugin.js +++ b/.eslintplugin.js @@ -3,10 +3,10 @@ const path = require("path"); const rulesDir = path.join(__dirname, "scripts", "eslint", "rules"); const ext = ".cjs"; -const ruleFiles = fs.readdirSync(rulesDir).filter((p) => p.endsWith(ext)); +const ruleFiles = fs.readdirSync(rulesDir).filter(p => p.endsWith(ext)); module.exports = { - rules: Object.fromEntries(ruleFiles.map((p) => { + rules: Object.fromEntries(ruleFiles.map(p => { return [p.slice(0, -ext.length), require(path.join(rulesDir, p))]; })), -} +}; diff --git a/.eslintrc.json b/.eslintrc.json index 0eb936e9be5c8..5f3d49fde9631 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -128,33 +128,7 @@ // eslint-plugin-simple-import-sort "simple-import-sort/imports": "error", - "simple-import-sort/exports": "error", - - // Formatting rules; remove once a formatter enforces these. - "curly": ["error", "multi-line"], - "linebreak-style": ["error", "windows"], - "max-statements-per-line": ["error", { "max": 1 }], - "new-parens": "error", - "no-trailing-spaces": "error", - "quote-props": ["error", "consistent-as-needed"], - "space-in-parens": "error", - "@typescript-eslint/brace-style": ["error", "stroustrup", { "allowSingleLine": true }], - "@typescript-eslint/no-extra-semi": "error", - "@typescript-eslint/quotes": ["error", "double", { "avoidEscape": true, "allowTemplateLiterals": true }], - "@typescript-eslint/semi": "error", - "@typescript-eslint/space-before-function-paren": [ - "error", - { - "asyncArrow": "always", - "anonymous": "always", - "named": "never" - } - ], - "local/object-literal-surrounding-space": "error", - "local/no-type-assertion-whitespace": "error", - "local/type-operator-spacing": "error", - "local/no-double-space": "error", - "local/simple-indent": "error" + "simple-import-sort/exports": "error" }, "overrides": [ // By default, the ESLint CLI only looks at .js files. But, it will also look at diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index ac2e1f6bd02c5..61241ea7bf909 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,5 +1,5 @@ -name: "Bug report" -description: "Create a report to help us improve TypeScript" +name: 'Bug report' +description: 'Create a report to help us improve TypeScript' body: - type: markdown attributes: @@ -7,7 +7,7 @@ body: - type: textarea id: search_terms attributes: - label: "🔎 Search Terms" + label: '🔎 Search Terms' description: | What search terms did you use when trying to find an existing bug report? @@ -22,7 +22,7 @@ body: - type: textarea id: version_info attributes: - label: "🕗 Version & Regression Information" + label: '🕗 Version & Regression Information' description: | When did you start seeing this bug occur? @@ -33,7 +33,7 @@ body: If possible, please try testing the nightly version of TS to see if it's already been fixed. For npm: `typescript@next` This is also the 'Nightly' version in the playground: http://www.typescriptlang.org/play/?ts=Nightly - + Note: The TypeScript Playground can be used to try older versions of TypeScript. @@ -56,7 +56,7 @@ body: As a last resort, you can link to a repo, but these will be slower for us to investigate. - placeholder: "Playground link with relevant code: https://www.typescriptlang.org/play?#code/PTAEFkE9QYwewCYFNQHM5IM6gBZIE5JA" + placeholder: 'Playground link with relevant code: https://www.typescriptlang.org/play?#code/PTAEFkE9QYwewCYFNQHM5IM6gBZIE5JA' validations: required: false - type: textarea @@ -87,7 +87,7 @@ body: id: actual_behavior attributes: label: 🙁 Actual behavior - description: "What happened, and why it was wrong." + description: 'What happened, and why it was wrong.' validations: required: true - type: textarea diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 69db3e0326a02..9526309bdc220 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,19 +1,15 @@ ---- +--- blank_issues_enabled: false -contact_links: - - - about: "Please ask and answer usage questions on Stack Overflow." +contact_links: + - about: 'Please ask and answer usage questions on Stack Overflow.' name: Question - url: "https://stackoverflow.com/questions/tagged/typescript" - - - about: "Alternatively, you can use the TypeScript Community Discord." + url: 'https://stackoverflow.com/questions/tagged/typescript' + - about: 'Alternatively, you can use the TypeScript Community Discord.' name: Chat - url: "https://discord.gg/typescript" - - - about: "Please check the FAQ before filing new issues" - name: "TypeScript FAQ" - url: "https://github.com/microsoft/TypeScript/wiki/FAQ" - - - about: "Please raise issues about the site on its own repo." + url: 'https://discord.gg/typescript' + - about: 'Please check the FAQ before filing new issues' + name: 'TypeScript FAQ' + url: 'https://github.com/microsoft/TypeScript/wiki/FAQ' + - about: 'Please raise issues about the site on its own repo.' name: Website - url: "https://github.com/microsoft/TypeScript-Website/issues/new" + url: 'https://github.com/microsoft/TypeScript-Website/issues/new' diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 07424b99d7ae4..ad96977fafa9f 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,19 +1,19 @@ -name: "Feature request" -description: "Suggest an idea" +name: 'Feature request' +description: 'Suggest an idea' body: - type: markdown attributes: - value: "Please fill in each section completely. Thank you!" + value: 'Please fill in each section completely. Thank you!' - type: textarea id: search_terms attributes: - label: "🔍 Search Terms" + label: '🔍 Search Terms' description: | - 💡 Did you know? TypeScript has over 2,000 open suggestions! + 💡 Did you know? TypeScript has over 2,000 open suggestions! - 🔎 Please search thoroughly before logging new feature requests as most common ideas already have a proposal in progress. + 🔎 Please search thoroughly before logging new feature requests as most common ideas already have a proposal in progress. - The "Common Feature Requests" section of the FAQ lists many popular requests: https://github.com/Microsoft/TypeScript/wiki/FAQ#common-feature-requests + The "Common Feature Requests" section of the FAQ lists many popular requests: https://github.com/Microsoft/TypeScript/wiki/FAQ#common-feature-requests placeholder: | List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback. @@ -24,7 +24,7 @@ body: - type: checkboxes id: viability_checklist attributes: - label: "✅ Viability Checklist" + label: '✅ Viability Checklist' description: | Suggestions that don't meet all these criteria are very, very unlikely to be accepted. We always recommend reviewing the TypeScript design goals before investing time writing @@ -32,36 +32,36 @@ body: My suggestion meets the following guidelines. options: - - label: This wouldn't be a breaking change in existing TypeScript/JavaScript code - required: true - - label: This wouldn't change the runtime behavior of existing JavaScript code - required: true - - label: This could be implemented without emitting different JS based on the types of the expressions - required: true - - label: This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.) - required: true - - label: "This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals" - required: true + - label: This wouldn't be a breaking change in existing TypeScript/JavaScript code + required: true + - label: This wouldn't change the runtime behavior of existing JavaScript code + required: true + - label: This could be implemented without emitting different JS based on the types of the expressions + required: true + - label: This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.) + required: true + - label: 'This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals' + required: true - type: textarea id: suggestion_summary attributes: - label: "⭐ Suggestion" + label: '⭐ Suggestion' description: "A summary of what you'd like to see added or changed" validations: required: true - type: textarea id: motivating_example attributes: - label: "📃 Motivating Example" + label: '📃 Motivating Example' description: | - If you were announcing this feature in a blog post, what's a short - explanation that shows a developer why this feature improves the language? + If you were announcing this feature in a blog post, what's a short + explanation that shows a developer why this feature improves the language? validations: required: true - type: textarea id: use_cases attributes: - label: "💻 Use Cases" + label: '💻 Use Cases' value: | 1. What do you want to use this for? 2. What shortcomings exist with current approaches? diff --git a/.github/ISSUE_TEMPLATE/lib_change.yml b/.github/ISSUE_TEMPLATE/lib_change.yml index 8fc6a3034f36e..f3d5c40b50614 100644 --- a/.github/ISSUE_TEMPLATE/lib_change.yml +++ b/.github/ISSUE_TEMPLATE/lib_change.yml @@ -1,5 +1,5 @@ -name: "Library change" -description: "Fix or improve issues with built-in type definitions like `lib.dom.d.ts`, `lib.es6.d.ts`, etc." +name: 'Library change' +description: 'Fix or improve issues with built-in type definitions like `lib.dom.d.ts`, `lib.es6.d.ts`, etc.' body: - type: markdown attributes: @@ -18,37 +18,37 @@ body: - type: markdown attributes: value: | - If you're missing common new methods like `Array.includes`, you may have a misconfigured project. - Try setting `lib: "es2020"` and checking whether the type you want is present. - You can diagnose further by running `tsc` with `--listFilesOnly` or `--showConfig`. + If you're missing common new methods like `Array.includes`, you may have a misconfigured project. + Try setting `lib: "es2020"` and checking whether the type you want is present. + You can diagnose further by running `tsc` with `--listFilesOnly` or `--showConfig`. - Conversely, if you are seeing built-in methods you expect to *not* see, check your 'lib' setting or review your dependencies for lib/reference directives that might be polluting - your global scope. This is common when using the 'node' type library. See https://github.com/microsoft/TypeScript/issues/40184 + Conversely, if you are seeing built-in methods you expect to *not* see, check your 'lib' setting or review your dependencies for lib/reference directives that might be polluting + your global scope. This is common when using the 'node' type library. See https://github.com/microsoft/TypeScript/issues/40184 - type: input id: compilation_target attributes: - label: "⚙ Compilation target" + label: '⚙ Compilation target' description: "What's your compilation target (e.g.: `ES2015`)?" validations: required: true - type: input id: current_lib attributes: - label: "⚙ Library" + label: '⚙ Library' description: "What's the current library you're using?" validations: required: true - type: textarea id: incorrect_definition attributes: - label: "Missing / Incorrect Definition" - description: "What property, method, function, etc. is missing or incorrect?" + label: 'Missing / Incorrect Definition' + description: 'What property, method, function, etc. is missing or incorrect?' validations: required: true - type: textarea id: sample_code attributes: - label: "Sample Code" + label: 'Sample Code' description: "What's some code using this that should work, but doesn't?" render: TypeScript validations: @@ -56,7 +56,7 @@ body: - type: textarea id: documentation_link attributes: - label: "Documentation Link" + label: 'Documentation Link' description: | Link to relevant documentation (e.g. MDN, W3C, ECMAScript Spec) to consult for this property. Note that lib.dom.d.ts intentionally does not include browser-specific extensions or early experimental features. diff --git a/.github/ISSUE_TEMPLATE/module_resolution.yml b/.github/ISSUE_TEMPLATE/module_resolution.yml index dd3b50a326b6a..9bbfa64fa1789 100644 --- a/.github/ISSUE_TEMPLATE/module_resolution.yml +++ b/.github/ISSUE_TEMPLATE/module_resolution.yml @@ -1,6 +1,6 @@ name: Module resolution description: Report a problem with module resolution -title: "Module resolution:" +title: 'Module resolution:' labels: [] body: - type: markdown @@ -64,7 +64,7 @@ body: attributes: label: Run `tsc --showConfig` and paste its output here description: Repros that depend on running within external tools (yarn, pnpm, esbuild, etc.) are not TypeScript defects and will not be investigated. - placeholder: "> tsc --showConfig" + placeholder: '> tsc --showConfig' validations: required: true @@ -73,7 +73,7 @@ body: attributes: label: Run `tsc --traceResolution` and paste its output here description: Run `tsc --traceResolution` and paste the output here. - placeholder: "> tsc --traceResolution" + placeholder: '> tsc --traceResolution' validations: required: true @@ -81,7 +81,7 @@ body: id: import-package-json attributes: label: Paste the `package.json` of the *importing* module, if it exists - placeholder: "my_project/package.json" + placeholder: 'my_project/package.json' validations: required: true @@ -89,7 +89,7 @@ body: id: export-package-json attributes: label: Paste the `package.json` of the *target* module, if it exists - placeholder: "node_modules/somepkg/package.json" + placeholder: 'node_modules/somepkg/package.json' validations: required: true @@ -97,6 +97,6 @@ body: id: comments attributes: label: Any other comments can go here - placeholder: "Have a nice day!" + placeholder: 'Have a nice day!' validations: required: true diff --git a/.github/ISSUE_TEMPLATE/other.yml b/.github/ISSUE_TEMPLATE/other.yml index e23eee5ccc098..bc9b84fd71b6b 100644 --- a/.github/ISSUE_TEMPLATE/other.yml +++ b/.github/ISSUE_TEMPLATE/other.yml @@ -1,13 +1,13 @@ -name: "Other" -description: "Something not captured by any other template" +name: 'Other' +description: 'Something not captured by any other template' body: - type: checkboxes id: acknowledgement attributes: label: Acknowledgement options: - - label: I acknowledge that issues using this template may be closed without further explanation at the maintainer's discretion. - required: true + - label: I acknowledge that issues using this template may be closed without further explanation at the maintainer's discretion. + required: true - type: textarea id: contents attributes: diff --git a/.github/codeql/codeql-configuration.yml b/.github/codeql/codeql-configuration.yml index f94ac49439139..5012a8c080e48 100644 --- a/.github/codeql/codeql-configuration.yml +++ b/.github/codeql/codeql-configuration.yml @@ -1,4 +1,4 @@ -name : CodeQL Configuration +name: CodeQL Configuration paths: - src diff --git a/.github/workflows/accept-baselines-fix-lints.yaml b/.github/workflows/accept-baselines-fix-lints.yaml index 7462a8ec794c8..cc3f27235f52b 100644 --- a/.github/workflows/accept-baselines-fix-lints.yaml +++ b/.github/workflows/accept-baselines-fix-lints.yaml @@ -20,19 +20,19 @@ jobs: contents: write steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 - - name: Configure Git, Run Tests, Update Baselines, Apply Fixes - run: | - git config user.email "typescriptbot@microsoft.com" - git config user.name "TypeScript Bot" - npm ci - git rm -r --quiet tests/baselines/reference - npx hereby runtests-parallel --ci --fix || true - npx hereby baseline-accept - git add ./src - git add ./tests/baselines/reference - git diff --cached - git commit -m "Update Baselines and/or Applied Lint Fixes" - git push + - name: Configure Git, Run Tests, Update Baselines, Apply Fixes + run: | + git config user.email "typescriptbot@microsoft.com" + git config user.name "TypeScript Bot" + npm ci + git rm -r --quiet tests/baselines/reference + npx hereby runtests-parallel --ci --fix || true + npx hereby baseline-accept + git add ./src + git add ./tests/baselines/reference + git diff --cached + git commit -m "Update Baselines and/or Applied Lint Fixes" + git push diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a551bed2d27e9..e35bd060e6311 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,219 +26,243 @@ jobs: strategy: matrix: node-version: - - "20" - - "18" - - "16" - - "14" + - '20' + - '18' + - '16' + - '14' bundle: - - "true" + - 'true' include: - - node-version: "*" - bundle: "false" + - node-version: '*' + bundle: 'false' name: Test Node ${{ matrix.node-version }} with --bundle=${{ matrix.bundle }} steps: - - uses: actions/checkout@v3 - - name: Use node version ${{ matrix.node-version }} - uses: actions/setup-node@v3 - with: - node-version: ${{ matrix.node-version }} - check-latest: true - - run: npm ci - - - name: Tests - # run tests, but lint separately - run: npm run test -- --no-lint --bundle=${{ matrix.bundle }} + - uses: actions/checkout@v3 + - name: Use node version ${{ matrix.node-version }} + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + check-latest: true + - run: npm ci + + - name: Tests + # run tests, but lint separately + run: npm run test -- --no-lint --bundle=${{ matrix.bundle }} lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - node-version: "*" - check-latest: true - - run: npm ci + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: npm ci - - name: Linter - run: npm run lint + - name: Linter + run: npm run lint + + format: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: npm ci + + # TODO: The cache fails when copied between GHA runners. See: + # https://github.com/dprint/dprint/issues/734 + # https://github.com/dprint/dprint/issues/735 + # - uses: actions/cache@v3 + # with: + # path: ~/.cache/dprint + # key: ${{ runner.os }}-dprint-${{ hashFiles('package-lock.json', '.dprint.jsonc') }} + # restore-keys: | + # ${{ runner.os }}-dprint- + + - name: Check formatting + run: npx dprint check browser-integration: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - node-version: "*" - check-latest: true - - run: npm ci + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: npm ci - - name: Adding playwright - run: npm install --no-save --no-package-lock playwright + - name: Adding playwright + run: npm install --no-save --no-package-lock playwright - - name: Validate the browser can import TypeScript - run: npx hereby test-browser-integration + - name: Validate the browser can import TypeScript + run: npx hereby test-browser-integration typecheck: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - node-version: "*" - check-latest: true - - run: npm ci + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: npm ci - - name: Build src - run: npx hereby build-src + - name: Build src + run: npx hereby build-src smoke: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - - uses: actions/setup-node@v3 - with: - node-version: "*" - check-latest: true - - run: | - npm --version - # corepack enable npm - npm install -g $(jq -r '.packageManager' < package.json) - npm --version - - - run: npm ci - - - run: npx hereby lkg - - run: | - npm pack - mv typescript*.tgz typescript.tgz - echo "package=$PWD/typescript.tgz" >> "$GITHUB_OUTPUT" - id: pack - - - name: Smoke test - run: | - cd "$(mktemp -d)" - npm init --yes - npm install ${{ steps.pack.outputs.package }} - - echo "Testing tsc..." - npx tsc --version - - echo "Testing tsserver..." - echo '{"seq": 1, "command": "status"}' | npx tsserver - - node $GITHUB_WORKSPACE/scripts/checkModuleFormat.mjs typescript - node $GITHUB_WORKSPACE/scripts/checkModuleFormat.mjs typescript/lib/tsserverlibrary + - uses: actions/checkout@v3 + + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: | + npm --version + # corepack enable npm + npm install -g $(jq -r '.packageManager' < package.json) + npm --version + + - run: npm ci + + - run: npx hereby lkg + - run: | + npm pack + mv typescript*.tgz typescript.tgz + echo "package=$PWD/typescript.tgz" >> "$GITHUB_OUTPUT" + id: pack + + - name: Smoke test + run: | + cd "$(mktemp -d)" + npm init --yes + npm install ${{ steps.pack.outputs.package }} + + echo "Testing tsc..." + npx tsc --version + + echo "Testing tsserver..." + echo '{"seq": 1, "command": "status"}' | npx tsserver + + node $GITHUB_WORKSPACE/scripts/checkModuleFormat.mjs typescript + node $GITHUB_WORKSPACE/scripts/checkModuleFormat.mjs typescript/lib/tsserverlibrary package-size: runs-on: ubuntu-latest if: github.event_name == 'pull_request' steps: - - uses: actions/checkout@v3 - with: - path: pr - - - uses: actions/checkout@v3 - with: - path: base - ref: ${{ github.base_ref }} - - - uses: actions/setup-node@v3 - with: - node-version: "*" - check-latest: true - - run: | - npm --version - # corepack enable npm - - - run: | - npm install -g $(jq -r '.packageManager' < package.json) - npm --version - working-directory: ./pr - - - run: npm ci - working-directory: ./pr - - - run: npm ci - working-directory: ./base - - - run: npx hereby lkg - working-directory: ./pr - - - run: npx hereby lkg - working-directory: ./base - - - run: | - echo "See $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID for more info." - node ./pr/scripts/checkPackageSize.mjs ./base ./pr >> $GITHUB_STEP_SUMMARY + - uses: actions/checkout@v3 + with: + path: pr + + - uses: actions/checkout@v3 + with: + path: base + ref: ${{ github.base_ref }} + + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: | + npm --version + # corepack enable npm + + - run: | + npm install -g $(jq -r '.packageManager' < package.json) + npm --version + working-directory: ./pr + + - run: npm ci + working-directory: ./pr + + - run: npm ci + working-directory: ./base + + - run: npx hereby lkg + working-directory: ./pr + + - run: npx hereby lkg + working-directory: ./base + + - run: | + echo "See $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID for more info." + node ./pr/scripts/checkPackageSize.mjs ./base ./pr >> $GITHUB_STEP_SUMMARY misc: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - node-version: "*" - check-latest: true - - run: npm ci + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: npm ci - - name: Build scripts - run: npx hereby scripts + - name: Build scripts + run: npx hereby scripts - - name: ESLint tests - run: npx hereby run-eslint-rules-tests + - name: ESLint tests + run: npx hereby run-eslint-rules-tests self-check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - node-version: "*" - check-latest: true - - run: npm ci + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: npm ci - - name: Build tsc - run: npx hereby tsc + - name: Build tsc + run: npx hereby tsc - - name: Clean - run: npx hereby clean-src + - name: Clean + run: npx hereby clean-src - - name: Self build - run: npx hereby build-src --built + - name: Self build + run: npx hereby build-src --built unused-baselines: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - node-version: "*" - check-latest: true - - run: npm ci - - - name: Remove all baselines - run: rm -rf tests/baselines/reference - - - name: Run tests - run: npm test &> /dev/null || exit 0 - - - name: Accept baselines - run: npx hereby baseline-accept - - - name: Check for unused baselines - run: | - if ! git diff --exit-code --quiet; then - echo "Unused baselines:" - git diff --exit-code --name-only - fi + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '*' + check-latest: true + - run: npm ci + + - name: Remove all baselines + run: rm -rf tests/baselines/reference + + - name: Run tests + run: npm test &> /dev/null || exit 0 + + - name: Accept baselines + run: npx hereby baseline-accept + + - name: Check for unused baselines + run: | + if ! git diff --exit-code --quiet; then + echo "Unused baselines:" + git diff --exit-code --name-only + fi diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index b90bfec110d5d..a54f05f8c3f04 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,4 +1,4 @@ -name: "Code Scanning - Action" +name: 'Code Scanning - Action' on: push: diff --git a/.github/workflows/ensure-related-repos-run-crons.yml b/.github/workflows/ensure-related-repos-run-crons.yml index 2e72bd2c6e6e3..077095ce9a64d 100644 --- a/.github/workflows/ensure-related-repos-run-crons.yml +++ b/.github/workflows/ensure-related-repos-run-crons.yml @@ -6,10 +6,10 @@ name: Related Repo Commit Bumps on: - schedule: - # Monthly, https://crontab.guru/#0_0_*_1-12_* - - cron: '0 0 1 * *' - workflow_dispatch: {} + schedule: + # Monthly, https://crontab.guru/#0_0_*_1-12_* + - cron: '0 0 1 * *' + workflow_dispatch: {} permissions: contents: read @@ -26,31 +26,31 @@ jobs: if: github.repository == 'microsoft/TypeScript' steps: - - name: Configure git - run: | - git config --global user.email "typescriptbot@microsoft.com" - git config --global user.name "TypeScript Bot" - - - uses: actions/checkout@v3 - with: - repository: 'microsoft/TypeScript-Website' - path: 'ts-site' - - - name: Push Commit to TS Website - run: | - cd ts-site - git commit --allow-empty -m "Monthly Bump" - git config --unset-all http.https://github.com/.extraheader - git push https://${{ secrets.TS_BOT_GITHUB_TOKEN }}@github.com/microsoft/TypeScript-Website.git - - - uses: actions/checkout@v3 - with: - repository: 'microsoft/TypeScript-Make-Monaco-Builds' - path: 'monaco-builds' - - - name: Push Commit to TS Make Monaco Builds - run: | - cd monaco-builds - git commit --allow-empty -m "Monthly Bump" - git config --unset-all http.https://github.com/.extraheader - git push https://${{ secrets.TS_BOT_GITHUB_TOKEN }}@github.com/microsoft/TypeScript-Make-Monaco-Builds.git + - name: Configure git + run: | + git config --global user.email "typescriptbot@microsoft.com" + git config --global user.name "TypeScript Bot" + + - uses: actions/checkout@v3 + with: + repository: 'microsoft/TypeScript-Website' + path: 'ts-site' + + - name: Push Commit to TS Website + run: | + cd ts-site + git commit --allow-empty -m "Monthly Bump" + git config --unset-all http.https://github.com/.extraheader + git push https://${{ secrets.TS_BOT_GITHUB_TOKEN }}@github.com/microsoft/TypeScript-Website.git + + - uses: actions/checkout@v3 + with: + repository: 'microsoft/TypeScript-Make-Monaco-Builds' + path: 'monaco-builds' + + - name: Push Commit to TS Make Monaco Builds + run: | + cd monaco-builds + git commit --allow-empty -m "Monthly Bump" + git config --unset-all http.https://github.com/.extraheader + git push https://${{ secrets.TS_BOT_GITHUB_TOKEN }}@github.com/microsoft/TypeScript-Make-Monaco-Builds.git diff --git a/.github/workflows/error-deltas-watchdog.yaml b/.github/workflows/error-deltas-watchdog.yaml index 14b2cff887408..86aee16a71556 100644 --- a/.github/workflows/error-deltas-watchdog.yaml +++ b/.github/workflows/error-deltas-watchdog.yaml @@ -1,4 +1,4 @@ -name: "typescript-error-deltas Watchdog" +name: 'typescript-error-deltas Watchdog' on: workflow_dispatch: @@ -23,23 +23,23 @@ jobs: issues: write env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TAGS: "@navya9singh @RyanCavanaugh @DanielRosenwasser" + TAGS: '@navya9singh @RyanCavanaugh @DanielRosenwasser' steps: - - name: NewErrors - run: | # --json and --jq prints exactly one issue number per line of output - DATE=$(date --date="7 days ago" --iso-8601) - gh issue list --repo microsoft/typescript --search "[NewErrors] created:>=$DATE" --state all --json number --jq ".[].number" \ - | grep -qe "[0-9]" \ - || gh issue create --repo ${{ github.repository }} --title "No NewErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=48)." - - name: ServerErrors TS - run: | - DATE=$(date --date="7 days ago" --iso-8601) - gh issue list --repo microsoft/typescript --search "[ServerErrors][TypeScript] created:>=$DATE" --state all --json number --jq ".[].number" \ - | grep -qe "[0-9]" \ - || gh issue create --repo ${{ github.repository }} --title "No TypeScript ServerErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=59)." - - name: ServerErrors JS - run: | - DATE=$(date --date="7 days ago" --iso-8601) - gh issue list --repo microsoft/typescript --search "[ServerErrors][JavaScript] created:>=$DATE" --state all --json number --jq ".[].number" \ - | grep -qe "[0-9]" \ - || gh issue create --repo ${{ github.repository }} --title "No JavaScript ServerErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=58)." + - name: NewErrors + run: | # --json and --jq prints exactly one issue number per line of output + DATE=$(date --date="7 days ago" --iso-8601) + gh issue list --repo microsoft/typescript --search "[NewErrors] created:>=$DATE" --state all --json number --jq ".[].number" \ + | grep -qe "[0-9]" \ + || gh issue create --repo ${{ github.repository }} --title "No NewErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=48)." + - name: ServerErrors TS + run: | + DATE=$(date --date="7 days ago" --iso-8601) + gh issue list --repo microsoft/typescript --search "[ServerErrors][TypeScript] created:>=$DATE" --state all --json number --jq ".[].number" \ + | grep -qe "[0-9]" \ + || gh issue create --repo ${{ github.repository }} --title "No TypeScript ServerErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=59)." + - name: ServerErrors JS + run: | + DATE=$(date --date="7 days ago" --iso-8601) + gh issue list --repo microsoft/typescript --search "[ServerErrors][JavaScript] created:>=$DATE" --state all --json number --jq ".[].number" \ + | grep -qe "[0-9]" \ + || gh issue create --repo ${{ github.repository }} --title "No JavaScript ServerErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=58)." diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml index 8d5ec9a7010c8..666b322cfcea8 100644 --- a/.github/workflows/new-release-branch.yaml +++ b/.github/workflows/new-release-branch.yaml @@ -21,32 +21,32 @@ jobs: contents: write steps: - - uses: actions/setup-node@v3 - - run: | - npm --version - # corepack enable npm - npm install -g $(jq -r '.packageManager' < package.json) - npm --version - - uses: actions/checkout@v3 - with: - fetch-depth: 5 - - run: | - git checkout -b ${{ github.event.client_payload.branch_name }} - sed -i -e 's/"version": ".*"/"version": "${{ github.event.client_payload.package_version }}"/g' package.json - sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' src/compiler/corePublic.ts - sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/typescript.d.ts - sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/tsserverlibrary.d.ts - sed -i -e 's/const version\(: string\)\{0,1\} = `${versionMajorMinor}.0-.*`/const version = `${versionMajorMinor}.0-${{ github.event.client_payload.core_tag || 'dev' }}`/g' src/compiler/corePublic.ts - npm ci - npx hereby LKG - npm test - git diff - git add package.json - git add src/compiler/corePublic.ts - git add tests/baselines/reference/api/typescript.d.ts - git add tests/baselines/reference/api/tsserverlibrary.d.ts - git add --force ./lib - git config user.email "typescriptbot@microsoft.com" - git config user.name "TypeScript Bot" - git commit -m 'Bump version to ${{ github.event.client_payload.package_version }} and LKG' - git push --set-upstream origin ${{ github.event.client_payload.branch_name }} + - uses: actions/setup-node@v3 + - run: | + npm --version + # corepack enable npm + npm install -g $(jq -r '.packageManager' < package.json) + npm --version + - uses: actions/checkout@v3 + with: + fetch-depth: 5 + - run: | + git checkout -b ${{ github.event.client_payload.branch_name }} + sed -i -e 's/"version": ".*"/"version": "${{ github.event.client_payload.package_version }}"/g' package.json + sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' src/compiler/corePublic.ts + sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/typescript.d.ts + sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/tsserverlibrary.d.ts + sed -i -e 's/const version\(: string\)\{0,1\} = `${versionMajorMinor}.0-.*`/const version = `${versionMajorMinor}.0-${{ github.event.client_payload.core_tag || 'dev' }}`/g' src/compiler/corePublic.ts + npm ci + npx hereby LKG + npm test + git diff + git add package.json + git add src/compiler/corePublic.ts + git add tests/baselines/reference/api/typescript.d.ts + git add tests/baselines/reference/api/tsserverlibrary.d.ts + git add --force ./lib + git config user.email "typescriptbot@microsoft.com" + git config user.name "TypeScript Bot" + git commit -m 'Bump version to ${{ github.event.client_payload.package_version }} and LKG' + git push --set-upstream origin ${{ github.event.client_payload.branch_name }} diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index 8692ed2d75e83..20a5d2c590354 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -2,7 +2,7 @@ name: Publish Nightly on: schedule: - - cron: '0 7 * * *' + - cron: '0 7 * * *' # enable users to manually trigger with workflow_dispatch workflow_dispatch: {} repository_dispatch: @@ -23,24 +23,24 @@ jobs: if: github.repository == 'microsoft/TypeScript' steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - with: - # Use NODE_AUTH_TOKEN environment variable to authenticate to this registry. - registry-url: https://registry.npmjs.org/ - - run: | - npm --version - # corepack enable npm - npm install -g $(jq -r '.packageManager' < package.json) - npm --version - - name: Setup and publish nightly - run: | - npm whoami - npm ci - npx hereby configure-nightly - npx hereby LKG - npx hereby runtests-parallel - npx hereby clean - npm publish --tag next - env: - NODE_AUTH_TOKEN: ${{secrets.npm_token}} + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + # Use NODE_AUTH_TOKEN environment variable to authenticate to this registry. + registry-url: https://registry.npmjs.org/ + - run: | + npm --version + # corepack enable npm + npm install -g $(jq -r '.packageManager' < package.json) + npm --version + - name: Setup and publish nightly + run: | + npm whoami + npm ci + npx hereby configure-nightly + npx hereby LKG + npx hereby runtests-parallel + npx hereby clean + npm publish --tag next + env: + NODE_AUTH_TOKEN: ${{secrets.npm_token}} diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index e0b95bdf00660..7a44017374b7b 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml @@ -19,29 +19,29 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - - run: | - npm --version - # corepack enable npm - npm install -g $(jq -r '.packageManager' < package.json) - npm --version - - name: npm install and test - run: | - npm ci - npm test - - name: Adding playwright - run: npm install --no-save --no-package-lock playwright - - name: Validate the browser can import TypeScript - run: npx hereby test-browser-integration - - name: LKG, clean, and pack - run: | - npx hereby LKG - npx hereby clean - npm pack ./ - mv typescript-*.tgz typescript.tgz - - name: Upload built tarfile - uses: actions/upload-artifact@v3 - with: - name: tgz - path: typescript.tgz + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + - run: | + npm --version + # corepack enable npm + npm install -g $(jq -r '.packageManager' < package.json) + npm --version + - name: npm install and test + run: | + npm ci + npm test + - name: Adding playwright + run: npm install --no-save --no-package-lock playwright + - name: Validate the browser can import TypeScript + run: npx hereby test-browser-integration + - name: LKG, clean, and pack + run: | + npx hereby LKG + npx hereby clean + npm pack ./ + mv typescript-*.tgz typescript.tgz + - name: Upload built tarfile + uses: actions/upload-artifact@v3 + with: + name: tgz + path: typescript.tgz diff --git a/.github/workflows/rich-navigation.yml b/.github/workflows/rich-navigation.yml index c5c59e0cdf9f6..83bf30ec0833f 100644 --- a/.github/workflows/rich-navigation.yml +++ b/.github/workflows/rich-navigation.yml @@ -1,4 +1,4 @@ -name: "Rich Navigation Indexing" +name: 'Rich Navigation Indexing' on: workflow_dispatch: push: @@ -31,7 +31,7 @@ jobs: - uses: actions/setup-node@v3 - name: Install dependencies - run: npm ci + run: npm ci - uses: microsoft/RichCodeNavIndexer@v0.1 with: diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 0e7e361a188d3..dcfc01ed5f719 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -12,7 +12,7 @@ on: schedule: - cron: '19 15 * * 4' push: - branches: [ "main" ] + branches: ['main'] # Declare default permissions as read only. permissions: read-all @@ -28,12 +28,12 @@ jobs: id-token: write steps: - - name: "Checkout code" + - name: 'Checkout code' uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # v3.1.0 with: persist-credentials: false - - name: "Run analysis" + - name: 'Run analysis' uses: ossf/scorecard-action@80e868c13c90f172d68d1f4501dee99e2479f7af # v2.1.3 with: results_file: results.sarif @@ -46,7 +46,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - - name: "Upload artifact" + - name: 'Upload artifact' uses: actions/upload-artifact@3cea5372237819ed00197afe530f5a7ea3e805c8 # v3.1.0 with: name: SARIF file @@ -54,7 +54,7 @@ jobs: retention-days: 5 # Upload the results to GitHub's code scanning dashboard. - - name: "Upload to code-scanning" + - name: 'Upload to code-scanning' uses: github/codeql-action/upload-sarif@807578363a7869ca324a79039e6db9c843e0e100 # v2.1.27 with: sarif_file: results.sarif diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml index ec04aebfefe0b..8e5ce9399d3e0 100644 --- a/.github/workflows/set-version.yaml +++ b/.github/workflows/set-version.yaml @@ -21,38 +21,38 @@ jobs: contents: write steps: - - uses: actions/setup-node@v3 - - uses: actions/checkout@v3 - with: - ref: ${{ github.event.client_payload.branch_name }} - - run: | - npm --version - # corepack enable npm - npm install -g $(jq -r '.packageManager' < package.json) - npm --version - # notably, this is essentially the same script as `new-release-branch.yaml` (with fewer inputs), but it assumes the branch already exists - # do note that executing the transform below will prevent the `configurePrerelease` script from running on the source, as it makes the - # `version` identifier no longer match the regex it uses - # required client_payload members: - # branch_name - the target branch - # package_version - the full version string (eg, `3.9.1-rc` or `3.9.2`) - # core_major_minor - the major.minor pair associated with the desired package_version (eg, `3.9` for `3.9.3`) - - run: | - sed -i -e 's/"version": ".*"/"version": "${{ github.event.client_payload.package_version }}"/g' package.json - sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' src/compiler/corePublic.ts - sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/typescript.d.ts - sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/tsserverlibrary.d.ts - sed -i -e 's/const version\(: string\)\{0,1\} = .*;/const version = "${{ github.event.client_payload.package_version }}" as string;/g' src/compiler/corePublic.ts - npm ci - npx hereby LKG - npm test - git diff - git add package.json - git add src/compiler/corePublic.ts - git add tests/baselines/reference/api/typescript.d.ts - git add tests/baselines/reference/api/tsserverlibrary.d.ts - git add --force ./lib - git config user.email "typescriptbot@microsoft.com" - git config user.name "TypeScript Bot" - git commit -m 'Bump version to ${{ github.event.client_payload.package_version }} and LKG' - git push + - uses: actions/setup-node@v3 + - uses: actions/checkout@v3 + with: + ref: ${{ github.event.client_payload.branch_name }} + - run: | + npm --version + # corepack enable npm + npm install -g $(jq -r '.packageManager' < package.json) + npm --version + # notably, this is essentially the same script as `new-release-branch.yaml` (with fewer inputs), but it assumes the branch already exists + # do note that executing the transform below will prevent the `configurePrerelease` script from running on the source, as it makes the + # `version` identifier no longer match the regex it uses + # required client_payload members: + # branch_name - the target branch + # package_version - the full version string (eg, `3.9.1-rc` or `3.9.2`) + # core_major_minor - the major.minor pair associated with the desired package_version (eg, `3.9` for `3.9.3`) + - run: | + sed -i -e 's/"version": ".*"/"version": "${{ github.event.client_payload.package_version }}"/g' package.json + sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' src/compiler/corePublic.ts + sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/typescript.d.ts + sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/tsserverlibrary.d.ts + sed -i -e 's/const version\(: string\)\{0,1\} = .*;/const version = "${{ github.event.client_payload.package_version }}" as string;/g' src/compiler/corePublic.ts + npm ci + npx hereby LKG + npm test + git diff + git add package.json + git add src/compiler/corePublic.ts + git add tests/baselines/reference/api/typescript.d.ts + git add tests/baselines/reference/api/tsserverlibrary.d.ts + git add --force ./lib + git config user.email "typescriptbot@microsoft.com" + git config user.name "TypeScript Bot" + git commit -m 'Bump version to ${{ github.event.client_payload.package_version }} and LKG' + git push diff --git a/.github/workflows/sync-branch.yaml b/.github/workflows/sync-branch.yaml index cbe0a3ca0834b..68dc6b286c451 100644 --- a/.github/workflows/sync-branch.yaml +++ b/.github/workflows/sync-branch.yaml @@ -26,19 +26,19 @@ jobs: contents: write steps: - - uses: actions/setup-node@v3 - - uses: actions/checkout@v3 - with: - ref: ${{ github.event.inputs.branch_name || github.event.client_payload.branch_name }} - fetch-depth: 0 - # This does a test post-merge and only pushes the result if the test succeeds - # required client_payload members: - # branch_name - the target branch - - run: | - git config user.email "typescriptbot@microsoft.com" - git config user.name "TypeScript Bot" - git fetch origin main - git merge origin/main --no-ff - npm ci - npm test - git push + - uses: actions/setup-node@v3 + - uses: actions/checkout@v3 + with: + ref: ${{ github.event.inputs.branch_name || github.event.client_payload.branch_name }} + fetch-depth: 0 + # This does a test post-merge and only pushes the result if the test succeeds + # required client_payload members: + # branch_name - the target branch + - run: | + git config user.email "typescriptbot@microsoft.com" + git config user.name "TypeScript Bot" + git fetch origin main + git merge origin/main --no-ff + npm ci + npm test + git push diff --git a/.github/workflows/sync-wiki.yml b/.github/workflows/sync-wiki.yml index 38b20f96657b5..ee20ba8d4c780 100644 --- a/.github/workflows/sync-wiki.yml +++ b/.github/workflows/sync-wiki.yml @@ -15,16 +15,16 @@ jobs: sync: runs-on: ubuntu-latest steps: - - name: Get repo name - run: R=${GITHUB_REPOSITORY%?wiki}; echo "BASENAME=${R##*/}" >> $GITHUB_ENV - - name: Checkout ${{ env.BASENAME }}-wiki - uses: actions/checkout@v3 - with: - repository: "${{ GITHUB.repository_owner }}/${{ env.BASENAME }}-wiki" - token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - fetch-depth: 0 - - name: Run sync - run: ./.github/workflows/sync - env: - PUSHER: typescript-bot - AUTH: ${{ secrets.TS_BOT_GITHUB_TOKEN }} + - name: Get repo name + run: R=${GITHUB_REPOSITORY%?wiki}; echo "BASENAME=${R##*/}" >> $GITHUB_ENV + - name: Checkout ${{ env.BASENAME }}-wiki + uses: actions/checkout@v3 + with: + repository: '${{ GITHUB.repository_owner }}/${{ env.BASENAME }}-wiki' + token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} + fetch-depth: 0 + - name: Run sync + run: ./.github/workflows/sync + env: + PUSHER: typescript-bot + AUTH: ${{ secrets.TS_BOT_GITHUB_TOKEN }} diff --git a/.github/workflows/twoslash-repros.yaml b/.github/workflows/twoslash-repros.yaml index c4bdbf38258fe..60aba0dc60b80 100644 --- a/.github/workflows/twoslash-repros.yaml +++ b/.github/workflows/twoslash-repros.yaml @@ -5,7 +5,7 @@ on: branches: - orta-twoslash-repros schedule: - - cron: '0 8 * * *' + - cron: '0 8 * * *' repository_dispatch: types: run-twoslash-repros workflow_dispatch: @@ -33,15 +33,15 @@ jobs: if: ${{ github.repository == 'microsoft/TypeScript' }} runs-on: ubuntu-latest steps: - - if: ${{ github.event.inputs.bisect }} - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - if: ${{ !github.event.inputs.bisect }} - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 - - uses: microsoft/TypeScript-Twoslash-Repro-Action@master - with: - github-token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - issue: ${{ github.event.inputs.issue }} - bisect: ${{ github.event.inputs.bisect }} + - if: ${{ github.event.inputs.bisect }} + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - if: ${{ !github.event.inputs.bisect }} + uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + - uses: microsoft/TypeScript-Twoslash-Repro-Action@master + with: + github-token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} + issue: ${{ github.event.inputs.issue }} + bisect: ${{ github.event.inputs.bisect }} diff --git a/.github/workflows/update-lkg.yml b/.github/workflows/update-lkg.yml index 3caf672ccc9bb..c335f5a8d159f 100644 --- a/.github/workflows/update-lkg.yml +++ b/.github/workflows/update-lkg.yml @@ -20,17 +20,17 @@ jobs: contents: write steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 - - name: Configure Git and Update LKG - run: | - git config user.email "typescriptbot@microsoft.com" - git config user.name "TypeScript Bot" - npm ci - npx hereby LKG - npm test - git diff - git add --force ./lib - git commit -m "Update LKG" - git push + - name: Configure Git and Update LKG + run: | + git config user.email "typescriptbot@microsoft.com" + git config user.name "TypeScript Bot" + npm ci + npx hereby LKG + npm test + git diff + git add --force ./lib + git commit -m "Update LKG" + git push diff --git a/.github/workflows/update-package-lock.yaml b/.github/workflows/update-package-lock.yaml index f3b2c35e4e173..da5796e9b0dd8 100644 --- a/.github/workflows/update-package-lock.yaml +++ b/.github/workflows/update-package-lock.yaml @@ -1,11 +1,11 @@ name: Update package-lock.json on: - schedule: - # This is probably 6am UTC, which is 10pm PST or 11pm PDT - # Alternatively, 6am local is also fine - - cron: '0 6 * * *' - workflow_dispatch: {} + schedule: + # This is probably 6am UTC, which is 10pm PST or 11pm PDT + # Alternatively, 6am local is also fine + - cron: '0 6 * * *' + workflow_dispatch: {} permissions: contents: read @@ -25,31 +25,31 @@ jobs: contents: write steps: - - uses: actions/checkout@v3 - with: - token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@v3 - with: - node-version: 16 - - run: | - npm --version - # corepack enable npm - npm install -g $(jq -r '.packageManager' < package.json) - npm --version - - - name: Update package-lock.json and push - run: | - rm package-lock.json - npm install - - if git diff --exit-code --name-only package-lock.json; then - echo "No change." - else - npm test - npx hereby lkg - git config user.email "typescriptbot@microsoft.com" - git config user.name "TypeScript Bot" - git add -f package-lock.json - git commit -m "Update package-lock.json" - git push - fi + - uses: actions/checkout@v3 + with: + token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} + - uses: actions/setup-node@v3 + with: + node-version: 16 + - run: | + npm --version + # corepack enable npm + npm install -g $(jq -r '.packageManager' < package.json) + npm --version + + - name: Update package-lock.json and push + run: | + rm package-lock.json + npm install + + if git diff --exit-code --name-only package-lock.json; then + echo "No change." + else + npm test + npx hereby lkg + git config user.email "typescriptbot@microsoft.com" + git config user.name "TypeScript Bot" + git add -f package-lock.json + git commit -m "Update package-lock.json" + git push + fi diff --git a/.vscode/extensions.json b/.vscode/extensions.json index c3ea200176d3c..beff1465a0127 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,7 +1,8 @@ { "recommendations": [ "dbaeumer.vscode-eslint", - "rbuckton.tsserver-live-reload" + "rbuckton.tsserver-live-reload", + "dprint.dprint" ], "unwantedRecommendations": [ diff --git a/.vscode/settings.template.json b/.vscode/settings.template.json index 7d6691df5aa8a..71b1986cf1a46 100644 --- a/.vscode/settings.template.json +++ b/.vscode/settings.template.json @@ -4,6 +4,11 @@ // To use the locally built compiler, after 'npm run build': // "typescript.tsdk": "built/local" + "[typescript][javascript][yaml]": { + "editor.formatOnSave": true, + "editor.defaultFormatter": "dprint.dprint" + }, + // To ignore commits listed in .git-blame-ignore-revs in GitLens: "gitlens.advanced.blame.customArguments": [ "--ignore-revs-file", diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 38269cbcc3929..85c248d6dbe70 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -1,21 +1,45 @@ // @ts-check -import { CancelToken } from "@esfx/canceltoken"; +import { + CancelToken, +} from "@esfx/canceltoken"; import chalk from "chalk"; import chokidar from "chokidar"; import del from "del"; import esbuild from "esbuild"; -import { EventEmitter } from "events"; +import { + EventEmitter, +} from "events"; import fs from "fs"; import _glob from "glob"; -import { task } from "hereby"; +import { + task, +} from "hereby"; import path from "path"; import util from "util"; -import { localizationDirectories } from "./scripts/build/localization.mjs"; +import { + localizationDirectories, +} from "./scripts/build/localization.mjs"; import cmdLineOptions from "./scripts/build/options.mjs"; -import { buildProject, cleanProject, watchProject } from "./scripts/build/projects.mjs"; -import { localBaseline, refBaseline, runConsoleTests } from "./scripts/build/tests.mjs"; -import { Debouncer, Deferred, exec, getDiffTool, memoize, needsUpdate, readJson } from "./scripts/build/utils.mjs"; +import { + buildProject, + cleanProject, + watchProject, +} from "./scripts/build/projects.mjs"; +import { + localBaseline, + refBaseline, + runConsoleTests, +} from "./scripts/build/tests.mjs"; +import { + Debouncer, + Deferred, + exec, + getDiffTool, + memoize, + needsUpdate, + readJson, +} from "./scripts/build/utils.mjs"; const glob = util.promisify(_glob); @@ -28,11 +52,10 @@ const copyright = memoize(async () => { return contents.replace(/\r\n/g, "\n"); }); - export const buildScripts = task({ name: "scripts", description: "Builds files in the 'scripts' folder.", - run: () => buildProject("scripts") + run: () => buildProject("scripts"), }); const libs = memoize(() => { @@ -48,7 +71,6 @@ const libs = memoize(() => { return libs; }); - export const generateLibs = task({ name: "lib", description: "Builds the library targets", @@ -67,7 +89,6 @@ export const generateLibs = task({ }, }); - const diagnosticInformationMapTs = "src/compiler/diagnosticInformationMap.generated.ts"; const diagnosticMessagesJson = "src/compiler/diagnosticMessages.json"; const diagnosticMessagesGeneratedJson = "src/compiler/diagnosticMessages.generated.json"; @@ -77,7 +98,7 @@ export const generateDiagnostics = task({ description: "Generates a diagnostic file in TypeScript based on an input JSON file", run: async () => { await exec(process.execPath, ["scripts/processDiagnosticMessages.mjs", diagnosticMessagesJson]); - } + }, }); const cleanDiagnostics = task({ @@ -87,7 +108,6 @@ const cleanDiagnostics = task({ run: () => del([diagnosticInformationMapTs, diagnosticMessagesGeneratedJson]), }); - // Localize diagnostics /** * .lcg file is what localization team uses to know what messages to localize. @@ -113,7 +133,7 @@ const localize = task({ if (needsUpdate(diagnosticMessagesGeneratedJson, generatedLCGFile)) { await exec(process.execPath, ["scripts/generateLocalizedDiagnosticMessages.mjs", "src/loc/lcl", "built/local", diagnosticMessagesGeneratedJson], { ignoreExitCode: true }); } - } + }, }); export const buildSrc = task({ @@ -151,7 +171,6 @@ async function runDtsBundler(entrypoint, output) { ]); } - /** * @param {string} entrypoint * @param {string} outfile @@ -203,14 +222,14 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { options.plugins = [ { name: "fix-require", - setup: (build) => { + setup: build => { build.onEnd(async () => { let contents = await fs.promises.readFile(outfile, "utf-8"); contents = contents.replace(/\$\$require/g, " require"); await fs.promises.writeFile(outfile, contents); }); }, - } + }, ]; } @@ -226,7 +245,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { const onRebuild = taskOptions.onWatchRebuild; options.plugins = (options.plugins?.slice(0) ?? []).concat([{ name: "watch", - setup: (build) => { + setup: build => { let firstBuild = true; build.onEnd(() => { if (firstBuild) { @@ -236,7 +255,7 @@ function createBundler(entrypoint, outfile, taskOptions = {}) { onRebuild(); } }); - } + }, }]); } @@ -331,13 +350,12 @@ function entrypointBuildTask(options) { return watchProject(options.project); } return bundler.watch(); - } + }, }); return { build, bundle, shim, main, watch }; } - const { main: tsc, watch: watchTsc } = entrypointBuildTask({ name: "tsc", description: "Builds the command-line compiler", @@ -350,7 +368,6 @@ const { main: tsc, watch: watchTsc } = entrypointBuildTask({ }); export { tsc, watchTsc }; - const { main: services, build: buildServices, watch: watchServices } = entrypointBuildTask({ name: "services", description: "Builds the typescript.js library", @@ -375,7 +392,6 @@ export const dtsServices = task({ }, }); - const { main: tsserver, watch: watchTsserver } = entrypointBuildTask({ name: "tsserver", description: "Builds the language server", @@ -388,7 +404,6 @@ const { main: tsserver, watch: watchTsserver } = entrypointBuildTask({ }); export { tsserver, watchTsserver }; - export const min = task({ name: "min", description: "Builds only tsc and tsserver", @@ -402,8 +417,6 @@ export const watchMin = task({ dependencies: [watchTsc, watchTsserver], }); - - // This is technically not enough to make tsserverlibrary loadable in the // browser, but it's unlikely that anyone has actually been doing that. const lsslJs = ` @@ -438,7 +451,7 @@ const lssl = task({ dependencies: [services], run: async () => { await fs.promises.writeFile("./built/local/tsserverlibrary.js", await fileContentsWithCopyright(lsslJs)); - } + }, }); export const dtsLssl = task({ @@ -448,7 +461,7 @@ export const dtsLssl = task({ run: async () => { await fs.promises.writeFile("./built/local/tsserverlibrary.d.ts", await fileContentsWithCopyright(lsslDts)); await fs.promises.writeFile("./built/local/tsserverlibrary.internal.d.ts", await fileContentsWithCopyright(lsslDtsInternal)); - } + }, }); export const dts = task({ @@ -456,7 +469,6 @@ export const dts = task({ dependencies: [dtsServices, dtsLssl], }); - const testRunner = "./built/local/run.js"; const watchTestsEmitter = new EventEmitter(); const { main: tests, watch: watchTests } = entrypointBuildTask({ @@ -473,12 +485,11 @@ const { main: tests, watch: watchTests } = entrypointBuildTask({ treeShaking: false, onWatchRebuild() { watchTestsEmitter.emit("rebuild"); - } + }, }, }); export { tests, watchTests }; - export const runEslintRulesTests = task({ name: "run-eslint-rules-tests", description: "Runs the eslint rule tests", @@ -494,8 +505,10 @@ export const lint = task({ const args = [ "node_modules/eslint/bin/eslint", "--cache", - "--cache-location", `${folder}/.eslintcache`, - "--format", formatter, + "--cache-location", + `${folder}/.eslintcache`, + "--format", + formatter, ]; if (cmdLineOptions.fix) { @@ -506,7 +519,19 @@ export const lint = task({ console.log(`Linting: ${args.join(" ")}`); return exec(process.execPath, args); - } + }, +}); + +export const format = task({ + name: "format", + description: "Formats the codebase.", + run: () => exec(process.execPath, ["node_modules/dprint/bin.js", "fmt"]), +}); + +export const checkFormat = task({ + name: "check-format", + description: "Checks that the codebase is formatted.", + run: () => exec(process.execPath, ["node_modules/dprint/bin.js", "check"], { ignoreStdout: true }), }); const { main: cancellationToken, watch: watchCancellationToken } = entrypointBuildTask({ @@ -543,10 +568,9 @@ export const generateTypesMap = task({ const contents = await fs.promises.readFile(source, "utf-8"); JSON.parse(contents); // Validates that the JSON parses. await fs.promises.writeFile(target, contents); - } + }, }); - // Drop a copy of diagnosticMessages.generated.json into the built/local folder. This allows // it to be synced to the Azure DevOps repo, so that it can get picked up by the build // pipeline that generates the localization artifacts that are then fed into the translation process. @@ -558,10 +582,9 @@ const copyBuiltLocalDiagnosticMessages = task({ const contents = await fs.promises.readFile(diagnosticMessagesGeneratedJson, "utf-8"); JSON.parse(contents); // Validates that the JSON parses. await fs.promises.writeFile(builtLocalDiagnosticMessagesGeneratedJson, contents); - } + }, }); - export const otherOutputs = task({ name: "other-outputs", description: "Builds miscelaneous scripts and documents distributed with the LKG", @@ -626,7 +649,7 @@ export const runTestsAndWatch = task({ let watching = true; let running = true; let lastTestChangeTimeMs = Date.now(); - let testsChangedDeferred = /** @type {Deferred} */(new Deferred()); + let testsChangedDeferred = /** @type {Deferred} */ (new Deferred()); let testsChangedCancelSource = CancelToken.source(); const testsChangedDebouncer = new Debouncer(1_000, endRunTests); @@ -636,7 +659,7 @@ export const runTestsAndWatch = task({ "tests/projects/**/*.*", ], { ignorePermissionErrors: true, - alwaysStat: true + alwaysStat: true, }); process.on("SIGINT", endWatchMode); @@ -709,7 +732,7 @@ export const runTestsAndWatch = task({ function endRunTests() { lastTestChangeTimeMs = Date.now(); testsChangedDeferred.resolve(); - testsChangedDeferred = /** @type {Deferred} */(new Deferred()); + testsChangedDeferred = /** @type {Deferred} */ (new Deferred()); } function endWatchMode() { @@ -807,10 +830,9 @@ export const updateSublime = task({ for (const file of ["built/local/tsserver.js", "built/local/tsserver.js.map"]) { await fs.promises.copyFile(file, path.resolve("../TypeScript-Sublime-Plugin/tsserver/", path.basename(file))); } - } + }, }); - export const produceLKG = task({ name: "LKG", description: "Makes a new LKG out of the built js files", @@ -839,7 +861,7 @@ export const produceLKG = task({ } await exec(process.execPath, ["scripts/produceLKG.mjs"]); - } + }, }); export const lkg = task({ diff --git a/package-lock.json b/package-lock.json index c661d8d85002d..183a8a5cfe690 100644 --- a/package-lock.json +++ b/package-lock.json @@ -35,6 +35,7 @@ "chokidar": "^3.5.3", "del": "^6.1.1", "diff": "^5.1.0", + "dprint": "^0.40.2", "esbuild": "^0.19.0", "eslint": "^8.22.0", "eslint-formatter-autolinkable-stylish": "^1.2.0", @@ -75,6 +76,84 @@ "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "dev": true }, + "node_modules/@dprint/darwin-arm64": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/darwin-arm64/-/darwin-arm64-0.40.2.tgz", + "integrity": "sha512-qharMFhxpNq9brgvHLbqzzAgVgPWSHLfzNLwWWhKcGOUUDUIilfAo3SlvOz6w4nQiIifLpYZOvZqK7Lpf9mSSw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@dprint/darwin-x64": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/darwin-x64/-/darwin-x64-0.40.2.tgz", + "integrity": "sha512-FPDdOTVr1JfqtLBTCvqlihWslTy3LBUoi3H1gaqIazCKMj2dB9voFWkBiMT+REMHDrlVsoSpFAfsliNr/y7HPA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@dprint/linux-arm64-glibc": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/linux-arm64-glibc/-/linux-arm64-glibc-0.40.2.tgz", + "integrity": "sha512-GmUWfKwEwXA+onvewX9hEJSMcd9V184+uRbEhI5tG28tBP9+IjQhrY7jCjxPvaZA+EvzNPnAy5D1wbJdlNLBNA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@dprint/linux-x64-glibc": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/linux-x64-glibc/-/linux-x64-glibc-0.40.2.tgz", + "integrity": "sha512-vMHAHdsOY+2thieSWbIrIioDfPgvipwUgd0MZUWOqycTrXU6kLyi2B+5J/2Jc+QO3CiLIbumQd2FH/0vB1eWqA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@dprint/linux-x64-musl": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/linux-x64-musl/-/linux-x64-musl-0.40.2.tgz", + "integrity": "sha512-nFSbDWd9ORyOhJ7a+RmE39WbuPoQ3OQutIgfAmfikiu/wENzEwxxv4QJ7aFnBaoZb0wuVEEpXShr8vY4p0exkg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@dprint/win32-x64": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/win32-x64/-/win32-x64-0.40.2.tgz", + "integrity": "sha512-qF4VCQzFTZYD61lbQqXLU/IwUTbLK22CancO+uVtXmZRoKU9GaVjcBhMUB7URxsa8rvxWHhHT6ldillI/aOWCg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@esbuild/android-arm": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.2.tgz", @@ -1700,6 +1779,24 @@ "node": ">=6.0.0" } }, + "node_modules/dprint": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/dprint/-/dprint-0.40.2.tgz", + "integrity": "sha512-3LdyUV0itEW59UPtsRA2StOWOu8FyOW+BgvJpH/tACRHKi0z5gaQnvSxdS3mbG7dgtEhdRnGg6JoiQyGib6NTg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "dprint": "bin.js" + }, + "optionalDependencies": { + "@dprint/darwin-arm64": "0.40.2", + "@dprint/darwin-x64": "0.40.2", + "@dprint/linux-arm64-glibc": "0.40.2", + "@dprint/linux-x64-glibc": "0.40.2", + "@dprint/linux-x64-musl": "0.40.2", + "@dprint/win32-x64": "0.40.2" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -3905,6 +4002,48 @@ "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", "dev": true }, + "@dprint/darwin-arm64": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/darwin-arm64/-/darwin-arm64-0.40.2.tgz", + "integrity": "sha512-qharMFhxpNq9brgvHLbqzzAgVgPWSHLfzNLwWWhKcGOUUDUIilfAo3SlvOz6w4nQiIifLpYZOvZqK7Lpf9mSSw==", + "dev": true, + "optional": true + }, + "@dprint/darwin-x64": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/darwin-x64/-/darwin-x64-0.40.2.tgz", + "integrity": "sha512-FPDdOTVr1JfqtLBTCvqlihWslTy3LBUoi3H1gaqIazCKMj2dB9voFWkBiMT+REMHDrlVsoSpFAfsliNr/y7HPA==", + "dev": true, + "optional": true + }, + "@dprint/linux-arm64-glibc": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/linux-arm64-glibc/-/linux-arm64-glibc-0.40.2.tgz", + "integrity": "sha512-GmUWfKwEwXA+onvewX9hEJSMcd9V184+uRbEhI5tG28tBP9+IjQhrY7jCjxPvaZA+EvzNPnAy5D1wbJdlNLBNA==", + "dev": true, + "optional": true + }, + "@dprint/linux-x64-glibc": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/linux-x64-glibc/-/linux-x64-glibc-0.40.2.tgz", + "integrity": "sha512-vMHAHdsOY+2thieSWbIrIioDfPgvipwUgd0MZUWOqycTrXU6kLyi2B+5J/2Jc+QO3CiLIbumQd2FH/0vB1eWqA==", + "dev": true, + "optional": true + }, + "@dprint/linux-x64-musl": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/linux-x64-musl/-/linux-x64-musl-0.40.2.tgz", + "integrity": "sha512-nFSbDWd9ORyOhJ7a+RmE39WbuPoQ3OQutIgfAmfikiu/wENzEwxxv4QJ7aFnBaoZb0wuVEEpXShr8vY4p0exkg==", + "dev": true, + "optional": true + }, + "@dprint/win32-x64": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/@dprint/win32-x64/-/win32-x64-0.40.2.tgz", + "integrity": "sha512-qF4VCQzFTZYD61lbQqXLU/IwUTbLK22CancO+uVtXmZRoKU9GaVjcBhMUB7URxsa8rvxWHhHT6ldillI/aOWCg==", + "dev": true, + "optional": true + }, "@esbuild/android-arm": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.2.tgz", @@ -5008,6 +5147,20 @@ "esutils": "^2.0.2" } }, + "dprint": { + "version": "0.40.2", + "resolved": "https://registry.npmjs.org/dprint/-/dprint-0.40.2.tgz", + "integrity": "sha512-3LdyUV0itEW59UPtsRA2StOWOu8FyOW+BgvJpH/tACRHKi0z5gaQnvSxdS3mbG7dgtEhdRnGg6JoiQyGib6NTg==", + "dev": true, + "requires": { + "@dprint/darwin-arm64": "0.40.2", + "@dprint/darwin-x64": "0.40.2", + "@dprint/linux-arm64-glibc": "0.40.2", + "@dprint/linux-x64-glibc": "0.40.2", + "@dprint/linux-x64-musl": "0.40.2", + "@dprint/win32-x64": "0.40.2" + } + }, "emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", diff --git a/package.json b/package.json index cc39f6cba399e..ea2323bac3b81 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ "chokidar": "^3.5.3", "del": "^6.1.1", "diff": "^5.1.0", + "dprint": "^0.40.2", "esbuild": "^0.19.0", "eslint": "^8.22.0", "eslint-formatter-autolinkable-stylish": "^1.2.0", @@ -96,6 +97,7 @@ "clean": "hereby clean", "gulp": "hereby", "lint": "hereby lint", + "format": "dprint fmt", "setup-hooks": "node scripts/link-hooks.mjs" }, "browser": { diff --git a/scripts/browserIntegrationTest.mjs b/scripts/browserIntegrationTest.mjs index fd06edc654ee1..bb1007743b4a6 100644 --- a/scripts/browserIntegrationTest.mjs +++ b/scripts/browserIntegrationTest.mjs @@ -1,6 +1,10 @@ import chalk from "chalk"; -import { readFileSync } from "fs"; -import { join } from "path"; +import { + readFileSync, +} from "fs"; +import { + join, +} from "path"; let playwright; try { diff --git a/scripts/build/findUpDir.mjs b/scripts/build/findUpDir.mjs index 246e11b8e1be9..44bbc658beda5 100644 --- a/scripts/build/findUpDir.mjs +++ b/scripts/build/findUpDir.mjs @@ -1,5 +1,11 @@ -import { existsSync } from "fs"; -import { dirname, join, resolve } from "path"; +import { + existsSync, +} from "fs"; +import { + dirname, + join, + resolve, +} from "path"; import url from "url"; const __filename = url.fileURLToPath(new URL(import.meta.url)); diff --git a/scripts/build/options.mjs b/scripts/build/options.mjs index ce2aa1330cb67..be5ef5ae4eac5 100644 --- a/scripts/build/options.mjs +++ b/scripts/build/options.mjs @@ -8,15 +8,15 @@ const parsed = minimist(process.argv.slice(2), { string: ["browser", "tests", "break", "host", "reporter", "stackTraceLimit", "timeout", "shards", "shardId"], alias: { /* eslint-disable quote-props */ - "b": "browser", - "i": ["inspect", "inspect-brk", "break", "debug", "debug-brk"], - "t": ["tests", "test"], - "ru": ["runners", "runner"], - "r": "reporter", - "c": ["colors", "color"], - "skippercent": "skipPercent", - "w": "workers", - "f": "fix" + b: "browser", + i: ["inspect", "inspect-brk", "break", "debug", "debug-brk"], + t: ["tests", "test"], + ru: ["runners", "runner"], + r: "reporter", + c: ["colors", "color"], + skippercent: "skipPercent", + w: "workers", + f: "fix", /* eslint-enable quote-props */ }, default: { @@ -43,7 +43,7 @@ const parsed = minimist(process.argv.slice(2), { typecheck: true, lint: true, coverage: false, - } + }, }); /** @type {CommandLineOptions} */ @@ -59,8 +59,6 @@ if (!options.bundle && !options.typecheck) { export default options; - - /** * @typedef CommandLineOptions * @property {boolean} dirty diff --git a/scripts/build/projects.mjs b/scripts/build/projects.mjs index 812bdb5c6287c..70e25766672c0 100644 --- a/scripts/build/projects.mjs +++ b/scripts/build/projects.mjs @@ -1,8 +1,15 @@ -import { resolve } from "path"; +import { + resolve, +} from "path"; -import { findUpRoot } from "./findUpDir.mjs"; +import { + findUpRoot, +} from "./findUpDir.mjs"; import cmdLineOptions from "./options.mjs"; -import { Debouncer, exec } from "./utils.mjs"; +import { + Debouncer, + exec, +} from "./utils.mjs"; class ProjectQueue { /** @@ -33,29 +40,29 @@ class ProjectQueue { const tscPath = resolve( findUpRoot(), cmdLineOptions.lkg ? "./lib/tsc.js" : - cmdLineOptions.built ? "./built/local/tsc.js" : - "./node_modules/typescript/lib/tsc.js", + cmdLineOptions.built ? "./built/local/tsc.js" : + "./node_modules/typescript/lib/tsc.js", ); const execTsc = (/** @type {string[]} */ ...args) => exec(process.execPath, [tscPath, "-b", ...args], { hidePrompt: true }); -const projectBuilder = new ProjectQueue((projects) => execTsc(...(cmdLineOptions.bundle ? [] : ["--emitDeclarationOnly", "false"]), ...projects)); +const projectBuilder = new ProjectQueue(projects => execTsc(...(cmdLineOptions.bundle ? [] : ["--emitDeclarationOnly", "false"]), ...projects)); /** * @param {string} project */ -export const buildProject = (project) => projectBuilder.enqueue(project); +export const buildProject = project => projectBuilder.enqueue(project); -const projectCleaner = new ProjectQueue((projects) => execTsc("--clean", ...projects)); +const projectCleaner = new ProjectQueue(projects => execTsc("--clean", ...projects)); /** * @param {string} project */ -export const cleanProject = (project) => projectCleaner.enqueue(project); +export const cleanProject = project => projectCleaner.enqueue(project); -const projectWatcher = new ProjectQueue((projects) => execTsc("--watch", "--preserveWatchOutput", ...projects)); +const projectWatcher = new ProjectQueue(projects => execTsc("--watch", "--preserveWatchOutput", ...projects)); /** * @param {string} project */ -export const watchProject = (project) => projectWatcher.enqueue(project); +export const watchProject = project => projectWatcher.enqueue(project); diff --git a/scripts/build/tests.mjs b/scripts/build/tests.mjs index 205076f51dd3e..eda3422e365d1 100644 --- a/scripts/build/tests.mjs +++ b/scripts/build/tests.mjs @@ -1,13 +1,21 @@ -import { CancelError } from "@esfx/canceltoken"; +import { + CancelError, +} from "@esfx/canceltoken"; import chalk from "chalk"; import del from "del"; import fs from "fs"; import os from "os"; import path from "path"; -import { findUpFile, findUpRoot } from "./findUpDir.mjs"; +import { + findUpFile, + findUpRoot, +} from "./findUpDir.mjs"; import cmdLineOptions from "./options.mjs"; -import { exec, ExecError } from "./utils.mjs"; +import { + exec, + ExecError, +} from "./utils.mjs"; const mochaJs = path.resolve(findUpRoot(), "node_modules", "mocha", "bin", "_mocha"); export const localBaseline = "tests/baselines/local/"; @@ -59,7 +67,8 @@ export async function runConsoleTests(runJs, defaultReporter, runInParallel, opt do { taskConfigsFolder = prefix + i; i++; - } while (fs.existsSync(taskConfigsFolder)); + } + while (fs.existsSync(taskConfigsFolder)); fs.mkdirSync(taskConfigsFolder); workerCount = cmdLineOptions.workers; @@ -106,7 +115,7 @@ export async function runConsoleTests(runJs, defaultReporter, runInParallel, opt args.push("--no-colors"); } if (inspect !== undefined) { - args.unshift((inspect === "" || inspect === true) ? "--inspect-brk" : "--inspect-brk="+inspect); + args.unshift((inspect === "" || inspect === true) ? "--inspect-brk" : "--inspect-brk=" + inspect); args.push("-t", "0"); } else { @@ -201,7 +210,7 @@ export function writeTestConfigFile(tests, runners, light, taskConfigsFolder, wo timeout, keepFailed, shards, - shardId + shardId, }); console.info("Running tests with config: " + testConfigContents); fs.writeFileSync("test.config", testConfigContents); diff --git a/scripts/build/utils.mjs b/scripts/build/utils.mjs index ec3b7bccaa220..6a60fec2d995d 100644 --- a/scripts/build/utils.mjs +++ b/scripts/build/utils.mjs @@ -1,7 +1,11 @@ -import { CancelError } from "@esfx/canceltoken"; +import { + CancelError, +} from "@esfx/canceltoken"; import assert from "assert"; import chalk from "chalk"; -import { spawn } from "child_process"; +import { + spawn, +} from "child_process"; import fs from "fs"; import JSONC from "jsonc-parser"; import which from "which"; @@ -16,14 +20,15 @@ import which from "which"; * @property {boolean} [ignoreExitCode] * @property {boolean} [hidePrompt] * @property {boolean} [waitForExit=true] + * @property {boolean} [ignoreStdout] * @property {import("@esfx/canceltoken").CancelToken} [token] */ export async function exec(cmd, args, options = {}) { - return /**@type {Promise<{exitCode?: number}>}*/(new Promise((resolve, reject) => { - const { ignoreExitCode, waitForExit = true } = options; + return /**@type {Promise<{exitCode?: number}>}*/ (new Promise((resolve, reject) => { + const { ignoreExitCode, waitForExit = true, ignoreStdout } = options; if (!options.hidePrompt) console.log(`> ${chalk.green(cmd)} ${args.join(" ")}`); - const proc = spawn(which.sync(cmd), args, { stdio: waitForExit ? "inherit" : "ignore" }); + const proc = spawn(which.sync(cmd), args, { stdio: waitForExit ? ignoreStdout ? ["inherit", "ignore", "inherit"] : "inherit" : "ignore" }); if (waitForExit) { const onCanceled = () => { proc.kill(); @@ -83,18 +88,18 @@ export function readJson(jsonPath) { export function needsUpdate(source, dest) { if (typeof source === "string" && typeof dest === "string") { if (fs.existsSync(dest)) { - const {mtime: outTime} = fs.statSync(dest); - const {mtime: inTime} = fs.statSync(source); + const { mtime: outTime } = fs.statSync(dest); + const { mtime: inTime } = fs.statSync(source); if (+inTime <= +outTime) { return false; } } } else if (typeof source === "string" && typeof dest !== "string") { - const {mtime: inTime} = fs.statSync(source); + const { mtime: inTime } = fs.statSync(source); for (const filepath of dest) { if (fs.existsSync(filepath)) { - const {mtime: outTime} = fs.statSync(filepath); + const { mtime: outTime } = fs.statSync(filepath); if (+inTime > +outTime) { return true; } @@ -107,10 +112,10 @@ export function needsUpdate(source, dest) { } else if (typeof source !== "string" && typeof dest === "string") { if (fs.existsSync(dest)) { - const {mtime: outTime} = fs.statSync(dest); + const { mtime: outTime } = fs.statSync(dest); for (const filepath of source) { if (fs.existsSync(filepath)) { - const {mtime: inTime} = fs.statSync(filepath); + const { mtime: inTime } = fs.statSync(filepath); if (+inTime > +outTime) { return true; } @@ -128,8 +133,8 @@ export function needsUpdate(source, dest) { continue; } if (fs.existsSync(dest[i])) { - const {mtime: outTime} = fs.statSync(dest[i]); - const {mtime: inTime} = fs.statSync(source[i]); + const { mtime: outTime } = fs.statSync(dest[i]); + const { mtime: inTime } = fs.statSync(source[i]); if (+inTime > +outTime) { return true; } @@ -175,7 +180,9 @@ export class Debouncer { this._action = action; } - get empty() { return !this._deferred; } + get empty() { + return !this._deferred; + } enqueue() { if (this._timer) { diff --git a/scripts/checkModuleFormat.mjs b/scripts/checkModuleFormat.mjs index 0ce73003b7a0a..6c461d370a32e 100644 --- a/scripts/checkModuleFormat.mjs +++ b/scripts/checkModuleFormat.mjs @@ -1,5 +1,10 @@ -import { createRequire } from "module"; -import { __importDefault, __importStar } from "tslib"; +import { + createRequire, +} from "module"; +import { + __importDefault, + __importStar, +} from "tslib"; // This script tests that TypeScript's CJS API is structured // as expected. It calls "require" as though it were in CWD, @@ -13,12 +18,12 @@ const ts = require(process.argv[2]); // See: https://github.com/microsoft/TypeScript/pull/51474#issuecomment-1310871623 /** @type {[fn: (() => any), shouldSucceed: boolean][]} */ const fns = [ - [() => ts.version, true], - [() => ts.default.version, false], - [() => __importDefault(ts).version, false], + [() => ts.version, true], + [() => ts.default.version, false], + [() => __importDefault(ts).version, false], [() => __importDefault(ts).default.version, true], - [() => __importStar(ts).version, true], - [() => __importStar(ts).default.version, true], + [() => __importStar(ts).version, true], + [() => __importStar(ts).default.version, true], ]; for (const [fn, shouldSucceed] of fns) { diff --git a/scripts/checkPackageSize.mjs b/scripts/checkPackageSize.mjs index 9614ca195842a..4d65c7328102e 100644 --- a/scripts/checkPackageSize.mjs +++ b/scripts/checkPackageSize.mjs @@ -117,7 +117,7 @@ else { prettyPrintSizeDiff(before.unpackedSize, after.unpackedSize), prettyPercentDiff(before.unpackedSize, after.unpackedSize), ], - ] + ], ); } @@ -126,7 +126,6 @@ failIfTooBig(before.unpackedSize, after.unpackedSize); console.log(); - /** @type {Map} */ const fileCounts = new Map(); const inBefore = -1; diff --git a/scripts/configurePrerelease.mjs b/scripts/configurePrerelease.mjs index 66c83c207ae42..de0d48f0f657e 100644 --- a/scripts/configurePrerelease.mjs +++ b/scripts/configurePrerelease.mjs @@ -1,7 +1,15 @@ import assert from "assert"; -import { execFileSync } from "child_process"; -import { readFileSync, writeFileSync } from "fs"; -import { normalize, relative } from "path"; +import { + execFileSync, +} from "child_process"; +import { + readFileSync, + writeFileSync, +} from "fs"; +import { + normalize, + relative, +} from "path"; import url from "url"; const __filename = url.fileURLToPath(new URL(import.meta.url)); diff --git a/scripts/dtsBundler.mjs b/scripts/dtsBundler.mjs index 305172d3199e1..ddf3b36cefd79 100644 --- a/scripts/dtsBundler.mjs +++ b/scripts/dtsBundler.mjs @@ -5,7 +5,10 @@ * bundle as namespaces again, even though the project is modules. */ -import assert, { fail } from "assert"; +import assert, { + fail, +} from "assert"; +import cp from "child_process"; import fs from "fs"; import minimist from "minimist"; import path from "path"; @@ -48,7 +51,6 @@ function isInternalDeclaration(node) { } /** - * * @param {ts.VariableDeclaration} node * @returns {ts.VariableStatement} */ @@ -62,7 +64,6 @@ function getParentVariableStatement(node) { } /** - * * @param {ts.Declaration} node * @returns {ts.Statement | undefined} */ @@ -207,8 +208,8 @@ function nodeToLocation(node) { function removeDeclareConstExport(node) { switch (node.kind) { case ts.SyntaxKind.DeclareKeyword: // No need to emit this in d.ts files. - case ts.SyntaxKind.ConstKeyword: // Remove const from const enums. - case ts.SyntaxKind.ExportKeyword: // No export modifier; we are already in the namespace. + case ts.SyntaxKind.ConstKeyword: // Remove const from const enums. + case ts.SyntaxKind.ExportKeyword: // No export modifier; we are already in the namespace. return undefined; } return node; @@ -374,7 +375,7 @@ function emitAsNamespace(name, moduleSymbol) { const isInternal = isInternalDeclaration(statement); if (!isInternal) { - const publicStatement = ts.visitEachChild(statement, (node) => { + const publicStatement = ts.visitEachChild(statement, node => { // No @internal comments in the public API. if (isInternalDeclaration(node)) { return undefined; @@ -409,5 +410,24 @@ if (publicContents.includes("@internal")) { console.error("Output includes untrimmed @internal nodes!"); } -fs.writeFileSync(output, publicContents); -fs.writeFileSync(internalOutput, internalContents); +const dprintPath = path.resolve(__dirname, "..", "node_modules", "dprint", "bin.js"); + +/** + * @param {string} contents + * @returns {string} + */ +function dprint(contents) { + return cp.execFileSync( + process.execPath, + [dprintPath, "fmt", "--stdin", "ts"], + { + stdio: ["pipe", "pipe", "inherit"], + encoding: "utf-8", + input: contents, + maxBuffer: 100 * 1024 * 1024, // 100 MB "ought to be enough for anyone"; https://github.com/nodejs/node/issues/9829 + }, + ); +} + +fs.writeFileSync(output, dprint(publicContents)); +fs.writeFileSync(internalOutput, dprint(internalContents)); diff --git a/scripts/eslint/rules/argument-trivia.cjs b/scripts/eslint/rules/argument-trivia.cjs index 49ec726dc4b04..4e3b6011e765b 100644 --- a/scripts/eslint/rules/argument-trivia.cjs +++ b/scripts/eslint/rules/argument-trivia.cjs @@ -19,7 +19,6 @@ function memoize(fn) { }; } - module.exports = createRule({ name: "argument-trivia", meta: { @@ -42,9 +41,9 @@ module.exports = createRule({ const sourceCodeText = sourceCode.getText(); /** @type {(name: string) => boolean} */ - const isSetOrAssert = (name) => name.startsWith("set") || name.startsWith("assert"); + const isSetOrAssert = name => name.startsWith("set") || name.startsWith("assert"); /** @type {(node: TSESTree.Node) => boolean} */ - const isTrivia = (node) => { + const isTrivia = node => { if (node.type === AST_NODE_TYPES.Identifier) { return node.name === "undefined"; } @@ -58,7 +57,7 @@ module.exports = createRule({ }; /** @type {(node: TSESTree.CallExpression | TSESTree.NewExpression) => boolean} */ - const shouldIgnoreCalledExpression = (node) => { + const shouldIgnoreCalledExpression = node => { if (node.callee && node.callee.type === AST_NODE_TYPES.MemberExpression) { const methodName = node.callee.property.type === AST_NODE_TYPES.Identifier ? node.callee.property.name @@ -98,7 +97,6 @@ module.exports = createRule({ return false; }; - /** @type {(node: TSESTree.Node, i: number, getSignature: () => ts.Signature | undefined) => void} */ const checkArg = (node, i, getSignature) => { if (!isTrivia(node)) { @@ -130,9 +128,9 @@ module.exports = createRule({ context.report({ messageId: "argumentTriviaArgumentError", node, - fix: (fixer) => { + fix: fixer => { return fixer.insertTextBefore(node, `/*${expectedName}*/ `); - } + }, }); } else { @@ -151,7 +149,7 @@ module.exports = createRule({ messageId: "argumentTriviaArgumentNameError", data: { got, want: expectedName }, node: comment, - fix: (fixer) => { + fix: fixer => { return fixer.replaceText(comment, `/*${expectedName}*/`); }, }); @@ -165,15 +163,15 @@ module.exports = createRule({ context.report({ messageId: "argumentTriviaArgumentSpaceError", node, - fix: (fixer) => { + fix: fixer => { return fixer.replaceTextRange([commentRangeEnd, argRangeStart], " "); - } + }, }); } }; /** @type {(node: TSESTree.CallExpression | TSESTree.NewExpression) => void} */ - const checkArgumentTrivia = (node) => { + const checkArgumentTrivia = node => { if (shouldIgnoreCalledExpression(node)) { return; } diff --git a/scripts/eslint/rules/debug-assert.cjs b/scripts/eslint/rules/debug-assert.cjs index 8b2e0b0596a11..31a735c246889 100644 --- a/scripts/eslint/rules/debug-assert.cjs +++ b/scripts/eslint/rules/debug-assert.cjs @@ -18,22 +18,22 @@ module.exports = createRule({ create(context) { /** @type {(node: TSESTree.Node) => boolean} */ - const isArrowFunction = (node) => node.type === AST_NODE_TYPES.ArrowFunctionExpression; + const isArrowFunction = node => node.type === AST_NODE_TYPES.ArrowFunctionExpression; /** @type {(node: TSESTree.Node) => boolean} */ - const isStringLiteral = (node) => ( + const isStringLiteral = node => ( (node.type === AST_NODE_TYPES.Literal && typeof node.value === "string") || node.type === AST_NODE_TYPES.TemplateLiteral ); /** @type {(node: TSESTree.MemberExpression) => boolean} */ - const isDebugAssert = (node) => ( + const isDebugAssert = node => ( node.object.type === AST_NODE_TYPES.Identifier - && node.object.name === "Debug" - && node.property.type === AST_NODE_TYPES.Identifier - && node.property.name === "assert" + && node.object.name === "Debug" + && node.property.type === AST_NODE_TYPES.Identifier + && node.property.name === "assert" ); /** @type {(node: TSESTree.CallExpression) => void} */ - const checkDebugAssert = (node) => { + const checkDebugAssert = node => { const args = node.arguments; const argsLen = args.length; if (!(node.callee.type === AST_NODE_TYPES.MemberExpression && isDebugAssert(node.callee)) || argsLen < 2) { diff --git a/scripts/eslint/rules/jsdoc-format.cjs b/scripts/eslint/rules/jsdoc-format.cjs index 140e22b5e4fd3..b16de44b4aaa5 100644 --- a/scripts/eslint/rules/jsdoc-format.cjs +++ b/scripts/eslint/rules/jsdoc-format.cjs @@ -12,7 +12,6 @@ module.exports = createRule({ internalCommentNotLastError: `@internal should only appear in final JSDoc comment for declaration.`, multipleJSDocError: `Declaration has multiple JSDoc comments.`, internalCommentOnParameterProperty: `@internal cannot appear on a JSDoc comment; use a declared property and an assignment in the constructor instead.`, - misalignedJSDocComment: `This JSDoc comment is misaligned.`, }, schema: [], type: "problem", @@ -46,7 +45,7 @@ module.exports = createRule({ }; /** @type {(c: TSESTree.Comment) => TSESTree.SourceLocation} */ - const getJSDocStartLoc = (c) => { + const getJSDocStartLoc = c => { return { start: c.loc.start, end: { @@ -57,7 +56,7 @@ module.exports = createRule({ }; /** @type {(node: TSESTree.Node) => void} */ - const checkDeclaration = (node) => { + const checkDeclaration = node => { const blockComments = sourceCode.getCommentsBefore(node).filter(c => c.type === "Block"); if (blockComments.length === 0) { return; @@ -92,67 +91,7 @@ module.exports = createRule({ } }; - /** @type {(node: TSESTree.Node) => void} */ - const checkProgram = () => { - const comments = sourceCode.getAllComments(); - - for (const c of comments) { - if (c.type !== "Block") { - continue; - } - - const rawComment = sourceCode.getText(c); - if (!isJSDocText(rawComment)) { - continue; - } - - const expected = c.loc.start.column + 2; - const split = rawComment.split(/\r?\n/g); - for (let i = 1; i < split.length; i++) { - const line = split[i]; - const match = /^ *\*/.exec(line); - if (!match) { - continue; - } - - const actual = match[0].length; - const diff = actual - expected; - if (diff !== 0) { - const line = c.loc.start.line + i; - context.report({ - messageId: "misalignedJSDocComment", - node: c, - loc: { - start: { - line, - column: 0, - }, - end: { - line, - column: actual - 1, - } - }, - fix: (fixer) => { - if (diff > 0) { - // Too many - const start = sourceCode.getIndexFromLoc({ line, column: expected - 1 }); - return fixer.removeRange([start, start + diff]); - } - else { - // Too few - const start = sourceCode.getIndexFromLoc({ line, column: 0 }); - return fixer.insertTextAfterRange([start, start], " ".repeat(-diff)); - } - }, - }); - break; - } - } - } - }; - return { - Program: checkProgram, ClassDeclaration: checkDeclaration, FunctionDeclaration: checkDeclaration, TSEnumDeclaration: checkDeclaration, diff --git a/scripts/eslint/rules/no-double-space.cjs b/scripts/eslint/rules/no-double-space.cjs deleted file mode 100644 index 75c74d031a4fe..0000000000000 --- a/scripts/eslint/rules/no-double-space.cjs +++ /dev/null @@ -1,72 +0,0 @@ -const { TSESTree, AST_NODE_TYPES } = require("@typescript-eslint/utils"); -const { createRule } = require("./utils.cjs"); - -module.exports = createRule({ - name: "no-double-space", - meta: { - docs: { - description: ``, - }, - messages: { - noDoubleSpaceError: `Use only one space`, - }, - schema: [], - type: "problem", - }, - defaultOptions: [], - - create(context) { - const sourceCode = context.getSourceCode(); - const lines = sourceCode.getLines(); - - /** @type {(node: TSESTree.Node | null) => boolean} */ - const isStringLiteral = (node) => { - return !!(node && ( - (node.type === AST_NODE_TYPES.TemplateElement) || - (node.type === AST_NODE_TYPES.TemplateLiteral && node.quasis) || - (node.type === AST_NODE_TYPES.Literal && typeof node.value === "string") - )); - }; - - /** @type {(node: TSESTree.Node | null) => boolean} */ - const isRegexLiteral = (node) => { - return !!(node && node.type === AST_NODE_TYPES.Literal && Object.prototype.hasOwnProperty.call(node, "regex")); - }; - - /** @type {(node: TSESTree.Node) => void} */ - const checkDoubleSpace = (node) => { - lines.forEach((line, index) => { - const firstNonSpace = /\S/.exec(line); - if (!firstNonSpace || line.includes("@param")) { - return; - } - - // Allow common uses of double spaces - // * To align `=` or `!=` signs - // * To align comments at the end of lines - // * To indent inside a comment - // * To use two spaces after a period - // * To include aligned `->` in a comment - const rgx = /[^/*. ][ ]{2}[^-!/= ]/g; - rgx.lastIndex = firstNonSpace.index; - const doubleSpace = rgx.exec(line); - - if (!doubleSpace) { - return; - } - - const locIndex = sourceCode.getIndexFromLoc({ column: doubleSpace.index, line: index + 1 }); - const sourceNode = sourceCode.getNodeByRangeIndex(locIndex); - if (isStringLiteral(sourceNode) || isRegexLiteral(sourceNode)) { - return; - } - - context.report({ messageId: "noDoubleSpaceError", node, loc: { line: index + 1, column: doubleSpace.index + 1 } }); - }); - }; - - return { - Program: checkDoubleSpace, - }; - }, -}); diff --git a/scripts/eslint/rules/no-in-operator.cjs b/scripts/eslint/rules/no-in-operator.cjs index bbd2b60532596..cbd357b86823e 100644 --- a/scripts/eslint/rules/no-in-operator.cjs +++ b/scripts/eslint/rules/no-in-operator.cjs @@ -18,7 +18,7 @@ module.exports = createRule({ create(context) { const IN_OPERATOR = "in"; /** @type {(node: TSESTree.BinaryExpression) => void} */ - const checkInOperator = (node) => { + const checkInOperator = node => { if (node.operator === IN_OPERATOR) { context.report({ messageId: "noInOperatorError", node }); } diff --git a/scripts/eslint/rules/no-keywords.cjs b/scripts/eslint/rules/no-keywords.cjs index 0cb0c9f7b1d4f..a0032bf5ff102 100644 --- a/scripts/eslint/rules/no-keywords.cjs +++ b/scripts/eslint/rules/no-keywords.cjs @@ -35,15 +35,15 @@ module.exports = createRule({ ]; /** @type {(name: string) => boolean} */ - const isKeyword = (name) => keywords.includes(name); + const isKeyword = name => keywords.includes(name); /** @type {(node: TSESTree.Identifier) => void} */ - const report = (node) => { + const report = node => { context.report({ messageId: "noKeywordsError", data: { name: node.name }, node }); }; /** @type {(node: TSESTree.ObjectPattern) => void} */ - const checkProperties = (node) => { + const checkProperties = node => { node.properties.forEach(property => { if ( property && @@ -57,7 +57,7 @@ module.exports = createRule({ }; /** @type {(node: TSESTree.ArrayPattern) => void} */ - const checkElements = (node) => { + const checkElements = node => { node.elements.forEach(element => { if ( element && @@ -70,7 +70,7 @@ module.exports = createRule({ }; /** @type {(node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.TSMethodSignature | TSESTree.TSFunctionType) => void} */ - const checkParams = (node) => { + const checkParams = node => { if (!node || !node.params || !node.params.length) { return; } diff --git a/scripts/eslint/rules/no-type-assertion-whitespace.cjs b/scripts/eslint/rules/no-type-assertion-whitespace.cjs deleted file mode 100644 index 3f10a85dbc7f8..0000000000000 --- a/scripts/eslint/rules/no-type-assertion-whitespace.cjs +++ /dev/null @@ -1,42 +0,0 @@ -const { TSESTree } = require("@typescript-eslint/utils"); -const { createRule } = require("./utils.cjs"); - -module.exports = createRule({ - name: "no-type-assertion-whitespace", - meta: { - docs: { - description: ``, - }, - messages: { - noTypeAssertionWhitespace: `Excess trailing whitespace found around type assertion`, - }, - schema: [], - type: "problem", - }, - defaultOptions: [], - - create(context) { - const sourceCode = context.getSourceCode(); - /** @type {(node: TSESTree.TSTypeAssertion) => void} */ - const checkTypeAssertionWhitespace = (node) => { - const leftToken = sourceCode.getLastToken(node.typeAnnotation); - const rightToken = sourceCode.getFirstToken(node.expression); - - if (!leftToken || !rightToken) { - return; - } - - if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken)) { - context.report({ - messageId: "noTypeAssertionWhitespace", - node, - loc: { column: leftToken.loc.end.column + 1, line: leftToken.loc.end.line }, - }); - } - }; - - return { - TSTypeAssertion: checkTypeAssertionWhitespace, - }; - }, -}); diff --git a/scripts/eslint/rules/object-literal-surrounding-space.cjs b/scripts/eslint/rules/object-literal-surrounding-space.cjs deleted file mode 100644 index b2c8604790170..0000000000000 --- a/scripts/eslint/rules/object-literal-surrounding-space.cjs +++ /dev/null @@ -1,71 +0,0 @@ -const { TSESTree } = require("@typescript-eslint/utils"); -const { createRule } = require("./utils.cjs"); - -module.exports = createRule({ - name: "object-literal-surrounding-space", - meta: { - docs: { - description: ``, - }, - messages: { - leadingExcessStringError: `No trailing whitespace found on single-line object literal`, - leadingStringError: `No leading whitespace found on single-line object literal`, - - trailingExcessStringError: `Excess trailing whitespace found on single-line object literal.`, - trailingStringError: `No trailing whitespace found on single-line object literal`, - }, - schema: [], - type: "suggestion", - }, - defaultOptions: [], - - create(context) { - const sourceCode = context.getSourceCode(); - const SPACE_SYMBOL = " "; - const CLOSE_SYMBOL = "}"; - const OPEN_SYMBOL = "{"; - - /** @type {(text: string, startIndex: number) => boolean} */ - const manySpaces = (text, startIndex) => ( - [startIndex, startIndex + 1].every(i => text.charAt(i) === SPACE_SYMBOL) - ); - - /** @type {(node: TSESTree.ObjectExpression) => void} */ - const checkObjectLiteralSurroundingSpace = (node) => { - const text = sourceCode.getText(node); - const startLine = node.loc.start.line; - const endLine = node.loc.end.line; - - if (!node.properties.length || !text.match(/^{[^\n]+}$/g)) { - return; - } - - if (text.charAt(0) === OPEN_SYMBOL) { - if (text.charAt(1) !== SPACE_SYMBOL) { - context.report({ messageId: "leadingStringError", node }); - } - - if (manySpaces(text, 1)) { - context.report({ messageId: "leadingExcessStringError", node, loc: { column: node.loc.start.column + 1, line: startLine } }); - } - } - - if (text.charAt(text.length - 1) === CLOSE_SYMBOL) { - const index = text.length - 2; - const endColumn = node.loc.end.column; - - if (text.charAt(index) !== SPACE_SYMBOL) { - context.report({ messageId: "trailingStringError", node, loc: { column: endColumn - 1, line: endLine } }); - } - - if (manySpaces(text, index - 1)) { - context.report({ messageId: "trailingExcessStringError", node, loc: { column: endColumn - 2, line: endLine } }); - } - } - }; - - return { - ObjectExpression: checkObjectLiteralSurroundingSpace, - }; - }, -}); diff --git a/scripts/eslint/rules/only-arrow-functions.cjs b/scripts/eslint/rules/only-arrow-functions.cjs index d68ab8a397a67..9abde8775c08d 100644 --- a/scripts/eslint/rules/only-arrow-functions.cjs +++ b/scripts/eslint/rules/only-arrow-functions.cjs @@ -27,12 +27,11 @@ module.exports = createRule({ }], create(context, [{ allowNamedFunctions, allowDeclarations }]) { - /** @type {(node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression) => boolean} */ - const isThisParameter = (node) => !!node.params.length && !!node.params.find(param => param.type === AST_NODE_TYPES.Identifier && param.name === "this"); + const isThisParameter = node => !!node.params.length && !!node.params.find(param => param.type === AST_NODE_TYPES.Identifier && param.name === "this"); /** @type {(node: TSESTree.Node) => boolean} */ - const isMethodType = (node) => { + const isMethodType = node => { const types = [ AST_NODE_TYPES.MethodDefinition, AST_NODE_TYPES.Property, @@ -59,7 +58,7 @@ module.exports = createRule({ }; /** @type {(node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression) => void} */ - const exitFunction = (node) => { + const exitFunction = node => { const methodUsesThis = stack.pop(); if (node.type === AST_NODE_TYPES.FunctionDeclaration && allowDeclarations) { diff --git a/scripts/eslint/rules/simple-indent.cjs b/scripts/eslint/rules/simple-indent.cjs deleted file mode 100644 index 958e04658ee29..0000000000000 --- a/scripts/eslint/rules/simple-indent.cjs +++ /dev/null @@ -1,68 +0,0 @@ -const { TSESTree } = require("@typescript-eslint/utils"); -const { createRule } = require("./utils.cjs"); - -module.exports = createRule({ - name: "simple-indent", - meta: { - docs: { - description: "Enforce consistent indentation", - }, - messages: { - simpleIndentError: "4 space indentation expected", - }, - fixable: "whitespace", - schema: [], - type: "layout", - }, - defaultOptions: [], - create(context) { - const TAB_SIZE = 4; - const TAB_REGEX = /\t/g; - const sourceCode = context.getSourceCode(); - const linebreaks = sourceCode.getText().match(/\r\n|[\r\n\u2028\u2029]/gu); - - /** @type {(node: TSESTree.Program) => void} */ - const checkIndent = (node) => { - const lines = sourceCode.getLines(); - const linesLen = lines.length; - - let totalLen = 0; - for (let i = 0; i < linesLen; i++) { - const lineNumber = i + 1; - const line = lines[i]; - const linebreaksLen = linebreaks && linebreaks[i] ? linebreaks[i].length : 1; - const lineLen = line.length + linebreaksLen; - const matches = /\S/.exec(line); - - if (matches && matches.index) { - const indentEnd = matches.index; - const whitespace = line.slice(0, indentEnd); - - if (!TAB_REGEX.test(whitespace)) { - totalLen += lineLen; - continue; - } - - context.report({ - messageId: "simpleIndentError", - node, - loc: { column: indentEnd, line: lineNumber }, - fix(fixer) { - const rangeStart = totalLen; - const rangeEnd = rangeStart + indentEnd; - - return fixer - .replaceTextRange([rangeStart, rangeEnd], whitespace.replace(TAB_REGEX, " ".repeat(TAB_SIZE))); - } - }); - } - - totalLen += lineLen; - } - }; - - return { - Program: checkIndent, - }; - }, -}); diff --git a/scripts/eslint/rules/type-operator-spacing.cjs b/scripts/eslint/rules/type-operator-spacing.cjs deleted file mode 100644 index 5d0fd8f1e9794..0000000000000 --- a/scripts/eslint/rules/type-operator-spacing.cjs +++ /dev/null @@ -1,43 +0,0 @@ -const { TSESTree, AST_TOKEN_TYPES } = require("@typescript-eslint/utils"); -const { createRule } = require("./utils.cjs"); - -module.exports = createRule({ - name: "type-operator-spacing", - meta: { - docs: { - description: ``, - }, - messages: { - typeOperatorSpacingError: `The '|' and '&' operators must be surrounded by spaces`, - }, - schema: [], - type: "suggestion", - }, - defaultOptions: [], - - create(context) { - const sourceCode = context.getSourceCode(); - const tokens = ["|", "&"]; - const text = sourceCode.getText(); - - /** @type {(node: TSESTree.TSIntersectionType | TSESTree.TSUnionType) => void} */ - const checkTypeOperatorSpacing = (node) => { - node.types.forEach(node => { - const token = sourceCode.getTokenBefore(node); - - if (!!token && token.type === AST_TOKEN_TYPES.Punctuator && tokens.indexOf(token.value) >= 0) { - const [start, end] = token.range; - - if (/\S/.test(text[start - 1]) || /\S/.test(text[end])) { - context.report({ messageId: "typeOperatorSpacingError", node: token }); - } - } - }); - }; - - return { - TSIntersectionType: checkTypeOperatorSpacing, - TSUnionType: checkTypeOperatorSpacing, - }; - }, -}); diff --git a/scripts/eslint/tests/argument-trivia.test.cjs b/scripts/eslint/tests/argument-trivia.test.cjs index 3e749bdf25512..932a2bbf1c5d5 100644 --- a/scripts/eslint/tests/argument-trivia.test.cjs +++ b/scripts/eslint/tests/argument-trivia.test.cjs @@ -77,10 +77,10 @@ const fn = (prop: boolean) => {}; fn(/* boolean arg */false); `, errors: [{ messageId: "argumentTriviaArgumentSpaceError" }], - output:` + output: ` const fn = (prop: boolean) => {}; fn(/* boolean arg */ false); - ` + `, }, ], }); diff --git a/scripts/eslint/tests/debug-assert.test.cjs b/scripts/eslint/tests/debug-assert.test.cjs index ae5961e41fc12..702017ff7afec 100644 --- a/scripts/eslint/tests/debug-assert.test.cjs +++ b/scripts/eslint/tests/debug-assert.test.cjs @@ -45,6 +45,6 @@ ruleTester.run("debug-assert", rule, { { messageId: "secondArgumentDebugAssertError" }, { messageId: "thirdArgumentDebugAssertError" }, ], - } + }, ], }); diff --git a/scripts/eslint/tests/no-double-space.test.cjs b/scripts/eslint/tests/no-double-space.test.cjs deleted file mode 100644 index b411fbe6ea85f..0000000000000 --- a/scripts/eslint/tests/no-double-space.test.cjs +++ /dev/null @@ -1,154 +0,0 @@ -const { RuleTester } = require("./support/RuleTester.cjs"); -const rule = require("../rules/no-double-space.cjs"); - -const ruleTester = new RuleTester({ - parser: require.resolve("@typescript-eslint/parser"), - parserOptions: { - warnOnUnsupportedTypeScriptVersion: false, - }, -}); - -ruleTester.run("no-double-space", rule, { - valid: [ - { - code: `const a = {};`, - }, - { - code: `function fn() {}`, - }, - { - code: `const a = " ";`, - }, - { - code: `// ^ ^`, - }, - { - code: `class Cl {}`, - }, - { - code: `// comment `, - }, - { - code: `/* comment */`, - }, - { - code: `" string ";`, - }, - { - code: `/ regexp /g;`, - }, - { - code: `const rgx = / regexp /g;`, - }, - { - code: "const str = ` string template`;", - }, - { - code: ` // comment`, - }, - { - code: ` /* comment */`, - }, - { - code: `// `, - }, - { - code: ` -const a = - 1; - `, - }, - { - code: ` -/** - * comment - */ - `, - }, - { - code: ` -// comment -// - comment -// - comment - `, - }, - { - code: ` -interface Props { - prop: string[]; // comment prop - propB: string[]; // comment propB -} - `, - }, - { - code: ` -/** - * Returns a JSON-encoded value of the type: string[] - * - * @param exclude A JSON encoded string[] containing the paths to exclude - * when enumerating the directory. - */ - `, - }, - { - code: ` -const obj = { - content: "function f() { 1; }", -}; - `, - }, - ], - - invalid: [ - { - code: `const a = {};`, - errors: [ - { messageId: "noDoubleSpaceError", line: 1, column: 6 }, - ], - }, - { - code: `function fn() {}`, - errors: [ - { messageId: "noDoubleSpaceError", line: 1, column: 9 }, - ], - }, - { - code: `class Cl {}`, - errors: [{ messageId: "noDoubleSpaceError", line: 1, column: 6 }], - }, - { - code: "const str = ` string template`;", - errors: [ - { messageId: "noDoubleSpaceError", line: 1, column: 12 }, - ], - }, - { - code: `/** comment */`, - errors: [ - { messageId: "noDoubleSpaceError", line: 1, column: 12 }, - ], - }, - { - code: `/** comment with many spaces */`, - errors: [ - { messageId: "noDoubleSpaceError", line: 1, column: 12 }, - ], - }, - { - code: `// comment with many spaces`, - errors: [ - { messageId: "noDoubleSpaceError", line: 1, column: 11 }, - ], - }, - { - code: ` -const a = 1; -const b = 2; -const c = 3; - `, - errors: [ - { messageId: "noDoubleSpaceError", line: 4, column: 10 }, - ], - }, - ], -}); diff --git a/scripts/eslint/tests/no-keywords.test.cjs b/scripts/eslint/tests/no-keywords.test.cjs index 3618329b68aba..731b05a9d1ffe 100644 --- a/scripts/eslint/tests/no-keywords.test.cjs +++ b/scripts/eslint/tests/no-keywords.test.cjs @@ -76,7 +76,7 @@ interface Foo { number: string; } `, - } + }, ], invalid: [ @@ -144,14 +144,14 @@ interface A { code: `let [number, string] = [3, ''];`, errors: [ { messageId: "noKeywordsError" }, - { messageId: "noKeywordsError" } + { messageId: "noKeywordsError" }, ], }, { code: `let { String, Boolean } = { String: 1, Boolean: false };`, errors: [ { messageId: "noKeywordsError" }, - { messageId: "noKeywordsError" } + { messageId: "noKeywordsError" }, ], }, ], diff --git a/scripts/eslint/tests/no-type-assertion-whitespace.test.cjs b/scripts/eslint/tests/no-type-assertion-whitespace.test.cjs deleted file mode 100644 index aa820094a0ee9..0000000000000 --- a/scripts/eslint/tests/no-type-assertion-whitespace.test.cjs +++ /dev/null @@ -1,39 +0,0 @@ -const { RuleTester } = require("./support/RuleTester.cjs"); -const rule = require("../rules/no-type-assertion-whitespace.cjs"); - -const ruleTester = new RuleTester({ - parserOptions: { - warnOnUnsupportedTypeScriptVersion: false, - }, - parser: require.resolve("@typescript-eslint/parser"), -}); - -ruleTester.run("no-type-assertion-whitespace", rule, { - valid: [ - { - code: `const a = 1`, - }, - { - code: `const s = (new Symbol(1, 'name'));`, - }, - ], - - invalid: [ - { - code: `const a = 1`, - errors: [{ messageId: "noTypeAssertionWhitespace", column: 19, line: 1 }], - }, - { - code: `const a = 1`, - errors: [{ messageId: "noTypeAssertionWhitespace", column: 19, line: 1 }], - }, - { - code: `const a = 1`, - errors: [{ messageId: "noTypeAssertionWhitespace", column: 19, line: 1 }], - }, - { - code: `const s = (new Symbol(1, 'name'));`, - errors: [{ messageId: "noTypeAssertionWhitespace", column: 17, line: 1 }], - }, - ], -}); diff --git a/scripts/eslint/tests/object-literal-surrounding-space.test.cjs b/scripts/eslint/tests/object-literal-surrounding-space.test.cjs deleted file mode 100644 index 7c697af531fb9..0000000000000 --- a/scripts/eslint/tests/object-literal-surrounding-space.test.cjs +++ /dev/null @@ -1,49 +0,0 @@ -const { RuleTester } = require("./support/RuleTester.cjs"); -const rule = require("../rules/object-literal-surrounding-space.cjs"); - -const ruleTester = new RuleTester({ - parserOptions: { - warnOnUnsupportedTypeScriptVersion: false, - }, - parser: require.resolve("@typescript-eslint/parser"), -}); - -ruleTester.run("object-literal-surrounding-space", rule, { - valid: [ - { - code: `const prop = {}`, - }, - { - code: `const prop = { }`, - }, - { - code: `const prop = { x: 1 }`, - }, - ], - - invalid: [ - { - code: `const prop = {x: 1}`, - errors: [ - { messageId: "leadingStringError" }, - { messageId: "trailingStringError" } - ], - }, - { - code: `const prop = { x: 1 }`, - errors: [{ messageId: "leadingExcessStringError" }], - }, - { - code: `const prop = { x: 1 }`, - errors: [{ messageId: "trailingExcessStringError" }], - }, - { - code: `const prop = { x: 1}`, - errors: [{ messageId: "trailingStringError" }], - }, - { - code: `const prop = {x: 1 }`, - errors: [{ messageId: "leadingStringError" }], - }, - ], -}); diff --git a/scripts/eslint/tests/simple-indent.test.cjs b/scripts/eslint/tests/simple-indent.test.cjs deleted file mode 100644 index 0e4d925c56091..0000000000000 --- a/scripts/eslint/tests/simple-indent.test.cjs +++ /dev/null @@ -1,333 +0,0 @@ -const { RuleTester } = require("./support/RuleTester.cjs"); -const rule = require("../rules/simple-indent.cjs"); - -const ruleTester = new RuleTester({ - parserOptions: { - warnOnUnsupportedTypeScriptVersion: false, - }, - parser: require.resolve("@typescript-eslint/parser"), -}); - -ruleTester.run("simple-indent", rule, { - valid: [ - { - code: ` -/** - * Comment - */ - ` - }, - { - code: ` -module TestModule { - var func = () => { - console.warn("hi"); - }; -} - `, - }, - { - code: ` -class TestClass { - private variable; - - testFunction() { - this.variable = 3; - } -} - `, - }, - { - code: ` -var obj = { - a: 1, - b: 2, - c: 3 -}; - `, - }, - { - code: ` -export enum TestEnum { - VALUE1, - VALUE2 -} - `, - }, - { - code: ` -switch (integerValue) { - case 1: - console.warn("1"); - break; - default: - console.warn("default"); - break; -} - `, - }, - { - code: ` -function loops() { - for (var i = 0; i < 1; ++i) { - console.warn(i); - } - - while (i < 1) { - console.warn(i); - } - - do { - console.warn(i); - } while (i < 1); - - if (i < 1) { - console.warn(i); - } else { - console.warn(i + 1); - } -} - `, - }, - ], - - invalid: [ - { - code: ` -module TestModule { -\tvar testVariable = 123; -} - `, - output: ` -module TestModule { - var testVariable = 123; -} - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - ], - }, - { - code: ` -function a() { -\t\tvar test = 123; -} - `, - output: ` -function a() { - var test = 123; -} - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 3 }, - ], - }, - { - code: ` -class TestClass { -\tprivate variable; - -\ttestFunction() { -\t\tthis.variable = 3; -\t} -} - `, - output: ` -class TestClass { - private variable; - - testFunction() { - this.variable = 3; - } -} - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - { messageId: "simpleIndentError", line: 5, column: 2 }, - { messageId: "simpleIndentError", line: 6, column: 3 }, - { messageId: "simpleIndentError", line: 7, column: 2 }, - ], - }, - { - code: ` -var obj = { -\ta: 1, -\tb: 2, -\tc: 3 -}; - `, - output: ` -var obj = { - a: 1, - b: 2, - c: 3 -}; - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - { messageId: "simpleIndentError", line: 4, column: 2 }, - { messageId: "simpleIndentError", line: 5, column: 2 }, - ] - }, - { - code: ` -enum TestEnum { -\tVALUE1, - VALUE2 -} - `, - output: ` -enum TestEnum { - VALUE1, - VALUE2 -} - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - ], - }, - { - code: ` -switch (integerValue) { -\tcase 0: -\t\tconsole.warn("1"); -\t\tbreak; - case 1: - console.warn("1"); - break; -\tdefault: -\t\tconsole.log("2"); -\t\tbreak; -} - `, - output: ` -switch (integerValue) { - case 0: - console.warn("1"); - break; - case 1: - console.warn("1"); - break; - default: - console.log("2"); - break; -} - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - { messageId: "simpleIndentError", line: 4, column: 3 }, - { messageId: "simpleIndentError", line: 5, column: 3 }, - { messageId: "simpleIndentError", line: 9, column: 2 }, - { messageId: "simpleIndentError", line: 10, column: 3 }, - { messageId: "simpleIndentError", line: 11, column: 3 }, - ] - }, - { - code: ` -for (var i = 0; i < 1; ++i) { -\tconsole.warn("123"); -} - `, - output: ` -for (var i = 0; i < 1; ++i) { - console.warn("123"); -} - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - ], - }, - { - code: ` -while (i < 1) { -\tconsole.warn("123"); -} - `, - output: ` -while (i < 1) { - console.warn("123"); -} - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - ] - }, - { - code: ` -do { -\tconsole.warn("123"); -} while (i < 1); - `, - output: ` -do { - console.warn("123"); -} while (i < 1); - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - ] - }, - { - code: ` -if (i < 1) { -\tconsole.warn("123"); -} - `, - output: ` -if (i < 1) { - console.warn("123"); -} - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - ] - }, - { - code: ` -var arr = [ -\t1, - 2 -]; - `, - output: ` -var arr = [ - 1, - 2 -]; - `, - errors: [ - { messageId: "simpleIndentError", line: 3, column: 2 }, - ] - }, - { - code: ` -var arr2 = [ - { -\t\ta: 1, - b: 2 - }, - { - a: 3, -\t\tb: 4 - } -]; - `, - output: ` -var arr2 = [ - { - a: 1, - b: 2 - }, - { - a: 3, - b: 4 - } -]; - `, - errors: [ - { messageId: "simpleIndentError", line: 4, column: 3 }, - { messageId: "simpleIndentError", line: 9, column: 3 }, - ] - } - ], -}); diff --git a/scripts/eslint/tests/type-operator-spacing.test.cjs b/scripts/eslint/tests/type-operator-spacing.test.cjs deleted file mode 100644 index 3341348828e1a..0000000000000 --- a/scripts/eslint/tests/type-operator-spacing.test.cjs +++ /dev/null @@ -1,45 +0,0 @@ -const { RuleTester } = require("./support/RuleTester.cjs"); -const rule = require("../rules/type-operator-spacing.cjs"); - -const ruleTester = new RuleTester({ - parserOptions: { - warnOnUnsupportedTypeScriptVersion: false, - }, - parser: require.resolve("@typescript-eslint/parser"), -}); - -ruleTester.run("type-operator-spacing", rule, { - valid: [ - { - code: `type T = string | number`, - }, - { - code: `type T = string & number`, - }, - { - code: `function fn(): string | number {}`, - }, - { - code: `function fn(): string & number {}`, - }, - ], - - invalid: [ - { - code: `type T = string|number`, - errors: [{ messageId: "typeOperatorSpacingError" }], - }, - { - code: `type T = string&number`, - errors: [{ messageId: "typeOperatorSpacingError" }], - }, - { - code: `function fn(): string|number {}`, - errors: [{ messageId: "typeOperatorSpacingError" }], - }, - { - code: `function fn(): string&number {}`, - errors: [{ messageId: "typeOperatorSpacingError" }], - }, - ], -}); diff --git a/scripts/failed-tests.cjs b/scripts/failed-tests.cjs index b669db47c0313..c214f6eea90b1 100644 --- a/scripts/failed-tests.cjs +++ b/scripts/failed-tests.cjs @@ -76,7 +76,7 @@ class FailedTestsReporter extends Mocha.reporters.Base { */ static writeFailures(file, passes, failures, keepFailed, done) { const failingTests = new Set(fs.existsSync(file) ? readTests() : undefined); - const possiblyPassingSuites = /**@type {Set}*/(new Set()); + const possiblyPassingSuites = /**@type {Set}*/ (new Set()); // Remove tests that are now passing and track suites that are now // possibly passing. @@ -138,7 +138,7 @@ class FailedTestsReporter extends Mocha.reporters.Base { done(failures, fn) { assert(this.reporterOptions); assert(this.reporterOptions.file); - FailedTestsReporter.writeFailures(this.reporterOptions.file, this.passes, this.failures, this.reporterOptions.keepFailed || this.stats.tests === 0, (err) => { + FailedTestsReporter.writeFailures(this.reporterOptions.file, this.passes, this.failures, this.reporterOptions.keepFailed || this.stats.tests === 0, err => { const reporter = this.reporter; if (reporter && reporter.done) { reporter.done(failures, fn); diff --git a/scripts/find-unused-diganostic-messages.mjs b/scripts/find-unused-diganostic-messages.mjs index ad116ef5a5325..b4aff5913b437 100644 --- a/scripts/find-unused-diganostic-messages.mjs +++ b/scripts/find-unused-diganostic-messages.mjs @@ -1,9 +1,15 @@ // This file requires a modern version of node 14+, and grep to be available. // node scripts/find-unused-diagnostic-messages.mjs -import { execSync } from "child_process"; -import { readFileSync } from "fs"; -import { EOL } from "os"; +import { + execSync, +} from "child_process"; +import { + readFileSync, +} from "fs"; +import { + EOL, +} from "os"; const diags = readFileSync("src/compiler/diagnosticInformationMap.generated.ts", "utf8"); const startOfDiags = diags.split("export const Diagnostics")[1]; diff --git a/scripts/generateLocalizedDiagnosticMessages.mjs b/scripts/generateLocalizedDiagnosticMessages.mjs index e8711a0ca1c43..72b3e7febcf6f 100644 --- a/scripts/generateLocalizedDiagnosticMessages.mjs +++ b/scripts/generateLocalizedDiagnosticMessages.mjs @@ -1,4 +1,6 @@ -import { XMLParser } from "fast-xml-parser"; +import { + XMLParser, +} from "fast-xml-parser"; import fs from "fs"; import path from "path"; @@ -50,8 +52,7 @@ async function main() { const inputFilePath = path.join(inputPath, name, "diagnosticMessages", "diagnosticMessages.generated.json.lcl"); const contents = await fs.promises.readFile(inputFilePath); /** @type {ParsedLCL} */ - // eslint-disable-next-line local/object-literal-surrounding-space - const result = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "$_"}).parse(contents); + const result = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "$_" }).parse(contents); if (!result || !result.LCX || !result.LCX.$_TgtCul) { console.error("Unexpected XML file structure. Expected to find result.LCX.$_TgtCul."); process.exit(1); @@ -135,8 +136,8 @@ async function main() { path.join(outputPath, "enu", "diagnosticMessages.generated.json.lcg"), getLCGFileXML( Object.entries(JSON.parse(contents)) - .sort((a, b) => a[0] > b[0] ? 1 : -1) // lcg sorted by property keys - .reduce((s, [key, value]) => s + getItemXML(key, value), "") + .sort((a, b) => a[0] > b[0] ? 1 : -1) // lcg sorted by property keys + .reduce((s, [key, value]) => s + getItemXML(key, value), ""), ), ); return; diff --git a/scripts/link-hooks.mjs b/scripts/link-hooks.mjs index c54456fcacf66..6d5594b49062b 100644 --- a/scripts/link-hooks.mjs +++ b/scripts/link-hooks.mjs @@ -2,16 +2,18 @@ import fs from "fs"; import path from "path"; import url from "url"; -import { findUpRoot } from "./build/findUpDir.mjs"; +import { + findUpRoot, +} from "./build/findUpDir.mjs"; const __filename = url.fileURLToPath(new URL(import.meta.url)); const __dirname = path.dirname(__filename); const hooks = [ - "post-checkout" + "post-checkout", ]; -hooks.forEach((hook) => { +hooks.forEach(hook => { const hookInSourceControl = path.resolve(__dirname, "hooks", hook); if (fs.existsSync(hookInSourceControl)) { diff --git a/scripts/open-cherry-pick-pr.mjs b/scripts/open-cherry-pick-pr.mjs index 6b9fc9b1ab2fa..46c166c9c5f03 100644 --- a/scripts/open-cherry-pick-pr.mjs +++ b/scripts/open-cherry-pick-pr.mjs @@ -1,9 +1,13 @@ -import { Octokit } from "@octokit/rest"; +import { + Octokit, +} from "@octokit/rest"; import fs from "fs"; import path from "path"; import url from "url"; -import { runSequence } from "./run-sequence.mjs"; +import { + runSequence, +} from "./run-sequence.mjs"; const __filename = url.fileURLToPath(new URL(import.meta.url)); const __dirname = path.dirname(__filename); @@ -22,30 +26,30 @@ async function main() { throw new Error("Source issue not specified"); } const currentSha = runSequence([ - ["git", ["rev-parse", "HEAD"]] + ["git", ["rev-parse", "HEAD"]], ]); const currentAuthor = runSequence([ - ["git", ["log", "-1", `--pretty="%aN <%aE>"`]] + ["git", ["log", "-1", `--pretty="%aN <%aE>"`]], ]); const gh = new Octokit({ - auth: process.argv[2] + auth: process.argv[2], }); const inputPR = (await gh.pulls.get({ pull_number: +process.env.SOURCE_ISSUE, owner: "microsoft", repo: "TypeScript" })).data; let remoteName = "origin"; if (inputPR.base.repo.git_url !== `git:github.com/microsoft/TypeScript` && inputPR.base.repo.git_url !== `git://github.com/microsoft/TypeScript`) { runSequence([ - ["git", ["remote", "add", "nonlocal", inputPR.base.repo.git_url.replace(/^git:(?:\/\/)?/, "https://")]] + ["git", ["remote", "add", "nonlocal", inputPR.base.repo.git_url.replace(/^git:(?:\/\/)?/, "https://")]], ]); remoteName = "nonlocal"; } const baseBranchName = inputPR.base.ref; runSequence([ - ["git", ["fetch", remoteName, baseBranchName]] + ["git", ["fetch", remoteName, baseBranchName]], ]); let logText = runSequence([ - ["git", ["log", `${remoteName}/${baseBranchName}..${currentSha.trim()}`, `--pretty="%h %s%n%b"`, "--reverse"]] + ["git", ["log", `${remoteName}/${baseBranchName}..${currentSha.trim()}`, `--pretty="%h %s%n%b"`, "--reverse"]], ]); logText = `Cherry-pick PR #${process.env.SOURCE_ISSUE} into ${process.env.TARGET_BRANCH} @@ -55,15 +59,15 @@ ${logText.trim()}`; const mergebase = runSequence([["git", ["merge-base", `${remoteName}/${baseBranchName}`, currentSha]]]).trim(); runSequence([ ["git", ["checkout", "-b", "temp-branch"]], - ["git", ["reset", mergebase, "--soft"]] + ["git", ["reset", mergebase, "--soft"]], ]); fs.writeFileSync(logpath, logText); runSequence([ - ["git", ["commit", "-F", logpath, `--author="${currentAuthor.trim()}"`]] + ["git", ["commit", "-F", logpath, `--author="${currentAuthor.trim()}"`]], ]); fs.unlinkSync(logpath); const squashSha = runSequence([ - ["git", ["rev-parse", "HEAD"]] + ["git", ["rev-parse", "HEAD"]], ]); runSequence([ ["git", ["checkout", process.env.TARGET_BRANCH]], // checkout the target branch @@ -74,12 +78,12 @@ ${logText.trim()}`; runSequence([ ["node", ["./node_modules/hereby/dist/cli.js", "LKG"]], ["git", ["add", "lib"]], - ["git", ["commit", "-m", `"Update LKG"`]] + ["git", ["commit", "-m", `"Update LKG"`]], ]); } runSequence([ ["git", ["remote", "add", "fork", remoteUrl]], // Add the remote fork - ["git", ["push", "--set-upstream", "fork", branchName, "-f"]] // push the branch + ["git", ["push", "--set-upstream", "fork", branchName, "-f"]], // push the branch ]); const r = await gh.pulls.create({ @@ -89,8 +93,7 @@ ${logText.trim()}`; title: `🤖 Pick PR #${process.env.SOURCE_ISSUE} (${inputPR.title.substring(0, 35)}${inputPR.title.length > 35 ? "..." : ""}) into ${process.env.TARGET_BRANCH}`, head: `${userName}:${branchName}`, base: process.env.TARGET_BRANCH, - body: - `This cherry-pick was triggered by a request on https://github.com/Microsoft/TypeScript/pull/${process.env.SOURCE_ISSUE} + body: `This cherry-pick was triggered by a request on https://github.com/Microsoft/TypeScript/pull/${process.env.SOURCE_ISSUE} Please review the diff and merge if no changes are unexpected.${produceLKG ? ` An LKG update commit is included separately from the base change.` : ""} You can view the cherry-pick log [here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary). @@ -103,7 +106,7 @@ cc ${reviewers.map(r => "@" + r).join(" ")}`, issue_number: +process.env.SOURCE_ISSUE, owner: "Microsoft", repo: "TypeScript", - body: `Hey @${process.env.REQUESTING_USER}, I've opened #${num} for you.` + body: `Hey @${process.env.REQUESTING_USER}, I've opened #${num} for you.`, }); } @@ -112,13 +115,13 @@ main().catch(async e => { process.exitCode = 1; if (process.env.SOURCE_ISSUE) { const gh = new Octokit({ - auth: process.argv[2] + auth: process.argv[2], }); await gh.issues.createComment({ issue_number: +process.env.SOURCE_ISSUE, owner: "Microsoft", repo: "TypeScript", - body: `Hey @${process.env.REQUESTING_USER}, I couldn't open a PR with the cherry-pick. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary)). You may need to squash and pick this PR into ${process.env.TARGET_BRANCH} manually.` + body: `Hey @${process.env.REQUESTING_USER}, I couldn't open a PR with the cherry-pick. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary)). You may need to squash and pick this PR into ${process.env.TARGET_BRANCH} manually.`, }); } }); diff --git a/scripts/open-user-pr.mjs b/scripts/open-user-pr.mjs index f79e56f0fb71d..ef2509a075c44 100644 --- a/scripts/open-user-pr.mjs +++ b/scripts/open-user-pr.mjs @@ -1,6 +1,10 @@ -import { Octokit } from "@octokit/rest"; +import { + Octokit, +} from "@octokit/rest"; -import { runSequence } from "./run-sequence.mjs"; +import { + runSequence, +} from "./run-sequence.mjs"; const userName = process.env.GH_USERNAME || "typescript-bot"; const reviewers = process.env.REQUESTING_USER ? [process.env.REQUESTING_USER] : ["weswigham", "sandersn", "RyanCavanaugh"]; @@ -20,11 +24,11 @@ runSequence([ ["git", ["checkout", "-b", branchName]], // create a branch ["git", ["add", "."]], // Add all changes ["git", ["commit", "-m", `"Update user baselines${+(process.env.SOURCE_ISSUE ?? 0) === 33716 ? " +cc @sandersn" : ""}"`]], // Commit all changes (ping nathan if we would post to CI thread) - ["git", ["push", "--set-upstream", "fork", branchName, "-f"]] // push the branch + ["git", ["push", "--set-upstream", "fork", branchName, "-f"]], // push the branch ]); const gh = new Octokit({ - auth: process.argv[2] + auth: process.argv[2], }); const prOwner = branchName === masterBranchname ? "microsoft" : userName; gh.pulls.create({ @@ -34,8 +38,7 @@ gh.pulls.create({ title: `🤖 User test baselines have changed` + (process.env.TARGET_BRANCH ? ` for ${process.env.TARGET_BRANCH}` : ""), head: `${userName}:${branchName}`, base: branchName === masterBranchname ? "main" : masterBranchname, - body: -`${process.env.SOURCE_ISSUE ? `This test run was triggerd by a request on https://github.com/Microsoft/TypeScript/pull/${process.env.SOURCE_ISSUE} `+"\n" : ""}Please review the diff and merge if no changes are unexpected. + body: `${process.env.SOURCE_ISSUE ? `This test run was triggerd by a request on https://github.com/Microsoft/TypeScript/pull/${process.env.SOURCE_ISSUE} ` + "\n" : ""}Please review the diff and merge if no changes are unexpected. You can view the build log [here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary). cc ${reviewers.map(r => "@" + r).join(" ")}`, @@ -55,7 +58,7 @@ cc ${reviewers.map(r => "@" + r).join(" ")}`, issue_number: +process.env.SOURCE_ISSUE, owner: "microsoft", repo: "TypeScript", - body: `The user suite test run you requested has finished and _failed_. I've opened a [PR with the baseline diff from master](${r.data.html_url}).` + body: `The user suite test run you requested has finished and _failed_. I've opened a [PR with the baseline diff from master](${r.data.html_url}).`, }); } }).then(() => { diff --git a/scripts/perf-result-post.mjs b/scripts/perf-result-post.mjs index 77ce392688828..1be50f172ab1b 100644 --- a/scripts/perf-result-post.mjs +++ b/scripts/perf-result-post.mjs @@ -1,10 +1,11 @@ -import { Octokit } from "@octokit/rest"; +import { + Octokit, +} from "@octokit/rest"; import assert from "assert"; import ado from "azure-devops-node-api"; import fs from "fs"; import fetch from "node-fetch"; - async function main() { const source = process.env.SOURCE_ISSUE; if (!source) throw new Error("SOURCE_ISSUE environment variable not set."); @@ -52,7 +53,7 @@ async function main() { issue_number: +source, owner: "Microsoft", repo: "TypeScript", - body: `@${requester}\nThe results of the perf run you requested are in!\n
Here they are:

\n${outputTableText}\n

${benchmarkText}
` + body: `@${requester}\nThe results of the perf run you requested are in!\n
Here they are:

\n${outputTableText}\n

${benchmarkText}
`, }); console.log(`Results posted!`); @@ -60,14 +61,14 @@ async function main() { const comment = await gh.issues.getComment({ owner: "Microsoft", repo: "TypeScript", - comment_id: +postedComment + comment_id: +postedComment, }); const newBody = `${comment.data.body}\n\nUpdate: [The results are in!](${newCommentUrl})`; await gh.issues.updateComment({ owner: "Microsoft", repo: "TypeScript", comment_id: +postedComment, - body: newBody + body: newBody, }); } catch (e) { @@ -76,7 +77,7 @@ async function main() { issue_number: +source, owner: "Microsoft", repo: "TypeScript", - body: `Hey @${requester}, something went wrong when publishing results. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${buildId}&_a=summary)).` + body: `Hey @${requester}, something went wrong when publishing results. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${buildId}&_a=summary)).`, }); } } diff --git a/scripts/post-vsts-artifact-comment.mjs b/scripts/post-vsts-artifact-comment.mjs index 8c345c5842798..c5015ac9bcb0f 100644 --- a/scripts/post-vsts-artifact-comment.mjs +++ b/scripts/post-vsts-artifact-comment.mjs @@ -1,4 +1,6 @@ -import { Octokit } from "@octokit/rest"; +import { + Octokit, +} from "@octokit/rest"; import assert from "assert"; import ado from "azure-devops-node-api"; import fetch from "node-fetch"; @@ -23,7 +25,7 @@ async function main() { tgzUrl.search = `artifactName=tgz&fileId=${file.blob.id}&fileName=${file.path}`; const link = "" + tgzUrl; const gh = new Octokit({ - auth: process.argv[2] + auth: process.argv[2], }); // Please keep the strings "an installable tgz" and "packed" in this message, as well as the devDependencies section, @@ -42,7 +44,7 @@ async function main() { } \`\`\` and then running \`npm install\`. -` +`, }); // Temporarily disable until we get access controls set up right @@ -55,13 +57,13 @@ main().catch(async e => { process.exitCode = 1; if (process.env.SOURCE_ISSUE) { const gh = new Octokit({ - auth: process.argv[2] + auth: process.argv[2], }); await gh.issues.createComment({ issue_number: +process.env.SOURCE_ISSUE, owner: "Microsoft", repo: "TypeScript", - body: `Hey @${process.env.REQUESTING_USER}, something went wrong when looking for the build artifact. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary)).` + body: `Hey @${process.env.REQUESTING_USER}, something went wrong when looking for the build artifact. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary)).`, }); } }); diff --git a/scripts/processDiagnosticMessages.mjs b/scripts/processDiagnosticMessages.mjs index da207ec7ec3b3..069bd95aa4308 100644 --- a/scripts/processDiagnosticMessages.mjs +++ b/scripts/processDiagnosticMessages.mjs @@ -24,7 +24,7 @@ async function main() { * @param {string} fileName * @param {string} contents */ - async function writeFile(fileName, contents) { + async function writeFile(fileName, contents) { const filePath = path.join(path.dirname(inputFilePath), fileName); try { const existingContents = await fs.promises.readFile(filePath, "utf-8"); @@ -86,7 +86,7 @@ function buildInfoFileOutput(messageTable, inputFilePathRel) { "// ", `// generated from '${inputFilePathRel}'`, "", - "import { DiagnosticCategory, DiagnosticMessage } from \"./types\";", + 'import { DiagnosticCategory, DiagnosticMessage } from "./types";', "", "function diag(code: number, category: DiagnosticCategory, key: string, message: string, reportsUnnecessary?: {}, elidedInCompatabilityPyramid?: boolean, reportsDeprecated?: {}): DiagnosticMessage {", " return { code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated };", @@ -126,7 +126,6 @@ function buildDiagnosticMessageOutput(messageTable) { } /** - * * @param {string} name * @param {number} code * @returns {string} diff --git a/scripts/produceLKG.mjs b/scripts/produceLKG.mjs index 8db2e831d7828..f5dc7a5c27c22 100644 --- a/scripts/produceLKG.mjs +++ b/scripts/produceLKG.mjs @@ -3,7 +3,9 @@ import glob from "glob"; import path from "path"; import url from "url"; -import { localizationDirectories } from "./build/localization.mjs"; +import { + localizationDirectories, +} from "./build/localization.mjs"; const __filename = url.fileURLToPath(new URL(import.meta.url)); const __dirname = path.dirname(__filename); diff --git a/scripts/regenerate-unicode-identifier-parts.mjs b/scripts/regenerate-unicode-identifier-parts.mjs index 60730b77e2509..e993a40e7a8d9 100644 --- a/scripts/regenerate-unicode-identifier-parts.mjs +++ b/scripts/regenerate-unicode-identifier-parts.mjs @@ -1,4 +1,3 @@ - const MAX_UNICODE_CODEPOINT = 0x10FFFF; /** @type {(c: string) => boolean} */ const isStart = c => /[\p{ID_Start}\u{2118}\u{212E}\u{309B}\u{309C}]/u.test(c); // Other_ID_Start explicitly included for back compat - see http://www.unicode.org/reports/tr31/#Introduction diff --git a/scripts/request-pr-review.mjs b/scripts/request-pr-review.mjs index 51c9e90e786a6..ef5a69808deed 100644 --- a/scripts/request-pr-review.mjs +++ b/scripts/request-pr-review.mjs @@ -1,4 +1,6 @@ -import { Octokit } from "@octokit/rest"; +import { + Octokit, +} from "@octokit/rest"; import minimist from "minimist"; const options = minimist(process.argv.slice(2), { @@ -7,15 +9,15 @@ const options = minimist(process.argv.slice(2), { alias: { pr: "pull", h: "help", - ["?"]: "help" + ["?"]: "help", }, default: { token: process.env.GH_TOKEN, pull: process.env.GH_PULL_NUMBER, reviewer: process.env.REQUESTED_REVIEWER, owner: "microsoft", - repo: "TypeScript" - } + repo: "TypeScript", + }, }); if (options.help) { diff --git a/scripts/update-experimental-branches.mjs b/scripts/update-experimental-branches.mjs index 3251d8a0a7d0e..0b1fa533966fc 100644 --- a/scripts/update-experimental-branches.mjs +++ b/scripts/update-experimental-branches.mjs @@ -1,6 +1,10 @@ -import { Octokit } from "@octokit/rest"; +import { + Octokit, +} from "@octokit/rest"; -import { runSequence } from "./run-sequence.mjs"; +import { + runSequence, +} from "./run-sequence.mjs"; // The first is used by bot-based kickoffs, the second by automatic triggers const triggeredPR = process.env.SOURCE_ISSUE || process.env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER; @@ -13,7 +17,7 @@ const triggeredPR = process.env.SOURCE_ISSUE || process.env.SYSTEM_PULLREQUEST_P */ async function main() { const gh = new Octokit({ - auth: process.argv[2] + auth: process.argv[2], }); const prnums = (await gh.issues.listForRepo({ labels: "typescript@experimental", @@ -50,7 +54,7 @@ async function main() { owner: "Microsoft", repo: "TypeScript", issue_number: num, - body: `This PR is configured as an experiment, and currently has rebase conflicts with main - please rebase onto main and fix the conflicts.` + body: `This PR is configured as an experiment, and currently has rebase conflicts with main - please rebase onto main and fix the conflicts.`, }); } throw new Error(`Rebase conflict detected in PR ${num} with main`); // A PR is currently in conflict, give up @@ -61,7 +65,6 @@ async function main() { ["git", ["rebase", "main"]], ["git", ["push", "-f", "-u", "fork", `${num}`]], // Keep a rebased copy of this branch in our fork ]); - } else { throw new Error(`Invalid PR number: ${numRaw}`); @@ -83,7 +86,7 @@ async function main() { ]); // Simulate the merge and abort if there are conflicts const mergeTree = runSequence([ - ["git", ["merge-tree", mergeBase.trim(), branch, "experimental"]] + ["git", ["merge-tree", mergeBase.trim(), branch, "experimental"]], ]); if (mergeTree.indexOf(`===${"="}===`) >= 0) { // 7 equals is the center of the merge conflict marker throw new Error(`Merge conflict detected involving PR ${branch} with other experiment`); diff --git a/src/cancellationToken/cancellationToken.ts b/src/cancellationToken/cancellationToken.ts index 7f1b3998210e1..8ea543e01d473 100644 --- a/src/cancellationToken/cancellationToken.ts +++ b/src/cancellationToken/cancellationToken.ts @@ -29,7 +29,7 @@ function createCancellationToken(args: string[]): ServerCancellationToken { return { isCancellationRequested: () => false, setRequest: (_requestId: number): void => void 0, - resetRequest: (_requestId: number): void => void 0 + resetRequest: (_requestId: number): void => void 0, }; } // cancellationPipeName is a string without '*' inside that can optionally end with '*' @@ -55,14 +55,14 @@ function createCancellationToken(args: string[]): ServerCancellationToken { throw new Error(`Mismatched request id, expected ${currentRequestId}, actual ${requestId}`); } perRequestPipeName = undefined; - } + }, }; } else { return { isCancellationRequested: () => pipeExists(cancellationPipeName!), // TODO: GH#18217 setRequest: (_requestId: number): void => void 0, - resetRequest: (_requestId: number): void => void 0 + resetRequest: (_requestId: number): void => void 0, }; } } diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index cefe7b9c88797..38127a8d62075 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -313,7 +313,7 @@ import { unusedLabelIsError, VariableDeclaration, WhileStatement, - WithStatement + WithStatement, } from "./_namespaces/ts"; import * as performance from "./_namespaces/ts.performance"; @@ -321,7 +321,7 @@ import * as performance from "./_namespaces/ts.performance"; export const enum ModuleInstanceState { NonInstantiated = 0, Instantiated = 1, - ConstEnumOnly = 2 + ConstEnumOnly = 2, } interface ActiveLabel { @@ -835,8 +835,10 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // Error on multiple export default in the following case: // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) - if (symbol.declarations && symbol.declarations.length && - (node.kind === SyntaxKind.ExportAssignment && !(node as ExportAssignment).isExportEquals)) { + if ( + symbol.declarations && symbol.declarations.length && + (node.kind === SyntaxKind.ExportAssignment && !(node as ExportAssignment).isExportEquals) + ) { message = Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName = false; multipleDefaultExports = true; @@ -855,7 +857,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { const decl = getNameOfDeclaration(declaration) || declaration; const diag = messageNeedsName ? createDiagnosticForNode(decl, message, getDisplayName(declaration)) : createDiagnosticForNode(decl, message); file.bindDiagnostics.push( - multipleDefaultExports ? addRelatedInfo(diag, createDiagnosticForNode(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag + multipleDefaultExports ? addRelatedInfo(diag, createDiagnosticForNode(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag, ); if (multipleDefaultExports) { relatedInformation.push(createDiagnosticForNode(decl, Diagnostics.The_first_export_default_is_here)); @@ -996,12 +998,12 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { const saveExceptionTarget = currentExceptionTarget; const saveActiveLabelList = activeLabelList; const saveHasExplicitReturn = hasExplicitReturn; - const isImmediatelyInvoked = - (containerFlags & ContainerFlags.IsFunctionExpression && - !hasSyntacticModifier(node, ModifierFlags.Async) && - !(node as FunctionLikeDeclaration).asteriskToken && - !!getImmediatelyInvokedFunctionExpression(node)) || - node.kind === SyntaxKind.ClassStaticBlockDeclaration; + const isImmediatelyInvoked = ( + containerFlags & ContainerFlags.IsFunctionExpression && + !hasSyntacticModifier(node, ModifierFlags.Async) && + !(node as FunctionLikeDeclaration).asteriskToken && + !!getImmediatelyInvokedFunctionExpression(node) + ) || node.kind === SyntaxKind.ClassStaticBlockDeclaration; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isImmediatelyInvoked) { @@ -1252,8 +1254,10 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } } } - if (expr.expression.kind === SyntaxKind.PropertyAccessExpression && - containsNarrowableReference((expr.expression as PropertyAccessExpression).expression)) { + if ( + expr.expression.kind === SyntaxKind.PropertyAccessExpression && + containsNarrowableReference((expr.expression as PropertyAccessExpression).expression) + ) { return true; } return false; @@ -1332,9 +1336,11 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { if (!expression) { return flags & FlowFlags.TrueCondition ? antecedent : unreachableFlow; } - if ((expression.kind === SyntaxKind.TrueKeyword && flags & FlowFlags.FalseCondition || - expression.kind === SyntaxKind.FalseKeyword && flags & FlowFlags.TrueCondition) && - !isExpressionOfOptionalChainRoot(expression) && !isNullishCoalesce(expression.parent)) { + if ( + (expression.kind === SyntaxKind.TrueKeyword && flags & FlowFlags.FalseCondition || + expression.kind === SyntaxKind.FalseKeyword && flags & FlowFlags.TrueCondition) && + !isExpressionOfOptionalChainRoot(expression) && !isNullishCoalesce(expression.parent) + ) { return unreachableFlow; } if (!isNarrowingExpression(expression)) { @@ -1407,8 +1413,10 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } function isTopLevelLogicalExpression(node: Node): boolean { - while (isParenthesizedExpression(node.parent) || - isPrefixUnaryExpression(node.parent) && node.parent.operator === SyntaxKind.ExclamationToken) { + while ( + isParenthesizedExpression(node.parent) || + isPrefixUnaryExpression(node.parent) && node.parent.operator === SyntaxKind.ExclamationToken + ) { node = node.parent; } return !isStatementCondition(node) && @@ -1724,7 +1732,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { name: node.label.escapedText, breakTarget: postStatementLabel, continueTarget: undefined, - referenced: false + referenced: false, }; bind(node.label); bind(node.statement); @@ -1868,7 +1876,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { stackIndex: 0, skip: false, inStrictModeStack: [undefined], - parentStack: [undefined] + parentStack: [undefined], }; } // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions @@ -2291,9 +2299,11 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { function declareModuleSymbol(node: ModuleDeclaration): ModuleInstanceState { const state = getModuleInstanceState(node); const instantiated = state !== ModuleInstanceState.NonInstantiated; - declareSymbolAndAddToSymbolTable(node, + declareSymbolAndAddToSymbolTable( + node, instantiated ? SymbolFlags.ValueModule : SymbolFlags.NamespaceModule, - instantiated ? SymbolFlags.ValueModuleExcludes : SymbolFlags.NamespaceModuleExcludes); + instantiated ? SymbolFlags.ValueModuleExcludes : SymbolFlags.NamespaceModuleExcludes, + ); return state; } @@ -2376,8 +2386,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C const isTopLevel = isTopLevelNamespaceAssignment(declName.parent); if (isTopLevel) { - bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, - !!findAncestor(declName, d => isPropertyAccessExpression(d) && d.name.escapedText === "prototype"), /*containerIsClass*/ false); + bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!findAncestor(declName, d => isPropertyAccessExpression(d) && d.name.escapedText === "prototype"), /*containerIsClass*/ false); const oldContainer = container; switch (getAssignmentDeclarationPropertyAccessKind(declName.parent)) { case AssignmentDeclarationKind.ExportsProperty: @@ -2429,39 +2438,35 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // [Yield] or [Await] contexts, respectively. function checkContextualIdentifier(node: Identifier) { // Report error only if there are no parse errors in file - if (!file.parseDiagnostics.length && + if ( + !file.parseDiagnostics.length && !(node.flags & NodeFlags.Ambient) && !(node.flags & NodeFlags.JSDoc) && - !isIdentifierName(node)) { - + !isIdentifierName(node) + ) { // strict mode identifiers const originalKeywordKind = identifierToKeywordKind(node); if (originalKeywordKind === undefined) { return; } - if (inStrictMode && + if ( + inStrictMode && originalKeywordKind >= SyntaxKind.FirstFutureReservedWord && - originalKeywordKind <= SyntaxKind.LastFutureReservedWord) { - file.bindDiagnostics.push(createDiagnosticForNode(node, - getStrictModeIdentifierMessage(node), declarationNameToString(node))); + originalKeywordKind <= SyntaxKind.LastFutureReservedWord + ) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), declarationNameToString(node))); } else if (originalKeywordKind === SyntaxKind.AwaitKeyword) { if (isExternalModule(file) && isInTopLevelContext(node)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, - Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, - declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, declarationNameToString(node))); } else if (node.flags & NodeFlags.AwaitContext) { - file.bindDiagnostics.push(createDiagnosticForNode(node, - Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, - declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); } } else if (originalKeywordKind === SyntaxKind.YieldKeyword && node.flags & NodeFlags.YieldContext) { - file.bindDiagnostics.push(createDiagnosticForNode(node, - Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, - declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, declarationNameToString(node))); } } } @@ -2486,8 +2491,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { if (node.escapedText === "#constructor") { // Report error only if there are no parse errors in file if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(createDiagnosticForNode(node, - Diagnostics.constructor_is_a_reserved_word, declarationNameToString(node))); + file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.constructor_is_a_reserved_word, declarationNameToString(node))); } } } @@ -2529,8 +2533,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. const span = getErrorSpanForNode(file, name); - file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, - getStrictModeEvalOrArgumentsMessage(contextNode), idText(identifier))); + file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), idText(identifier))); } } } @@ -2573,14 +2576,15 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { function checkStrictModeFunctionDeclaration(node: FunctionDeclaration) { if (languageVersion < ScriptTarget.ES2015) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== SyntaxKind.SourceFile && + if ( + blockScopeContainer.kind !== SyntaxKind.SourceFile && blockScopeContainer.kind !== SyntaxKind.ModuleDeclaration && - !isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer)) { + !isFunctionLikeOrClassStaticBlockDeclaration(blockScopeContainer) + ) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. const errorSpan = getErrorSpanForNode(file, node); - file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length, - getStrictModeBlockScopeFunctionDeclarationMessage(node))); + file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); } } } @@ -2781,12 +2785,13 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { if (isSpecialPropertyDeclaration(expr)) { bindSpecialPropertyDeclaration(expr); } - if (isInJSFile(expr) && + if ( + isInJSFile(expr) && file.commonJsModuleIndicator && isModuleExportsAccessExpression(expr) && - !lookupSymbolForName(blockScopeContainer, "module" as __String)) { - declareSymbol(file.locals!, /*parent*/ undefined, expr.expression, - SymbolFlags.FunctionScopedVariable | SymbolFlags.ModuleExports, SymbolFlags.FunctionScopedVariableExcludes); + !lookupSymbolForName(blockScopeContainer, "module" as __String) + ) { + declareSymbol(file.locals!, /*parent*/ undefined, expr.expression, SymbolFlags.FunctionScopedVariable | SymbolFlags.ModuleExports, SymbolFlags.FunctionScopedVariableExcludes); } break; case SyntaxKind.BinaryExpression: @@ -2870,8 +2875,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.Method | ((node as MethodDeclaration).questionToken ? SymbolFlags.Optional : SymbolFlags.None), - isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes); + return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.Method | ((node as MethodDeclaration).questionToken ? SymbolFlags.Optional : SymbolFlags.None), isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes); case SyntaxKind.FunctionDeclaration: return bindFunctionDeclaration(node as FunctionDeclaration); case SyntaxKind.Constructor: @@ -3294,7 +3298,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { function bindSpecialPropertyAssignment(node: BindablePropertyAssignmentExpression) { // Class declarations in Typescript do not allow property declarations - const parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer) ; + const parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer); if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) { return; } @@ -3376,19 +3380,23 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } // Maybe accessor-like else if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) { - if (some(declaration.arguments[2].properties, p => { - const id = getNameOfDeclaration(p); - return !!id && isIdentifier(id) && idText(id) === "set"; - })) { + if ( + some(declaration.arguments[2].properties, p => { + const id = getNameOfDeclaration(p); + return !!id && isIdentifier(id) && idText(id) === "set"; + }) + ) { // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration) includes |= SymbolFlags.SetAccessor | SymbolFlags.Property; excludes |= SymbolFlags.SetAccessorExcludes; } - if (some(declaration.arguments[2].properties, p => { - const id = getNameOfDeclaration(p); - return !!id && isIdentifier(id) && idText(id) === "get"; - })) { + if ( + some(declaration.arguments[2].properties, p => { + const id = getNameOfDeclaration(p); + return !!id && isIdentifier(id) && idText(id) === "get"; + }) + ) { includes |= SymbolFlags.GetAccessor | SymbolFlags.Property; excludes |= SymbolFlags.GetAccessorExcludes; } @@ -3538,7 +3546,8 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { if (!isBindingPattern(node.name)) { const possibleVariableDecl = node.kind === SyntaxKind.VariableDeclaration ? node : node.parent.parent; - if (isInJSFile(node) && + if ( + isInJSFile(node) && shouldResolveJsRequire(options) && isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) && !getJSDocTypeTag(node) && @@ -3703,8 +3712,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // - node is not block scoped variable statement and at least one variable declaration has initializer // Rationale: we don't want to report errors on non-initialized var's since they are hoisted // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - const isError = - unreachableCodeIsError(options) && + const isError = unreachableCodeIsError(options) && !(node.flags & NodeFlags.Ambient) && ( !isVariableStatement(node) || diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index 7eae60d4e434b..40579969a48b6 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -90,7 +90,7 @@ import { export interface ReusableDiagnostic extends ReusableDiagnosticRelatedInformation { /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ reportsUnnecessary?: {}; - reportDeprecated?: {} + reportDeprecated?: {}; source?: string; relatedInformation?: ReusableDiagnosticRelatedInformation[]; skippedOn?: keyof CompilerOptions; @@ -176,6 +176,7 @@ export interface ReusableBuilderProgramState extends BuilderState { bundle?: BundleBuildInfo; } +// dprint-ignore /** @internal */ export const enum BuilderFileEmit { None = 0, @@ -250,15 +251,18 @@ export interface BuilderProgramState extends BuilderState, ReusableBuilderProgra } /** @internal */ -export type SavedBuildProgramEmitState = Pick & { changedFilesSet: BuilderProgramState["changedFilesSet"] | undefined }; +export type SavedBuildProgramEmitState = + & Pick< + BuilderProgramState, + | "affectedFilesPendingEmit" + | "seenEmittedFiles" + | "programEmitPending" + | "emitSignatures" + | "outSignature" + | "latestChangedDtsFile" + | "hasChangedEmitSignature" + > + & { changedFilesSet: BuilderProgramState["changedFilesSet"] | undefined; }; /** * Get flags determining what all needs to be emitted @@ -356,7 +360,8 @@ function createBuilderProgramState(newProgram: Program, oldState: Readonly | undefined; // if not using old state, every file is changed - if (!useOldState || + if ( + !useOldState || // File wasn't present in old state !(oldInfo = oldState!.fileInfos.get(sourceFilePath)) || // versions dont match @@ -366,7 +371,8 @@ function createBuilderProgramState(newProgram: Program, oldState: Readonly !state.fileInfos.has(path) && oldState!.fileInfos.has(path))) { + newReferences && forEachKey(newReferences, path => !state.fileInfos.has(path) && oldState!.fileInfos.has(path)) + ) { // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated addFileToChangeSet(state, sourceFilePath); } @@ -383,7 +389,7 @@ function createBuilderProgramState(newProgram: Program, oldState: Readonly { - if (state.fileInfos.has(sourceFilePath)) return false; - if (outFilePath || info.affectsGlobalScope) return true; - // if file is deleted we need to write buildInfo again - state.buildInfoEmitPending = true; - return false; - })) { + if ( + useOldState && forEachEntry(oldState!.fileInfos, (info, sourceFilePath) => { + if (state.fileInfos.has(sourceFilePath)) return false; + if (outFilePath || info.affectsGlobalScope) return true; + // if file is deleted we need to write buildInfo again + state.buildInfoEmitPending = true; + return false; + }) + ) { BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined) .forEach(file => addFileToChangeSet(state, file.resolvedPath)); } @@ -425,7 +433,7 @@ function createBuilderProgramState(newProgram: Program, oldState: Readonly program.isSourceFileDefaultLibrary(f) && !skipTypeChecking(f, options, program) && - removeSemanticDiagnosticsOf(state, f.resolvedPath) - ); + removeSemanticDiagnosticsOf(state, f.resolvedPath)); } } @@ -741,7 +748,7 @@ function handleDtsMayChangeOf( state: BuilderProgramState, path: Path, cancellationToken: CancellationToken | undefined, - host: BuilderProgramHost + host: BuilderProgramHost, ): void { removeSemanticDiagnosticsOf(state, path); @@ -760,7 +767,7 @@ function handleDtsMayChangeOf( sourceFile, cancellationToken, host, - /*useFileVersionAsSignature*/ true + /*useFileVersionAsSignature*/ true, ); // If not dts emit, nothing more to do if (getEmitDeclarations(state.compilerOptions)) { @@ -798,12 +805,14 @@ function handleDtsMayChangeOfGlobalScope( if (!state.fileInfos.get(filePath)?.affectsGlobalScope) return false; // Every file needs to be handled BuilderState.getAllFilesExcludingDefaultLibraryFile(state, state.program!, /*firstSourceFile*/ undefined) - .forEach(file => handleDtsMayChangeOf( - state, - file.resolvedPath, - cancellationToken, - host, - )); + .forEach(file => + handleDtsMayChangeOf( + state, + file.resolvedPath, + cancellationToken, + host, + ) + ); removeDiagnosticsOfLibraryFiles(state); return true; } @@ -815,7 +824,7 @@ function handleDtsMayChangeOfReferencingExportOfAffectedFile( state: BuilderProgramState, affectedFile: SourceFile, cancellationToken: CancellationToken | undefined, - host: BuilderProgramHost + host: BuilderProgramHost, ) { // If there was change in signature (dts output) for the changed file, // then only we need to handle pending file emit @@ -855,8 +864,7 @@ function handleDtsMayChangeOfReferencingExportOfAffectedFile( seenFileAndExportsOfFile, cancellationToken, host, - ) - ); + )); }); } @@ -907,7 +915,7 @@ function handleDtsMayChangeOfFileAndExportsOfFile( function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] { return concatenate( getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), - Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile) + Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile), ); } @@ -934,9 +942,9 @@ function getBinderAndCheckerDiagnosticsOfFile(state: BuilderProgramState, source } /** @internal */ -export type ProgramBuildInfoFileId = number & { __programBuildInfoFileIdBrand: any }; +export type ProgramBuildInfoFileId = number & { __programBuildInfoFileIdBrand: any; }; /** @internal */ -export type ProgramBuildInfoFileIdListId = number & { __programBuildInfoFileIdListIdBrand: any }; +export type ProgramBuildInfoFileIdListId = number & { __programBuildInfoFileIdListIdBrand: any; }; /** @internal */ export type ProgramBuildInfoDiagnostic = ProgramBuildInfoFileId | [fileId: ProgramBuildInfoFileId, diagnostics: readonly ReusableDiagnostic[]]; /** @@ -1057,10 +1065,10 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde outSignature: state.outSignature, latestChangedDtsFile, pendingEmit: !state.programEmitPending ? - undefined : // Pending is undefined or None is encoded as undefined + undefined : // Pending is undefined or None is encoded as undefined state.programEmitPending === getBuilderFileEmit(state.compilerOptions) ? - false : // Pending emit is same as deteremined by compilerOptions - state.programEmitPending, // Actual value + false : // Pending emit is same as deteremined by compilerOptions + state.programEmitPending, // Actual value }; // Complete the bundle information if we are doing partial emit (only js or only dts) const { js, dts, commonSourceDirectory, sourceFiles } = bundle!; @@ -1088,10 +1096,12 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde if (!isJsonSourceFile(file) && sourceFileMayBeEmitted(file, state.program!)) { const emitSignature = state.emitSignatures?.get(key); if (emitSignature !== actualSignature) { - (emitSignatures ||= []).push(emitSignature === undefined ? - fileId : // There is no emit, encode as false - // fileId, signature: emptyArray if signature only differs in dtsMap option than our own compilerOptions otherwise EmitSignature - [fileId, !isString(emitSignature) && emitSignature[0] === actualSignature ? emptyArray as [] : emitSignature]); + (emitSignatures ||= []).push( + emitSignature === undefined ? + fileId : // There is no emit, encode as false + // fileId, signature: emptyArray if signature only differs in dtsMap option than our own compilerOptions otherwise EmitSignature + [fileId, !isString(emitSignature) && emitSignature[0] === actualSignature ? emptyArray as [] : emitSignature], + ); } } } @@ -1102,20 +1112,20 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde // If file info only contains version and signature and both are same we can just write string value.version : actualSignature !== undefined ? // If signature is not same as version, encode signature in the fileInfo - oldSignature === undefined ? - // If we havent computed signature, use fileInfo as is - value : - // Serialize fileInfo with new updated signature - { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : - // Signature of the FileInfo is undefined, serialize it as false - { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; + oldSignature === undefined ? + // If we havent computed signature, use fileInfo as is + value : + // Serialize fileInfo with new updated signature + { version: value.version, signature: actualSignature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } : + // Signature of the FileInfo is undefined, serialize it as false + { version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat }; }); let referencedMap: ProgramBuildInfoReferencedMap | undefined; if (state.referencedMap) { referencedMap = arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive).map(key => [ toFileId(key), - toFileIdListId(state.referencedMap!.getValues(key)!) + toFileIdListId(state.referencedMap!.getValues(key)!), ]); } @@ -1138,9 +1148,9 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde value.length ? [ toFileId(key), - convertToReusableDiagnostics(value, relativeToBuildInfo) + convertToReusableDiagnostics(value, relativeToBuildInfo), ] : - toFileId(key) + toFileId(key), ); } } @@ -1156,10 +1166,10 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde const fileId = toFileId(path), pendingEmit = state.affectedFilesPendingEmit.get(path)!; (affectedFilesPendingEmit ||= []).push( pendingEmit === fullEmitForOptions ? - fileId : // Pending full emit per options + fileId : // Pending full emit per options pendingEmit === BuilderFileEmit.Dts ? - [fileId] : // Pending on Dts only - [fileId, pendingEmit] // Anything else + [fileId] : // Pending on Dts only + [fileId, pendingEmit], // Anything else ); } } @@ -1247,7 +1257,7 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde (result ||= {})[name] = convertToReusableCompilerOptionValue( optionInfo, options[name] as CompilerOptionsValue, - relativeToBuildInfoEnsuringAbsolutePath + relativeToBuildInfoEnsuringAbsolutePath, ); } } @@ -1326,7 +1336,7 @@ function convertToReusableDiagnosticMessageChainArray(array: DiagnosticMessageCh /** @internal */ export enum BuilderProgramKind { SemanticDiagnosticsBuilderProgram, - EmitAndSemanticDiagnosticsBuilderProgram + EmitAndSemanticDiagnosticsBuilderProgram, } /** @internal */ @@ -1357,7 +1367,7 @@ export function getBuilderCreationParameters(newProgramOrRootNames: Program | re host: oldProgramOrHost as CompilerHost, oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), configFileParsingDiagnostics, - projectReferences + projectReferences, }); host = oldProgramOrHost as CompilerHost; } @@ -1380,14 +1390,12 @@ export function computeSignatureWithDiagnostics( sourceFile: SourceFile, text: string, host: HostForComputeHash, - data: WriteFileCallbackData | undefined + data: WriteFileCallbackData | undefined, ) { text = getTextHandlingSourceMapForSignature(text, data); let sourceFileDirectory: string | undefined; if (data?.diagnostics?.length) { - text += data.diagnostics.map(diagnostic => - `${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText)}` - ).join("\n"); + text += data.diagnostics.map(diagnostic => `${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText)}`).join("\n"); } return (host.createHash ?? generateDjb2Hash)(text); @@ -1395,20 +1403,22 @@ export function computeSignatureWithDiagnostics( return isString(diagnostic) ? diagnostic : diagnostic === undefined ? - "" : - !diagnostic.next ? - diagnostic.messageText : - diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); + "" : + !diagnostic.next ? + diagnostic.messageText : + diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n"); } function locationInfo(diagnostic: DiagnosticWithLocation) { if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) return `(${diagnostic.start},${diagnostic.length})`; if (sourceFileDirectory === undefined) sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath); - return `${ensurePathIsNonModuleName(getRelativePathFromDirectory( - sourceFileDirectory, - diagnostic.file.resolvedPath, - program.getCanonicalFileName, - ))}(${diagnostic.start},${diagnostic.length})`; + return `${ + ensurePathIsNonModuleName(getRelativePathFromDirectory( + sourceFileDirectory, + diagnostic.file.resolvedPath, + program.getCanonicalFileName, + )) + }(${diagnostic.start},${diagnostic.length})`; } } @@ -1443,7 +1453,7 @@ export function createBuilderProgram(kind: BuilderProgramKind, { newProgram, hos const builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); builderProgram.getState = getState; builderProgram.saveEmitState = () => backupBuilderProgramEmitState(state); - builderProgram.restoreEmitState = (saved) => restoreBuilderProgramEmitState(state, saved); + builderProgram.restoreEmitState = saved => restoreBuilderProgramEmitState(state, saved); builderProgram.hasChangedEmitSignature = () => !!state.hasChangedEmitSignature; builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile); builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; @@ -1515,8 +1525,8 @@ export function createBuilderProgram(kind: BuilderProgramKind, { newProgram, hos state.programEmitPending = state.changedFilesSet.size ? getPendingEmitKind(programEmitKind, emitKind) : state.programEmitPending ? - getPendingEmitKind(state.programEmitPending, emitKind) : - undefined; + getPendingEmitKind(state.programEmitPending, emitKind) : + undefined; } // Actual emit const result = state.program!.emit( @@ -1524,7 +1534,7 @@ export function createBuilderProgram(kind: BuilderProgramKind, { newProgram, hos getWriteFileCallback(writeFile, customTransformers), cancellationToken, emitOnly, - customTransformers + customTransformers, ); if (affected !== state.program) { // update affected files @@ -1669,7 +1679,7 @@ export function createBuilderProgram(kind: BuilderProgramKind, { newProgram, hos emitSkipped, diagnostics: diagnostics || emptyArray, emittedFiles, - sourceMaps + sourceMaps, }; } // In non Emit builder, clear affected files pending emit @@ -1682,7 +1692,7 @@ export function createBuilderProgram(kind: BuilderProgramKind, { newProgram, hos getWriteFileCallback(writeFile, customTransformers), cancellationToken, emitOnlyDtsFiles, - customTransformers + customTransformers, ); } @@ -1762,12 +1772,12 @@ export function toBuilderStateFileInfoForMultiEmit(fileInfo: ProgramMultiFileEmi return isString(fileInfo) ? { version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined, impliedFormat: undefined } : isString(fileInfo.signature) ? - fileInfo as BuilderState.FileInfo : - { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; + fileInfo as BuilderState.FileInfo : + { version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } /** @internal */ -export function toBuilderFileEmit(value: ProgramBuilderInfoFilePendingEmit, fullEmitForOptions: BuilderFileEmit): BuilderFileEmit{ +export function toBuilderFileEmit(value: ProgramBuilderInfoFilePendingEmit, fullEmitForOptions: BuilderFileEmit): BuilderFileEmit { return isNumber(value) ? fullEmitForOptions : value[1] || BuilderFileEmit.Dts; } @@ -1815,10 +1825,12 @@ export function createBuilderProgramUsingProgramBuildInfo(buildInfo: BuildInfo, if (isNumber(value)) emitSignatures!.delete(toFilePath(value)); else { const key = toFilePath(value[0]); - emitSignatures!.set(key, !isString(value[1]) && !value[1].length ? - // File signature is emit signature but differs in map - [emitSignatures!.get(key)! as string] : - value[1] + emitSignatures!.set( + key, + !isString(value[1]) && !value[1].length ? + // File signature is emit signature but differs in map + [emitSignatures!.get(key)! as string] : + value[1], ); } }); @@ -1885,9 +1897,7 @@ export function createBuilderProgramUsingProgramBuildInfo(buildInfo: BuildInfo, } const map = BuilderState.createManyToManyPathMap(); - referenceMap.forEach(([fileId, fileIdListId]) => - map.set(toFilePath(fileId), toFilePathsSet(fileIdListId)) - ); + referenceMap.forEach(([fileId, fileIdListId]) => map.set(toFilePath(fileId), toFilePathsSet(fileIdListId))); return map; } } @@ -1896,7 +1906,7 @@ export function createBuilderProgramUsingProgramBuildInfo(buildInfo: BuildInfo, export function getBuildInfoFileVersionMap( program: ProgramBuildInfo, buildInfoPath: string, - host: Pick + host: Pick, ) { const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 5424336399c4e..3a9dd2be65a02 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -36,8 +36,14 @@ import { } from "./_namespaces/ts"; /** @internal */ -export function getFileEmitOutput(program: Program, sourceFile: SourceFile, emitOnlyDtsFiles: boolean, - cancellationToken?: CancellationToken, customTransformers?: CustomTransformers, forceDtsEmit?: boolean): EmitOutput { +export function getFileEmitOutput( + program: Program, + sourceFile: SourceFile, + emitOnlyDtsFiles: boolean, + cancellationToken?: CancellationToken, + customTransformers?: CustomTransformers, + forceDtsEmit?: boolean, +): EmitOutput { const outputFiles: OutputFile[] = []; const { emitSkipped, diagnostics } = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit); return { outputFiles, emitSkipped, diagnostics }; @@ -273,8 +279,10 @@ export namespace BuilderState { // Add any file other than our own as reference for (const declaration of symbol.declarations) { const declarationSourceFile = getSourceFileOfNode(declaration); - if (declarationSourceFile && - declarationSourceFile !== sourceFile) { + if ( + declarationSourceFile && + declarationSourceFile !== sourceFile + ) { addReferencedFile(declarationSourceFile.resolvedPath); } } @@ -335,7 +343,7 @@ export namespace BuilderState { signature, // No need to calculate affectsGlobalScope with --out since its not used at all affectsGlobalScope: !isOutFile ? isFileAffectingGlobalScope(sourceFile) || undefined : undefined, - impliedFormat: sourceFile.impliedNodeFormat + impliedFormat: sourceFile.impliedNodeFormat, }); } @@ -343,7 +351,7 @@ export namespace BuilderState { fileInfos, referencedMap, exportedModulesMap, - useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState + useFileVersionAsSignature: !disableUseFileVersionAsSignature && !useOldState, }; } @@ -412,18 +420,21 @@ export namespace BuilderState { sourceFile, (fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) => { Debug.assert(isDeclarationFileName(fileName), `File extension for signature expected to be dts: Got:: ${fileName}`); - onNewSignature(computeSignatureWithDiagnostics( - programOfThisState, - sourceFile, - text, - host, - data, - ), sourceFiles!); + onNewSignature( + computeSignatureWithDiagnostics( + programOfThisState, + sourceFile, + text, + host, + data, + ), + sourceFiles!, + ); }, cancellationToken, /*emitOnly*/ true, /*customTransformers*/ undefined, - /*forceDtsEmit*/ true + /*forceDtsEmit*/ true, ); } @@ -491,9 +502,10 @@ export namespace BuilderState { export function getExportedModules(exportedModulesFromDeclarationEmit: ExportedModulesFromDeclarationEmit | undefined) { let exportedModules: Set | undefined; exportedModulesFromDeclarationEmit?.forEach( - symbol => getReferencedFilesFromImportedModuleSymbol(symbol).forEach( - path => (exportedModules ??= new Set()).add(path) - ) + symbol => + getReferencedFilesFromImportedModuleSymbol(symbol).forEach( + path => (exportedModules ??= new Set()).add(path), + ), ); return exportedModules; } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d23a2c35a3f51..9c09379cde9b5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1075,7 +1075,7 @@ import { WhileStatement, WideningContext, WithStatement, - YieldExpression + YieldExpression, } from "./_namespaces/ts"; import * as moduleSpecifiers from "./_namespaces/ts.moduleSpecifiers"; import * as performance from "./_namespaces/ts.performance"; @@ -1111,7 +1111,6 @@ const enum IterationUse { GeneratorReturnType = AllowsSyncIterablesFlag, AsyncGeneratorReturnType = AllowsAsyncIterablesFlag, - } const enum IterationTypeKind { @@ -1141,6 +1140,7 @@ const enum WideningKind { GeneratorYield, } +// dprint-ignore /** @internal */ export const enum TypeFacts { None = 0, @@ -1233,7 +1233,7 @@ const typeofNEFacts: ReadonlyMap = new Map(Object.entries({ symbol: TypeFacts.TypeofNESymbol, undefined: TypeFacts.NEUndefined, object: TypeFacts.TypeofNEObject, - function: TypeFacts.TypeofNEFunction + function: TypeFacts.TypeofNEFunction, })); type TypeSystemEntity = Node | Symbol | Type | Signature; @@ -1251,6 +1251,7 @@ const enum TypeSystemPropertyName { ParameterInitializerContainsUndefined, } +// dprint-ignore /** @internal */ export const enum CheckMode { Normal = 0, // Normal type checking @@ -1279,8 +1280,8 @@ export const enum SignatureCheckMode { const enum IntersectionState { None = 0, - Source = 1 << 0, // Source type is a constituent of an outer intersection - Target = 1 << 1, // Target type is a constituent of an outer intersection + Source = 1 << 0, // Source type is a constituent of an outer intersection + Target = 1 << 1, // Target type is a constituent of an outer intersection } const enum RecursionFlags { @@ -1306,7 +1307,7 @@ const enum ExpandingFlags { const enum MembersOrExportsResolutionKind { resolvedExports = "resolvedExports", - resolvedMembers = "resolvedMembers" + resolvedMembers = "resolvedMembers", } const enum UnusedKind { @@ -1346,14 +1347,14 @@ const enum IntrinsicTypeKind { Uppercase, Lowercase, Capitalize, - Uncapitalize + Uncapitalize, } const intrinsicTypeKinds: ReadonlyMap = new Map(Object.entries({ Uppercase: IntrinsicTypeKind.Uppercase, Lowercase: IntrinsicTypeKind.Lowercase, Capitalize: IntrinsicTypeKind.Capitalize, - Uncapitalize: IntrinsicTypeKind.Uncapitalize + Uncapitalize: IntrinsicTypeKind.Uncapitalize, })); const SymbolLinks = class implements SymbolLinks { @@ -1642,23 +1643,21 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const node = getParseTreeNode(nodeIn, isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: (nodeIn) => { + getContextualTypeForJsxAttribute: nodeIn => { const node = getParseTreeNode(nodeIn, isJsxAttributeLike); return node && getContextualTypeForJsxAttribute(node, /*contextFlags*/ undefined); }, isContextSensitive, getTypeOfPropertyOfContextualType, getFullyQualifiedName, - getResolvedSignature: (node, candidatesOutArray, argumentCount) => - getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, CheckMode.Normal), + getResolvedSignature: (node, candidatesOutArray, argumentCount) => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, CheckMode.Normal), getResolvedSignatureForStringLiteralCompletions: (call, editingArgument, candidatesOutArray, checkMode = CheckMode.IsForStringLiteralArgumentCompletions) => { if (checkMode & CheckMode.IsForStringLiteralArgumentCompletions) { return runWithInferenceBlockedFromSourceNode(editingArgument, () => getResolvedSignatureWorker(call, candidatesOutArray, /*argumentCount*/ undefined, checkMode & ~CheckMode.IsForStringLiteralArgumentCompletions)); } return runWithoutResolvedSignatureCaching(editingArgument, () => getResolvedSignatureWorker(call, candidatesOutArray, /*argumentCount*/ undefined, checkMode & ~CheckMode.IsForStringLiteralArgumentCompletions)); }, - getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount) => - runWithoutResolvedSignatureCaching(node, () => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, CheckMode.IsForSignatureHelp)), + getResolvedSignatureForSignatureHelp: (node, candidatesOutArray, argumentCount) => runWithoutResolvedSignatureCaching(node, () => getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, CheckMode.IsForSignatureHelp)), getExpandedParameters, hasEffectiveRestParameter, containsArgumentsReference, @@ -1862,7 +1861,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { do { getNodeLinks(toMarkSkip).skipDirectInference = true; toMarkSkip = toMarkSkip.parent; - } while (toMarkSkip && toMarkSkip !== containingCall); + } + while (toMarkSkip && toMarkSkip !== containingCall); } isInferencePartiallyBlocked = true; @@ -1874,7 +1874,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { do { getNodeLinks(toMarkSkip).skipDirectInference = undefined; toMarkSkip = toMarkSkip.parent; - } while (toMarkSkip && toMarkSkip !== containingCall); + } + while (toMarkSkip && toMarkSkip !== containingCall); } return result; } @@ -1959,7 +1960,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; var numberOrBigIntType = getUnionType([numberType, bigintType]); var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]) as UnionType; - var numericStringType = getTemplateLiteralType(["", ""], [numberType]); // The `${number}` type + var numericStringType = getTemplateLiteralType(["", ""], [numberType]); // The `${number}` type var restrictiveMapper: TypeMapper = makeFunctionTypeMapper(t => t.flags & TypeFlags.TypeParameter ? getRestrictiveTypeParameter(t as TypeParameter) : t, () => "(restrictive mapper)"); var permissiveMapper: TypeMapper = makeFunctionTypeMapper(t => t.flags & TypeFlags.TypeParameter ? wildcardType : t, () => "(permissive mapper)"); @@ -2022,9 +2023,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { var iterationTypesCache = new Map(); // cache for common IterationTypes instances var noIterationTypes: IterationTypes = { - get yieldType(): Type { return Debug.fail("Not supported"); }, - get returnType(): Type { return Debug.fail("Not supported"); }, - get nextType(): Type { return Debug.fail("Not supported"); }, + get yieldType(): Type { + return Debug.fail("Not supported"); + }, + get returnType(): Type { + return Debug.fail("Not supported"); + }, + get nextType(): Type { + return Debug.fail("Not supported"); + }, }; var anyIterationTypes = createIterationTypes(anyType, anyType, anyType); @@ -2357,7 +2364,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } function errorOrSuggestion(isError: boolean, location: Node, message: DiagnosticMessage | DiagnosticMessageChain, ...args: DiagnosticArguments): void { - // Pseudo-synthesized input node + // Pseudo-synthesized input node if (location.pos < 0 || location.end < 0) { if (!isError) { return; // Drop suggestions (we have no span to suggest on) @@ -2374,7 +2381,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { location: Node, maybeMissingAwait: boolean, message: DiagnosticMessage, - ...args: DiagnosticArguments): Diagnostic { + ...args: DiagnosticArguments + ): Diagnostic { const diagnostic = error(location, message, ...args); if (maybeMissingAwait) { const related = createDiagnosticForNode(location, Diagnostics.Did_you_forget_to_use_await); @@ -2388,7 +2396,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (deprecatedTag) { addRelatedInfo( diagnostic, - createDiagnosticForNode(deprecatedTag, Diagnostics.The_declaration_was_marked_as_deprecated_here) + createDiagnosticForNode(deprecatedTag, Diagnostics.The_declaration_was_marked_as_deprecated_here), ); } // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates. @@ -2487,8 +2495,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it. */ function mergeSymbol(target: Symbol, source: Symbol, unidirectional = false): Symbol { - if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & SymbolFlags.Assignment) { + if ( + !(target.flags & getExcludedSymbolFlags(source.flags)) || + (source.flags | target.flags) & SymbolFlags.Assignment + ) { if (source === target) { // This can happen when an export assigned namespace exports something also erroneously exported at the top level // See `declarationFileNoCrashOnExtraExportModifier` for an example @@ -2531,7 +2541,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error( source.declarations && getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, - symbolToString(target)); + symbolToString(target), + ); } } else { // error @@ -2551,10 +2562,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === Comparison.LessThan ? sourceSymbolFile : targetSymbolFile; const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; - const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, (): DuplicateInfoForFiles => - ({ firstFile, secondFile, conflictingSymbols: new Map() })); - const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName, (): DuplicateInfoForSymbol => - ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] })); + const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, (): DuplicateInfoForFiles => ({ firstFile, secondFile, conflictingSymbols: new Map() })); + const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName, (): DuplicateInfoForSymbol => ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] })); if (!isSourcePlainJs) addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); if (!isTargetPlainJs) addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); } @@ -2746,10 +2755,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const useFile = getSourceFileOfNode(usage); const declContainer = getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { - if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + if ( + (moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!outFile(compilerOptions)) || isInTypeQuery(usage) || - declaration.flags & NodeFlags.Ambient) { + declaration.flags & NodeFlags.Ambient + ) { // nodes are in different files and order cannot be determined return true; } @@ -2789,13 +2800,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (isParameterPropertyDeclaration(declaration, declaration.parent)) { // foo = this.bar is illegal in emitStandardClassFields when bar is a parameter property return !(emitStandardClassFields - && getContainingClass(declaration) === getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration)); + && getContainingClass(declaration) === getContainingClass(usage) + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } - // declaration is after usage, but it can still be legal if usage is deferred: // 1. inside an export specifier // 2. inside a function @@ -2819,9 +2829,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (emitStandardClassFields + if ( + emitStandardClassFields && getContainingClass(declaration) - && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent)) + ) { return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); } else { @@ -2911,9 +2923,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.PropertyDeclaration: // even when stopping at any property declaration, they need to come from the same class return stopAtAnyPropertyDeclaration && - (isPropertyDeclaration(declaration) && node.parent === declaration.parent - || isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) - ? "quit": true; + (isPropertyDeclaration(declaration) && node.parent === declaration.parent + || isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent) + ? "quit" : true; case SyntaxKind.Block: switch (node.parent.kind) { case SyntaxKind.GetAccessor: @@ -2935,11 +2947,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function useOuterVariableScopeInParameter(result: Symbol, location: Node, lastLocation: Node) { const target = getEmitScriptTarget(compilerOptions); const functionLocation = location as FunctionLikeDeclaration; - if (isParameter(lastLocation) + if ( + isParameter(lastLocation) && functionLocation.body && result.valueDeclaration && result.valueDeclaration.pos >= functionLocation.body.pos - && result.valueDeclaration.end <= functionLocation.body.end) { + && result.valueDeclaration.end <= functionLocation.body.end + ) { // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body // - static field in a class expression // - optional chaining pre-es2020 @@ -3014,7 +3028,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { nameArg: __String | Identifier | undefined, isUse: boolean, excludeGlobals = false, - getSpellingSuggestions = true): Symbol | undefined { + getSpellingSuggestions = true, + ): Symbol | undefined { return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggestions, getSymbol); } @@ -3027,7 +3042,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isUse: boolean, excludeGlobals: boolean, getSpellingSuggestions: boolean, - lookup: typeof getSymbol): Symbol | undefined { + lookup: typeof getSymbol, + ): Symbol | undefined { const originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location let result: Symbol | undefined; let lastLocation: Node | undefined; @@ -3039,7 +3055,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let grandparent: Node; let isInExternalModule = false; - loop: while (location) { + loop: + while (location) { if (name === "const" && isConstAssertion(location)) { // `const` in an `as const` has no symbol, but issues no error because there is no *actual* lookup of the type // (it refers to the constant type of the expression instead) @@ -3066,10 +3083,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { useResult = result.flags & SymbolFlags.TypeParameter // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === (location as FunctionLikeDeclaration).type || - lastLocation.kind === SyntaxKind.Parameter || - lastLocation.kind === SyntaxKind.JSDocParameterTag || - lastLocation.kind === SyntaxKind.JSDocReturnTag || - lastLocation.kind === SyntaxKind.TypeParameter + lastLocation.kind === SyntaxKind.Parameter || + lastLocation.kind === SyntaxKind.JSDocParameterTag || + lastLocation.kind === SyntaxKind.JSDocReturnTag || + lastLocation.kind === SyntaxKind.TypeParameter // local types not visible outside the function body : false; } @@ -3083,8 +3100,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // technically for parameter list case here we might mix parameters and variables declared in function, // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === SyntaxKind.Parameter || + useResult = lastLocation.kind === SyntaxKind.Parameter || ( lastLocation === (location as FunctionLikeDeclaration).type && !!findAncestor(result.valueDeclaration, isParameter) @@ -3115,7 +3131,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.ModuleDeclaration: const moduleExports = getSymbolOfDeclaration(location as SourceFile | ModuleDeclaration)?.exports || emptySymbols; if (location.kind === SyntaxKind.SourceFile || (isModuleDeclaration(location) && location.flags & NodeFlags.Ambient && !isGlobalScopeAugmentation(location))) { - // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get(InternalSymbolName.Default)) { @@ -3138,9 +3153,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, // which is not the desired behavior. const moduleExport = moduleExports.get(name); - if (moduleExport && + if ( + moduleExport && moduleExport.flags === SymbolFlags.Alias && - (getDeclarationOfKind(moduleExport, SyntaxKind.ExportSpecifier) || getDeclarationOfKind(moduleExport, SyntaxKind.NamespaceExport))) { + (getDeclarationOfKind(moduleExport, SyntaxKind.ExportSpecifier) || getDeclarationOfKind(moduleExport, SyntaxKind.NamespaceExport)) + ) { break; } } @@ -3163,7 +3180,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { Diagnostics.Cannot_access_0_from_another_file_without_qualification_when_1_is_enabled_Use_2_instead, unescapeLeadingUnderscores(name), isolatedModulesLikeFlagName, - `${unescapeLeadingUnderscores(getSymbolOfNode(location)!.escapedName)}.${unescapeLeadingUnderscores(name)}`); + `${unescapeLeadingUnderscores(getSymbolOfNode(location)!.escapedName)}.${unescapeLeadingUnderscores(name)}`, + ); } break loop; } @@ -3319,18 +3337,24 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } break; case SyntaxKind.Parameter: - if (lastLocation && ( - lastLocation === (location as ParameterDeclaration).initializer || - lastLocation === (location as ParameterDeclaration).name && isBindingPattern(lastLocation))) { + if ( + lastLocation && ( + lastLocation === (location as ParameterDeclaration).initializer || + lastLocation === (location as ParameterDeclaration).name && isBindingPattern(lastLocation) + ) + ) { if (!associatedDeclarationForContainingInitializerOrBindingName) { associatedDeclarationForContainingInitializerOrBindingName = location as ParameterDeclaration; } } break; case SyntaxKind.BindingElement: - if (lastLocation && ( - lastLocation === (location as BindingElement).initializer || - lastLocation === (location as BindingElement).name && isBindingPattern(lastLocation))) { + if ( + lastLocation && ( + lastLocation === (location as BindingElement).initializer || + lastLocation === (location as BindingElement).name && isBindingPattern(lastLocation) + ) + ) { if (isParameterDeclaration(location as BindingElement) && !associatedDeclarationForContainingInitializerOrBindingName) { associatedDeclarationForContainingInitializerOrBindingName = location as BindingElement; } @@ -3347,9 +3371,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; case SyntaxKind.ExportSpecifier: // External module export bindings shouldn't be resolved to local symbols. - if (lastLocation && + if ( + lastLocation && lastLocation === (location as ExportSpecifier).propertyName && - (location as ExportSpecifier).parent.parent.moduleSpecifier) { + (location as ExportSpecifier).parent.parent.moduleSpecifier + ) { location = location.parent.parent.parent; } break; @@ -3398,11 +3424,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed // with emitStandardClassFields because the scope semantics are different. - error(errorLocation, + error( + errorLocation, errorLocation && propertyWithInvalidInitializer.type && textRangeContainsPositionInclusive(propertyWithInvalidInitializer.type, errorLocation.pos) ? Diagnostics.Type_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor : Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, - declarationNameToString(propertyWithInvalidInitializer.name), diagnosticName(nameArg!)); + declarationNameToString(propertyWithInvalidInitializer.name), + diagnosticName(nameArg!), + ); return true; } return false; @@ -3411,16 +3440,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(() => { - if (!errorLocation || + if ( + !errorLocation || errorLocation.parent.kind !== SyntaxKind.JSDocLink && - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg!) && // TODO: GH#18217 - !checkAndReportErrorForInvalidInitializer() && - !checkAndReportErrorForExtendingInterface(errorLocation) && - !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && - !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && - !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg!) && // TODO: GH#18217 + !checkAndReportErrorForInvalidInitializer() && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) + ) { let suggestion: Symbol | undefined; let suggestedLib: string | undefined; // Report missing lib first @@ -3448,7 +3479,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (suggestion.valueDeclaration) { addRelatedInfo( diagnostic, - createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName) + createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName), ); } } @@ -3481,9 +3512,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // block-scoped variable and namespace module. However, only when we // try to resolve name in /*1*/ which is used in variable position, // we want to check for block-scoped - if (errorLocation && + if ( + errorLocation && (meaning & SymbolFlags.BlockScopedVariable || - ((meaning & SymbolFlags.Class || meaning & SymbolFlags.Enum) && (meaning & SymbolFlags.Value) === SymbolFlags.Value))) { + ((meaning & SymbolFlags.Class || meaning & SymbolFlags.Enum) && (meaning & SymbolFlags.Value) === SymbolFlags.Value)) + ) { const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result!); if (exportOrLocalSymbol.flags & SymbolFlags.BlockScopedVariable || exportOrLocalSymbol.flags & SymbolFlags.Class || exportOrLocalSymbol.flags & SymbolFlags.Enum) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); @@ -3501,7 +3534,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & SymbolFlags.Value) === SymbolFlags.Value) { const candidate = getMergedSymbol(getLateBoundSymbol(result)); - const root = (getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName) as ParameterDeclaration); + const root = getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName) as ParameterDeclaration; // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself if (candidate === getSymbolOfDeclaration(associatedDeclarationForContainingInitializerOrBindingName)) { error(errorLocation, Diagnostics.Parameter_0_cannot_reference_itself, declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); @@ -3521,7 +3554,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { addTypeOnlyDeclarationRelatedInfo( error(errorLocation, message, unescapedName), typeOnlyDeclaration, - unescapedName); + unescapedName, + ); } } }); @@ -3538,7 +3572,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { typeOnlyDeclaration.kind === SyntaxKind.ExportSpecifier || typeOnlyDeclaration.kind === SyntaxKind.ExportDeclaration || typeOnlyDeclaration.kind === SyntaxKind.NamespaceExport ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here, - unescapedName)); + unescapedName, + ), + ); } function getIsDeferredContext(location: Node, lastLocation: Node | undefined): boolean { @@ -3565,8 +3601,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { | InterfaceDeclaration | EnumDeclaration | TypeAliasDeclaration - | ModuleDeclaration - ; + | ModuleDeclaration; function isSelfReferenceLocation(node: Node): node is SelfReferenceLocation { switch (node.kind) { @@ -3638,7 +3673,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } - function checkAndReportErrorForExtendingInterface(errorLocation: Node): boolean { const expression = getEntityNameForExtendingInterface(errorLocation); if (expression && resolveEntityName(expression, SymbolFlags.Interface, /*ignoreErrors*/ true)) { @@ -3750,7 +3784,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isExtendedByInterface(node: Node): boolean { const grandparent = node.parent.parent; const parentOfGrandparent = grandparent.parent; - if(grandparent && parentOfGrandparent){ + if (grandparent && parentOfGrandparent) { const isExtending = isHeritageClause(grandparent) && grandparent.token === SyntaxKind.ExtendsKeyword; const isInterface = isInterfaceDeclaration(parentOfGrandparent); return isExtending && isInterface; @@ -3759,8 +3793,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function maybeMappedType(node: Node, symbol: Symbol) { - const container = findAncestor(node.parent, n => - isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit") as TypeLiteralNode | undefined; + const container = findAncestor(node.parent, n => isComputedPropertyName(n) || isPropertySignature(n) ? false : isTypeLiteralNode(n) || "quit") as TypeLiteralNode | undefined; if (container && container.members.length === 1) { const type = getDeclaredTypeOfSymbol(symbol); return !!(type.flags & TypeFlags.Union) && allTypesAssignableToKind(type, TypeFlags.StringOrNumberLiteral, /*strict*/ true); @@ -3788,7 +3821,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error( errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_value, - unescapeLeadingUnderscores(name)); + unescapeLeadingUnderscores(name), + ); return true; } } @@ -3810,7 +3844,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // Block-scoped variables cannot be used before their definition const declaration = result.declarations?.find( - d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration)); + d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration), + ); if (declaration === undefined) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); @@ -3828,9 +3863,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, - createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName) - ); + addRelatedInfo(diagnosticMessage, createDiagnosticForNode(declaration, Diagnostics._0_is_declared_here, declarationName)); } } } @@ -3841,7 +3874,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. */ function isSameScopeDescendentOf(initial: Node, parent: Node | undefined, stopAt: Node): boolean { - return !!parent && !!findAncestor(initial, n => n === parent + return !!parent && !!findAncestor(initial, n => + n === parent || (n === stopAt || isFunctionLike(n) && (!getImmediatelyInvokedFunctionExpression(n) || isAsyncFunction(n)) ? "quit" : false)); } @@ -3915,7 +3949,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isVariableDeclaration(node) || node.moduleReference.kind === SyntaxKind.ExternalModuleReference) { const immediate = resolveExternalModuleName( node, - getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node)); + getExternalModuleRequireArgument(node) || getExternalModuleImportEqualsDeclarationExpression(node), + ); const resolved = resolveExternalModuleSymbol(immediate); markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false); return resolved; @@ -4039,11 +4074,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const err = error(node.name, Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName); if (exportAssignment) { - addRelatedInfo(err, createDiagnosticForNode( - exportAssignment, - Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, - compilerOptionName - )); + addRelatedInfo( + err, + createDiagnosticForNode( + exportAssignment, + Diagnostics.This_module_is_declared_with_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, + compilerOptionName, + ), + ); } } else if (isImportClause(node)) { @@ -4065,12 +4103,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getModuleSpecifierForImportOrExport(node: ImportEqualsDeclaration | ImportClause | NamespaceImport | ImportOrExportSpecifier): Expression | undefined { switch (node.kind) { - case SyntaxKind.ImportClause: return node.parent.moduleSpecifier; - case SyntaxKind.ImportEqualsDeclaration: return isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : undefined; - case SyntaxKind.NamespaceImport: return node.parent.parent.moduleSpecifier; - case SyntaxKind.ImportSpecifier: return node.parent.parent.parent.moduleSpecifier; - case SyntaxKind.ExportSpecifier: return node.parent.parent.moduleSpecifier; - default: return Debug.assertNever(node); + case SyntaxKind.ImportClause: + return node.parent.moduleSpecifier; + case SyntaxKind.ImportEqualsDeclaration: + return isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : undefined; + case SyntaxKind.NamespaceImport: + return node.parent.parent.moduleSpecifier; + case SyntaxKind.ImportSpecifier: + return node.parent.parent.parent.moduleSpecifier; + case SyntaxKind.ExportSpecifier: + return node.parent.parent.moduleSpecifier; + default: + return Debug.assertNever(node); } } @@ -4087,10 +4131,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const diagnostic = error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); const exportStar = moduleSymbol.exports?.get(InternalSymbolName.ExportStar); if (exportStar) { - const defaultExport = exportStar.declarations?.find(decl => !!( - isExportDeclaration(decl) && decl.moduleSpecifier && + const defaultExport = exportStar.declarations?.find(decl => + !!( + isExportDeclaration(decl) && decl.moduleSpecifier && resolveExternalModuleName(decl, decl.moduleSpecifier)?.exports?.has(InternalSymbolName.Default) - )); + ) + ); if (defaultExport) { addRelatedInfo(diagnostic, createDiagnosticForNode(defaultExport, Diagnostics.export_Asterisk_does_not_re_export_a_default)); } @@ -4221,9 +4267,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const suggestionName = symbolToString(suggestion); const diagnostic = error(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); if (suggestion.valueDeclaration) { - addRelatedInfo(diagnostic, - createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName) - ); + addRelatedInfo(diagnostic, createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestionName)); } } else { @@ -4232,7 +4276,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { name, Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, - declarationName + declarationName, ); } else { @@ -4255,9 +4299,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const diagnostic = exportedSymbol ? error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : error(name, Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); if (localSymbol.declarations) { - addRelatedInfo(diagnostic, - ...map(localSymbol.declarations, (decl, index) => - createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName))); + addRelatedInfo(diagnostic, ...map(localSymbol.declarations, (decl, index) => createDiagnosticForNode(decl, index === 0 ? Diagnostics._0_is_declared_here : Diagnostics.and_here, declarationName))); } } } @@ -4382,7 +4424,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getTargetOfExportSpecifier(node as ExportSpecifier, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, dontRecursivelyResolve); case SyntaxKind.ExportAssignment: case SyntaxKind.BinaryExpression: - return getTargetOfExportAssignment((node as ExportAssignment | BinaryExpression), dontRecursivelyResolve); + return getTargetOfExportAssignment(node as ExportAssignment | BinaryExpression, dontRecursivelyResolve); case SyntaxKind.NamespaceExportDeclaration: return getTargetOfNamespaceExportDeclaration(node as NamespaceExportDeclaration, dontRecursivelyResolve); case SyntaxKind.ShorthandPropertyAssignment: @@ -4468,13 +4510,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const typeOnlyResolution = typeOnlyDeclaration && ( typeOnlyDeclarationIsExportStar ? resolveExternalModuleName(typeOnlyDeclaration.moduleSpecifier, typeOnlyDeclaration.moduleSpecifier, /*ignoreErrors*/ true) - : resolveAlias(typeOnlyDeclaration.symbol)); + : resolveAlias(typeOnlyDeclaration.symbol) + ); const typeOnlyExportStarTargets = typeOnlyDeclarationIsExportStar && typeOnlyResolution ? getExportsOfModule(typeOnlyResolution) : undefined; let flags = excludeLocalMeanings ? SymbolFlags.None : symbol.flags; let seenSymbols; while (symbol.flags & SymbolFlags.Alias) { const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); - if (!typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || + if ( + !typeOnlyDeclarationIsExportStar && target === typeOnlyResolution || typeOnlyExportStarTargets?.get(target.escapedName) === target ) { break; @@ -4527,7 +4571,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { immediateTarget: Symbol | undefined, finalTarget: Symbol | undefined, overwriteEmpty: boolean, - exportStarDeclaration?: ExportDeclaration & { readonly isTypeOnly: true, readonly moduleSpecifier: Expression }, + exportStarDeclaration?: ExportDeclaration & { readonly isTypeOnly: true; readonly moduleSpecifier: Expression; }, exportStarName?: __String, ): boolean { if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) return false; @@ -4749,7 +4793,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error( containingQualifiedName, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, - entityNameToString(containingQualifiedName) + entityNameToString(containingQualifiedName), ); return undefined; } @@ -4761,7 +4805,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { name.parent.right, Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, symbolToString(exportedTypeSymbol), - unescapeLeadingUnderscores(name.parent.right.escapedText) + unescapeLeadingUnderscores(name.parent.right.escapedText), ); return undefined; } @@ -4817,9 +4861,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getDeclarationOfJSPrototypeContainer(symbol); } } - if (host && (isObjectLiteralMethod(host) || isPropertyAssignment(host)) && + if ( + host && (isObjectLiteralMethod(host) || isPropertyAssignment(host)) && isBinaryExpression(host.parent.parent) && - getAssignmentDeclarationKind(host.parent.parent) === AssignmentDeclarationKind.Prototype) { + getAssignmentDeclarationKind(host.parent.parent) === AssignmentDeclarationKind.Prototype + ) { // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration const symbol = getSymbolOfDeclaration(host.parent.parent.left as BindableStaticNameExpression); if (symbol) { @@ -4866,9 +4912,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function resolveExternalModuleName(location: Node, moduleReferenceExpression: Expression, ignoreErrors?: boolean): Symbol | undefined { const isClassic = getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic; - const errorMessage = isClassic? - Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option - : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; + const errorMessage = isClassic ? + Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option + : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : errorMessage); } @@ -4892,7 +4938,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const currentSourceFile = getSourceFileOfNode(location); const contextSpecifier = isStringLiteralLike(location) ? location - : findAncestor(location, isImportCall)?.arguments[0] || + : findAncestor(location, isImportCall)?.arguments[0] || findAncestor(location, isImportDeclaration)?.moduleSpecifier || findAncestor(location, isExternalModuleImportEqualsDeclaration)?.moduleReference.expression || findAncestor(location, isExportDeclaration)?.moduleSpecifier || @@ -4912,19 +4958,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) { - const importOrExport = - findAncestor(location, isImportDeclaration)?.importClause || + const importOrExport = findAncestor(location, isImportDeclaration)?.importClause || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); if (importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) { error( errorNode, Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead, - getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference)))); + getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference))), + ); } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { - const importOrExport = - findAncestor(location, isImportDeclaration)?.importClause || + const importOrExport = findAncestor(location, isImportDeclaration)?.importClause || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); if (!(importOrExport?.isTypeOnly || findAncestor(location, isImportTypeNode))) { const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); @@ -4960,13 +5005,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*details*/ undefined, Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, - combinePaths(scope.packageDirectory, "package.json")); + combinePaths(scope.packageDirectory, "package.json"), + ); } else { diagnosticDetails = chainDiagnosticMessages( /*details*/ undefined, Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, - combinePaths(scope.packageDirectory, "package.json")); + combinePaths(scope.packageDirectory, "package.json"), + ); } } else { @@ -4974,19 +5021,26 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { diagnosticDetails = chainDiagnosticMessages( /*details*/ undefined, Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, - targetExt); + targetExt, + ); } else { diagnosticDetails = chainDiagnosticMessages( /*details*/ undefined, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module); + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module, + ); } } } - diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, chainDiagnosticMessages( - diagnosticDetails, - Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, - moduleReference))); + diagnostics.add(createDiagnosticForNodeFromMessageChain( + getSourceFileOfNode(errorNode), + errorNode, + chainDiagnosticMessages( + diagnosticDetails, + Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, + moduleReference, + ), + )); } } } @@ -5045,19 +5099,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isExtensionlessRelativePathImport = pathIsRelative(moduleReference) && !hasExtension(moduleReference); const resolutionIsNode16OrNext = moduleResolutionKind === ModuleResolutionKind.Node16 || moduleResolutionKind === ModuleResolutionKind.NodeNext; - if (!getResolveJsonModule(compilerOptions) && + if ( + !getResolveJsonModule(compilerOptions) && fileExtensionIs(moduleReference, Extension.Json) && moduleResolutionKind !== ModuleResolutionKind.Classic && - hasJsonModuleEmitEnabled(compilerOptions)) { + hasJsonModuleEmitEnabled(compilerOptions) + ) { error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else if (mode === ModuleKind.ESNext && resolutionIsNode16OrNext && isExtensionlessRelativePathImport) { const absoluteRef = getNormalizedAbsolutePath(moduleReference, getDirectoryPath(currentSourceFile.path)); const suggestedExt = suggestedExtensions.find(([actualExt, _importExt]) => host.fileExists(absoluteRef + actualExt))?.[1]; if (suggestedExt) { - error(errorNode, - Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, - moduleReference + suggestedExt); + error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Did_you_mean_0, moduleReference + suggestedExt); } else { error(errorNode, Diagnostics.Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node16_or_nodenext_Consider_adding_an_extension_to_the_import_path); @@ -5078,8 +5132,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { */ if (emitModuleKindIsNonNodeESM(moduleKind) || mode === ModuleKind.ESNext) { const preferTs = isDeclarationFileName(moduleReference) && shouldAllowImportingTsExtension(compilerOptions); - const ext = - tsExtension === Extension.Mts || tsExtension === Extension.Dmts ? preferTs ? ".mts" : ".mjs" : + const ext = tsExtension === Extension.Mts || tsExtension === Extension.Dmts ? preferTs ? ".mts" : ".mjs" : tsExtension === Extension.Cts || tsExtension === Extension.Dmts ? preferTs ? ".cts" : ".cjs" : preferTs ? ".ts" : ".js"; return importSourceWithoutExtension + ext; @@ -5093,11 +5146,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!isExternalModuleNameRelative(moduleReference) && packageId) { errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); } - errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( - errorInfo, - Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, - moduleReference, - resolvedFileName)); + errorOrSuggestion( + isError, + errorNode, + chainDiagnosticMessages( + errorInfo, + Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, + moduleReference, + resolvedFileName, + ), + ); } function resolveExternalModuleSymbol(moduleSymbol: Symbol, dontResolveAlias?: boolean): Symbol; @@ -5270,10 +5328,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function shouldTreatPropertiesOfExternalModuleAsExports(resolvedExternalModuleType: Type) { return !(resolvedExternalModuleType.flags & TypeFlags.Primitive || - getObjectFlags(resolvedExternalModuleType) & ObjectFlags.Class || - // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path - isArrayType(resolvedExternalModuleType) || - isTupleType(resolvedExternalModuleType)); + getObjectFlags(resolvedExternalModuleType) & ObjectFlags.Class || + // `isArrayOrTupleLikeType` is too expensive to use in this auto-imports hot path + isArrayType(resolvedExternalModuleType) || + isTupleType(resolvedExternalModuleType)); } function getExportsOfSymbol(symbol: Symbol): SymbolTable { @@ -5313,7 +5371,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { target.set(id, sourceSymbol); if (lookupTable && exportNode) { lookupTable.set(id, { - specifierText: getTextOfNode(exportNode.moduleSpecifier!) + specifierText: getTextOfNode(exportNode.moduleSpecifier!), }); } } @@ -5331,7 +5389,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getExportsOfModuleWorker(moduleSymbol: Symbol) { const visitedSymbols: Symbol[] = []; - let typeOnlyExportStarMap: Map<__String, ExportDeclaration & { readonly isTypeOnly: true, readonly moduleSpecifier: Expression }> | undefined; + let typeOnlyExportStarMap: Map<__String, ExportDeclaration & { readonly isTypeOnly: true; readonly moduleSpecifier: Expression; }> | undefined; const nonTypeOnlyNames = new Set<__String>(); // A module defined by an 'export=' consists of one export that needs to be resolved @@ -5374,7 +5432,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { nestedSymbols, exportedSymbols, lookupTable, - node as ExportDeclaration + node as ExportDeclaration, ); } } @@ -5388,7 +5446,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node, Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable.get(id)!.specifierText, - unescapeLeadingUnderscores(id) + unescapeLeadingUnderscores(id), )); } }); @@ -5396,9 +5454,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (exportStar?.isTypeOnly) { typeOnlyExportStarMap ??= new Map(); - symbols.forEach((_, escapedName) => typeOnlyExportStarMap!.set( - escapedName, - exportStar as ExportDeclaration & { readonly isTypeOnly: true, readonly moduleSpecifier: Expression })); + symbols.forEach((_, escapedName) => + typeOnlyExportStarMap!.set( + escapedName, + exportStar as ExportDeclaration & { readonly isTypeOnly: true; readonly moduleSpecifier: Expression; }, + ) + ); } return symbols; } @@ -5486,23 +5547,23 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // we potentially have a symbol which is a member of the instance side of something - look for a variable in scope with the container's type // which may be acting like a namespace (eg, `Symbol` acts like a namespace when looking up `Symbol.toStringTag`) const firstVariableMatch = !(container.flags & getQualifiedLeftMeaning(meaning)) - && container.flags & SymbolFlags.Type - && getDeclaredTypeOfSymbol(container).flags & TypeFlags.Object - && meaning === SymbolFlags.Value - ? forEachSymbolTableInScope(enclosingDeclaration, t => { - return forEachEntry(t, s => { - if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { - return s; - } - }); - }) : undefined; + && container.flags & SymbolFlags.Type + && getDeclaredTypeOfSymbol(container).flags & TypeFlags.Object + && meaning === SymbolFlags.Value + ? forEachSymbolTableInScope(enclosingDeclaration, t => { + return forEachEntry(t, s => { + if (s.flags & getQualifiedLeftMeaning(meaning) && getTypeOfSymbol(s) === getDeclaredTypeOfSymbol(container)) { + return s; + } + }); + }) : undefined; let res = firstVariableMatch ? [firstVariableMatch, ...additionalContainers, container] : [...additionalContainers, container]; res = append(res, objectLiteralContainer); res = addRange(res, reexportContainers); return res; } const candidates = mapDefined(symbol.declarations, d => { - if (!isAmbientModule(d) && d.parent){ + if (!isAmbientModule(d) && d.parent) { // direct children of a module if (hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) { return getSymbolOfDeclaration(d.parent as Declaration); @@ -5589,7 +5650,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function symbolIsValue(symbol: Symbol, includeTypeOnlyMembers?: boolean): boolean { return !!( symbol.flags & SymbolFlags.Value || - symbol.flags & SymbolFlags.Alias && getSymbolFlags(symbol, !includeTypeOnlyMembers) & SymbolFlags.Value); + symbol.flags & SymbolFlags.Alias && getSymbolFlags(symbol, !includeTypeOnlyMembers) & SymbolFlags.Value + ); } function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration | undefined { @@ -5690,8 +5752,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function createAnonymousType(symbol: Symbol | undefined, members: SymbolTable, callSignatures: readonly Signature[], constructSignatures: readonly Signature[], indexInfos: readonly IndexInfo[]): ResolvedType { - return setStructuredTypeMembers(createObjectType(ObjectFlags.Anonymous, symbol), - members, callSignatures, constructSignatures, indexInfos); + return setStructuredTypeMembers(createObjectType(ObjectFlags.Anonymous, symbol), members, callSignatures, constructSignatures, indexInfos); } function getResolvedTypeWithoutAbstractConstructSignatures(type: ResolvedType) { @@ -5704,7 +5765,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type.members, type.callSignatures, some(constructSignatures) ? constructSignatures : emptyArray, - type.indexInfos); + type.indexInfos, + ); type.objectTypeWithoutAbstractConstructSignatures = typeCopy; typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy; return typeCopy; @@ -5825,7 +5887,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Check if symbol is any of the aliases in scope const result = forEachEntry(symbols, symbolFromSymbolTable => { - if (symbolFromSymbolTable.flags & SymbolFlags.Alias + if ( + symbolFromSymbolTable.flags & SymbolFlags.Alias && symbolFromSymbolTable.escapedName !== InternalSymbolName.ExportEquals && symbolFromSymbolTable.escapedName !== InternalSymbolName.Default && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration))) @@ -5837,7 +5900,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // See similar comment in `resolveName` for details && (ignoreQualification || !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier)) ) { - const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); const candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification); if (candidate) { @@ -5886,7 +5948,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // Qualify if the symbol from symbol table has same meaning as expected - const shouldResolveAlias = (symbolFromSymbolTable.flags & SymbolFlags.Alias && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier)); + const shouldResolveAlias = symbolFromSymbolTable.flags & SymbolFlags.Alias && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier); symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; const flags = shouldResolveAlias ? getSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; if (flags & meaning) { @@ -5961,7 +6023,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // Any meaning of a module symbol is always accessible via an `import` type return { - accessibility: SymbolAccessibility.Accessible + accessibility: SymbolAccessibility.Accessible, }; } } @@ -5988,7 +6050,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (earlyModuleBail) { return { - accessibility: SymbolAccessibility.Accessible + accessibility: SymbolAccessibility.Accessible, }; } @@ -6072,28 +6134,36 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // because these kind of aliases can be used to name types in declaration file const anyImportSyntax = getAnyImportSyntax(declaration); - if (anyImportSyntax && + if ( + anyImportSyntax && !hasSyntacticModifier(anyImportSyntax, ModifierFlags.Export) && // import clause without export - isDeclarationVisible(anyImportSyntax.parent)) { + isDeclarationVisible(anyImportSyntax.parent) + ) { return addVisibleAlias(declaration, anyImportSyntax); } - else if (isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && + else if ( + isVariableDeclaration(declaration) && isVariableStatement(declaration.parent.parent) && !hasSyntacticModifier(declaration.parent.parent, ModifierFlags.Export) && // unexported variable statement - isDeclarationVisible(declaration.parent.parent.parent)) { + isDeclarationVisible(declaration.parent.parent.parent) + ) { return addVisibleAlias(declaration, declaration.parent.parent); } - else if (isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + else if ( + isLateVisibilityPaintedStatement(declaration) // unexported top-level statement && !hasSyntacticModifier(declaration, ModifierFlags.Export) - && isDeclarationVisible(declaration.parent)) { + && isDeclarationVisible(declaration.parent) + ) { return addVisibleAlias(declaration, declaration); } else if (isBindingElement(declaration)) { - if (symbol.flags & SymbolFlags.Alias && isInJSFile(declaration) && declaration.parent?.parent // exported import-like top-level JS require statement + if ( + symbol.flags & SymbolFlags.Alias && isInJSFile(declaration) && declaration.parent?.parent // exported import-like top-level JS require statement && isVariableDeclaration(declaration.parent.parent) && declaration.parent.parent.parent?.parent && isVariableStatement(declaration.parent.parent.parent.parent) && !hasSyntacticModifier(declaration.parent.parent.parent.parent, ModifierFlags.Export) && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file) - && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) { + && isDeclarationVisible(declaration.parent.parent.parent.parent.parent) + ) { return addVisibleAlias(declaration, declaration.parent.parent.parent.parent); } else if (symbol.flags & SymbolFlags.BlockScopedVariable) { @@ -6130,14 +6200,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult { // get symbol of the first identifier of the entityName let meaning: SymbolFlags; - if (entityName.parent.kind === SyntaxKind.TypeQuery || + if ( + entityName.parent.kind === SyntaxKind.TypeQuery || entityName.parent.kind === SyntaxKind.ExpressionWithTypeArguments && !isPartOfTypeNode(entityName.parent) || - entityName.parent.kind === SyntaxKind.ComputedPropertyName) { + entityName.parent.kind === SyntaxKind.ComputedPropertyName + ) { // Typeof value meaning = SymbolFlags.Value | SymbolFlags.ExportValue; } - else if (entityName.kind === SyntaxKind.QualifiedName || entityName.kind === SyntaxKind.PropertyAccessExpression || - entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration) { + else if ( + entityName.kind === SyntaxKind.QualifiedName || entityName.kind === SyntaxKind.PropertyAccessExpression || + entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration + ) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = SymbolFlags.Namespace; @@ -6160,7 +6234,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: SymbolAccessibility.NotAccessible, errorSymbolName: getTextOfNode(firstIdentifier), - errorNode: firstIdentifier + errorNode: firstIdentifier, }; } @@ -6261,26 +6335,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function createNodeBuilder() { return { - typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => typeToTypeNodeHelper(type, context)), - indexInfoToIndexSignatureDeclaration: (indexInfo: IndexInfo, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, /*typeNode*/ undefined)), - signatureToSignatureDeclaration: (signature: Signature, kind: SignatureDeclaration["kind"], enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => signatureToSignatureDeclarationHelper(signature, kind, context)), - symbolToEntityName: (symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false)), - symbolToExpression: (symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => symbolToExpression(symbol, context, meaning)), - symbolToTypeParameterDeclarations: (symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => typeParametersToTypeParameterDeclarations(symbol, context)), - symbolToParameterDeclaration: (symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => symbolToParameterDeclaration(symbol, context)), - typeParameterToDeclaration: (parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => typeParameterToDeclaration(parameter, context)), - symbolTableToDeclarationStatements: (symbolTable: SymbolTable, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker, bundled?: boolean) => - withContext(enclosingDeclaration, flags, tracker, context => symbolTableToDeclarationStatements(symbolTable, context, bundled)), - symbolToNode: (symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => - withContext(enclosingDeclaration, flags, tracker, context => symbolToNode(symbol, context, meaning)), + typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => typeToTypeNodeHelper(type, context)), + indexInfoToIndexSignatureDeclaration: (indexInfo: IndexInfo, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => indexInfoToIndexSignatureDeclarationHelper(indexInfo, context, /*typeNode*/ undefined)), + signatureToSignatureDeclaration: (signature: Signature, kind: SignatureDeclaration["kind"], enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => signatureToSignatureDeclarationHelper(signature, kind, context)), + symbolToEntityName: (symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false)), + symbolToExpression: (symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => symbolToExpression(symbol, context, meaning)), + symbolToTypeParameterDeclarations: (symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => typeParametersToTypeParameterDeclarations(symbol, context)), + symbolToParameterDeclaration: (symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => symbolToParameterDeclaration(symbol, context)), + typeParameterToDeclaration: (parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => typeParameterToDeclaration(parameter, context)), + symbolTableToDeclarationStatements: (symbolTable: SymbolTable, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker, bundled?: boolean) => withContext(enclosingDeclaration, flags, tracker, context => symbolTableToDeclarationStatements(symbolTable, context, bundled)), + symbolToNode: (symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker) => withContext(enclosingDeclaration, flags, tracker, context => symbolToNode(symbol, context, meaning)), }; function symbolToNode(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags) { @@ -6291,8 +6355,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const nameType = getSymbolLinks(symbol).nameType; if (nameType && nameType.flags & (TypeFlags.EnumLiteral | TypeFlags.UniqueESSymbol)) { - context.enclosingDeclaration = nameType.symbol.valueDeclaration; - return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning)); + context.enclosingDeclaration = nameType.symbol.valueDeclaration; + return factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, meaning)); } } return symbolToExpression(symbol, context, meaning); @@ -6300,8 +6364,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function withContext(enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker: SymbolTracker | undefined, cb: (context: NodeBuilderContext) => T): T | undefined { Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & NodeFlags.Synthesized) === 0); - const moduleResolverHost = - tracker?.trackSymbol ? tracker.moduleResolverHost : + const moduleResolverHost = tracker?.trackSymbol ? tracker.moduleResolverHost : flags! & NodeBuilderFlags.DoNotIncludeSymbolChain ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : undefined; const context: NodeBuilderContext = { @@ -6313,7 +6376,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { visitedTypes: undefined, symbolDepth: undefined, inferTypeParameters: undefined, - approximateLength: 0 + approximateLength: 0, }; context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost); const resultingNode = cb(context); @@ -6395,7 +6458,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isIdentifierText(memberName, ScriptTarget.ES3)) { return appendReferenceToType( parentName as TypeReferenceNode | ImportTypeNode, - factory.createTypeReferenceNode(memberName, /*typeArguments*/ undefined) + factory.createTypeReferenceNode(memberName, /*typeArguments*/ undefined), ); } if (isImportTypeNode(parentName)) { @@ -6412,7 +6475,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return symbolToTypeNode(type.symbol, context, SymbolFlags.Type); } if (type.flags & TypeFlags.StringLiteral) { - context.approximateLength += ((type as StringLiteralType).value.length + 2); + context.approximateLength += (type as StringLiteralType).value.length + 2; return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral((type as StringLiteralType).value, !!(context.flags & NodeBuilderFlags.UseSingleQuotesForStringLiteralType)), EmitFlags.NoAsciiEscaping)); } if (type.flags & TypeFlags.NumberLiteral) { @@ -6422,7 +6485,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (type.flags & TypeFlags.BigIntLiteral) { context.approximateLength += (pseudoBigIntToString((type as BigIntLiteralType).value).length) + 1; - return factory.createLiteralTypeNode((factory.createBigIntLiteral((type as BigIntLiteralType).value))); + return factory.createLiteralTypeNode(factory.createBigIntLiteral((type as BigIntLiteralType).value)); } if (type.flags & TypeFlags.BooleanLiteral) { context.approximateLength += (type as IntrinsicType).intrinsicName.length; @@ -6493,7 +6556,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (type.flags & TypeFlags.TypeParameter || objectFlags & ObjectFlags.ClassOrInterface) { if (type.flags & TypeFlags.TypeParameter && contains(context.inferTypeParameters, type)) { - context.approximateLength += (symbolName(type.symbol).length + 6); + context.approximateLength += symbolName(type.symbol).length + 6; let constraintNode: TypeNode | undefined; const constraint = getConstraintOfTypeParameter(type as TypeParameter); if (constraint) { @@ -6509,9 +6572,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } return factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type as TypeParameter, context, constraintNode)); } - if (context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams && + if ( + context.flags & NodeBuilderFlags.GenerateNamesForShadowedTypeParams && type.flags & TypeFlags.TypeParameter && - !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration) + ) { const name = typeParameterToName(type, context); context.approximateLength += idText(name).length; return factory.createTypeReferenceNode(factory.createIdentifier(idText(name)), /*typeArguments*/ undefined); @@ -6559,9 +6624,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const types = (type as TemplateLiteralType).types; const templateHead = factory.createTemplateHead(texts[0]); const templateSpans = factory.createNodeArray( - map(types, (t, i) => factory.createTemplateLiteralTypeSpan( - typeToTypeNodeHelper(t, context), - (i < types.length - 1 ? factory.createTemplateMiddle : factory.createTemplateTail)(texts[i + 1])))); + map(types, (t, i) => + factory.createTemplateLiteralTypeSpan( + typeToTypeNodeHelper(t, context), + (i < types.length - 1 ? factory.createTemplateMiddle : factory.createTemplateTail)(texts[i + 1]), + )), + ); context.approximateLength += 2; return factory.createTemplateLiteralType(templateHead, templateSpans); } @@ -6584,7 +6652,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return Debug.fail("Should be unreachable."); - function conditionalTypeToTypeNode(type: ConditionalType) { const checkTypeNode = typeToTypeNodeHelper(type.checkType, context); context.approximateLength += 15; @@ -6601,7 +6668,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const trueTypeNode = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type.root.node.trueType), newMapper)); const falseTypeNode = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type.root.node.falseType), newMapper)); - // outermost conditional makes `T` a type parameter, allowing the inner conditionals to be distributive // second conditional makes `T` have `T & checkType` substitution, so it is correctly usable as the checkType // inner conditional runs the check the user provided on the check type (distributively) and returns the result @@ -6619,9 +6685,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { factory.createTypeReferenceNode(factory.cloneNode(name)), typeToTypeNodeHelper(type.checkType, context), factory.createConditionalTypeNode(newTypeVariable, extendsTypeNode, trueTypeNode, falseTypeNode), - factory.createKeywordTypeNode(SyntaxKind.NeverKeyword) + factory.createKeywordTypeNode(SyntaxKind.NeverKeyword), ), - factory.createKeywordTypeNode(SyntaxKind.NeverKeyword) + factory.createKeywordTypeNode(SyntaxKind.NeverKeyword), ); } const saveInferTypeParameters = context.inferTypeParameters; @@ -6702,7 +6768,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration(/*modifiers*/ undefined, factory.cloneNode(newTypeVariable!.typeName) as Identifier, originalConstraint.flags & TypeFlags.Unknown ? undefined : typeToTypeNodeHelper(originalConstraint, context))), result, - factory.createKeywordTypeNode(SyntaxKind.NeverKeyword) + factory.createKeywordTypeNode(SyntaxKind.NeverKeyword), ); } else if (needsModifierPreservingWrapper) { @@ -6714,7 +6780,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration(/*modifiers*/ undefined, factory.cloneNode(newTypeVariable!.typeName) as Identifier, factory.createTypeOperatorNode(SyntaxKind.KeyOfKeyword, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)))), result, - factory.createKeywordTypeNode(SyntaxKind.NeverKeyword) + factory.createKeywordTypeNode(SyntaxKind.NeverKeyword), ); } return result; @@ -6730,11 +6796,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects - else if (symbol.flags & SymbolFlags.Class - && !getBaseTypeVariableOfClass(symbol) - && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== SymbolAccessibility.Accessible)) || + else if ( + symbol.flags & SymbolFlags.Class + && !getBaseTypeVariableOfClass(symbol) + && !(symbol.valueDeclaration && isClassLike(symbol.valueDeclaration) && context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral && (!isClassDeclaration(symbol.valueDeclaration) || isSymbolAccessible(symbol, context.enclosingDeclaration, isInstanceType, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== SymbolAccessibility.Accessible)) || symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule) || - shouldWriteTypeOfFunctionSymbol()) { + shouldWriteTypeOfFunctionSymbol() + ) { return symbolToTypeNode(symbol, context, isInstanceType); } else if (context.visitedTypes?.has(typeId)) { @@ -6771,12 +6839,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return createTypeNodeFromObjectType(type); } function shouldWriteTypeOfFunctionSymbol() { - const isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method) && // typeof static method + const isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method) && // typeof static method some(symbol.declarations, declaration => isStatic(declaration)); const isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) && (symbol.parent || // is exported function symbol - forEach(symbol.declarations, declaration => - declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock)); + forEach(symbol.declarations, declaration => declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock)); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions return (!!(context.flags & NodeBuilderFlags.UseTypeOfFunction) || (context.visitedTypes?.has(typeId))) && // it is type of the symbol uses itself recursively @@ -6875,7 +6942,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const signature = resolved.callSignatures[0]; const signatureNode = signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType, context) as FunctionTypeNode; return signatureNode; - } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { @@ -6889,8 +6955,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (some(abstractSignatures)) { const types = map(abstractSignatures, getOrCreateTypeFromSignature); // count the number of type elements excluding abstract constructors - const typeElementCount = - resolved.callSignatures.length + + const typeElementCount = resolved.callSignatures.length + (resolved.constructSignatures.length - abstractSignatures.length) + resolved.indexInfos.length + // exclude `prototype` when writing a class expression as a type literal, as per @@ -6946,12 +7011,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { factory.createIdentifier(unescapeLeadingUnderscores(getTupleElementLabel(labeledElementDeclaration))), flags & ElementFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, flags & ElementFlags.Rest ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : - tupleConstituentNodes[i] + tupleConstituentNodes[i], ); } else { - tupleConstituentNodes[i] = - flags & ElementFlags.Variable ? factory.createRestTypeNode(flags & ElementFlags.Rest ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : + tupleConstituentNodes[i] = flags & ElementFlags.Variable ? factory.createRestTypeNode(flags & ElementFlags.Rest ? factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) : flags & ElementFlags.Optional ? factory.createOptionalTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]; } @@ -6967,7 +7031,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { context.encounteredError = true; return undefined!; // TODO: GH#18217 } - else if (context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral && + else if ( + context.flags & NodeBuilderFlags.WriteClassExpressionAsTypeLiteral && type.symbol.valueDeclaration && isClassLike(type.symbol.valueDeclaration) && !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration) @@ -6986,7 +7051,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const parent = getParentSymbolOfTypeParameter(outerTypeParameters[i])!; do { i++; - } while (i < length && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } + while (i < length && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -7012,7 +7078,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - function appendReferenceToType(root: TypeReferenceNode | ImportTypeNode, ref: TypeReferenceNode): TypeReferenceNode | ImportTypeNode { if (isImportTypeNode(root)) { // first shift type arguments @@ -7026,9 +7091,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else { if (typeArguments !== getIdentifierTypeArguments(qualifier.right)) { - qualifier = factory.updateQualifiedName(qualifier, - qualifier.left, - setIdentifierTypeArguments(factory.cloneNode(qualifier.right), typeArguments)); + qualifier = factory.updateQualifiedName(qualifier, qualifier.left, setIdentifierTypeArguments(factory.cloneNode(qualifier.right), typeArguments)); } } } @@ -7044,7 +7107,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { root.assertions, qualifier, typeArguments, - root.isTypeOf); + root.isTypeOf, + ); } else { // first shift type arguments @@ -7057,9 +7121,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else { if (typeArguments !== getIdentifierTypeArguments(typeName.right)) { - typeName = factory.updateQualifiedName(typeName, - typeName.left, - setIdentifierTypeArguments(factory.cloneNode(typeName.right), typeArguments)); + typeName = factory.updateQualifiedName(typeName, typeName.left, setIdentifierTypeArguments(factory.cloneNode(typeName.right), typeArguments)); } } typeArguments = ref.typeArguments; @@ -7071,7 +7133,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return factory.updateTypeReferenceNode( root, typeName, - typeArguments); + typeArguments, + ); } } @@ -7124,7 +7187,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; } addPropertyToElementList(propertySymbol, context, typeElements); - } return typeElements.length ? typeElements : undefined; } @@ -7183,7 +7245,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { context.enclosingDeclaration = propertySymbol.valueDeclaration || propertySymbol.declarations?.[0] || saveEnclosingDeclaration; const propertyName = getPropertyNameNodeForSymbol(propertySymbol, context); context.enclosingDeclaration = saveEnclosingDeclaration; - context.approximateLength += (symbolName(propertySymbol).length + 1); + context.approximateLength += symbolName(propertySymbol).length + 1; const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined; if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { const signatures = getSignaturesOfType(filterType(propertyType, t => !(t.flags & TypeFlags.Undefined)), SignatureKind.Call); @@ -7218,7 +7280,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { modifiers, propertyName, optionalToken, - propertyTypeNode); + propertyTypeNode, + ); typeElements.push(preserveCommentsOn(propertySignature)); @@ -7248,7 +7311,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return [ typeToTypeNodeHelper(types[0], context), factory.createTypeReferenceNode(`... ${types.length - 2} more ...`, /*typeArguments*/ undefined), - typeToTypeNodeHelper(types[types.length - 1], context) + typeToTypeNodeHelper(types[types.length - 1], context), ]; } } @@ -7317,18 +7380,20 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { name, /*questionToken*/ undefined, indexerTypeNode, - /*initializer*/ undefined); + /*initializer*/ undefined, + ); if (!typeNode) { typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); } if (!indexInfo.type && !(context.flags & NodeBuilderFlags.AllowEmptyIndexInfoType)) { context.encounteredError = true; } - context.approximateLength += (name.length + 4); + context.approximateLength += name.length + 4; return factory.createIndexSignature( indexInfo.isReadonly ? [factory.createToken(SyntaxKind.ReadonlyKeyword)] : undefined, [indexingParameter], - typeNode); + typeNode, + ); } interface SignatureToSignatureDeclarationOptions { @@ -7467,8 +7532,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { modifiers = factory.createModifiersFromModifierFlags(flags | ModifierFlags.Abstract); } - const node = - kind === SyntaxKind.CallSignature ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : + const node = kind === SyntaxKind.CallSignature ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === SyntaxKind.ConstructSignature ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === SyntaxKind.MethodSignature ? factory.createMethodSignature(modifiers, options?.name ?? factory.createIdentifier(""), options?.questionToken, typeParameters, parameters, returnTypeNode) : kind === SyntaxKind.MethodDeclaration ? factory.createMethodDeclaration(modifiers, /*asteriskToken*/ undefined, options?.name ?? factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) : @@ -7508,7 +7572,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*dotDotDotToken*/ undefined, "this", /*questionToken*/ undefined, - typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context) + typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context), ); } } @@ -7547,8 +7611,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const dotDotDotToken = isRest ? factory.createToken(SyntaxKind.DotDotDotToken) : undefined; const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === SyntaxKind.Identifier ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : - parameterDeclaration.name.kind === SyntaxKind.QualifiedName ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), EmitFlags.NoAsciiEscaping) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === SyntaxKind.QualifiedName ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), EmitFlags.NoAsciiEscaping) : + cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & CheckFlags.OptionalParameter; @@ -7559,7 +7623,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { name, questionToken, parameterTypeNode, - /*initializer*/ undefined); + /*initializer*/ undefined, + ); context.approximateLength += symbolName(parameterSymbol).length + 3; return parameterNode; @@ -7576,7 +7641,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { visited.dotDotDotToken, visited.propertyName, visited.name, - /*initializer*/ undefined); + /*initializer*/ undefined, + ); } if (!nodeIsSynthesized(visited)) { visited = factory.cloneNode(visited); @@ -7618,24 +7684,28 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getSymbolChain(symbol: Symbol, meaning: SymbolFlags, endOfChain: boolean): Symbol[] | undefined { let accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & NodeBuilderFlags.UseOnlyExternalAliasing)); let parentSpecifiers: (string | undefined)[]; - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - + if ( + !accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning)) + ) { // Go up and add our parent. const parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration, meaning); if (length(parents)) { parentSpecifiers = parents!.map(symbol => some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol) ? getSpecifierForModuleSymbol(symbol, context) - : undefined); + : undefined + ); const indices = parents!.map((_, i) => i); indices.sort(sortByBestName); const sortedParents = indices.map(i => parents![i]); for (const parent of sortedParents) { const parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { - if (parent.exports && parent.exports.get(InternalSymbolName.ExportEquals) && - getSymbolIfSameReference(parent.exports.get(InternalSymbolName.ExportEquals)!, symbol)) { + if ( + parent.exports && parent.exports.get(InternalSymbolName.ExportEquals) && + getSymbolIfSameReference(parent.exports.get(InternalSymbolName.ExportEquals)!, symbol) + ) { // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent // No need to lookup an alias for the symbol in itself accessibleSymbolChain = parentChain; @@ -7655,7 +7725,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral))) { + !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral)) + ) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) if (!endOfChain && !yieldModuleSymbol && !!forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { return; @@ -7707,7 +7778,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const nextSymbol = chain[index + 1]; if (getCheckFlags(nextSymbol) & CheckFlags.Instantiated) { const params = getTypeParametersOfClassOrInterface( - parentSymbol.flags & SymbolFlags.Alias ? resolveAlias(parentSymbol) : parentSymbol + parentSymbol.flags & SymbolFlags.Alias ? resolveAlias(parentSymbol) : parentSymbol, ); // NOTE: cast to TransientSymbol should be safe because only TransientSymbol can have CheckFlags.Instantiated typeParameterNodes = mapToTypeNodes(map(params, t => getMappedType(t, (nextSymbol as TransientSymbol).links.mapper!)), context); @@ -7786,7 +7857,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { : resolutionMode === ModuleKind.ESNext ? "js" : undefined, }, - { overrideImportMode } + { overrideImportMode }, )); links.specifierCache ??= new Map(); links.specifierCache.set(cacheKey, specifier); @@ -7818,8 +7889,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { assertion = factory.createImportTypeAssertionContainer(factory.createAssertClause(factory.createNodeArray([ factory.createAssertEntry( factory.createStringLiteral("resolution-mode"), - factory.createStringLiteral("import") - ) + factory.createStringLiteral("import"), + ), ]))); context.tracker.reportImportTypeNodeResolutionModeOverride?.(); } @@ -7842,8 +7913,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { assertion = factory.createImportTypeAssertionContainer(factory.createAssertClause(factory.createNodeArray([ factory.createAssertEntry( factory.createStringLiteral("resolution-mode"), - factory.createStringLiteral(swappedMode === ModuleKind.ESNext ? "import" : "require") - ) + factory.createStringLiteral(swappedMode === ModuleKind.ESNext ? "import" : "require"), + ), ]))); context.tracker.reportImportTypeNodeResolutionModeOverride?.(); } @@ -7926,9 +7997,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } context.approximateLength += symbolName.length + 1; - if (!(context.flags & NodeBuilderFlags.ForbidIndexedAccessSymbolReferences) && parent && + if ( + !(context.flags & NodeBuilderFlags.ForbidIndexedAccessSymbolReferences) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) && - getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName)!, symbol)) { + getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName)!, symbol) + ) { // Should use an indexed access const LHS = createAccessFromSymbolChain(chain, index - 1, stopper); if (isIndexedAccessTypeNode(LHS)) { @@ -8003,9 +8076,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function symbolToName(symbol: Symbol, context: NodeBuilderContext, meaning: SymbolFlags, expectsIdentifier: boolean): EntityName { const chain = lookupSymbolChain(symbol, context, meaning); - if (expectsIdentifier && chain.length !== 1 + if ( + expectsIdentifier && chain.length !== 1 && !context.encounteredError - && !(context.flags & NodeBuilderFlags.AllowQualifiedNameInPlaceOfIdentifier)) { + && !(context.flags & NodeBuilderFlags.AllowQualifiedNameInPlaceOfIdentifier) + ) { context.encounteredError = true; } return createEntityNameFromSymbolChain(chain, chain.length - 1); @@ -8065,7 +8140,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } let expression: Expression | undefined; if (isSingleOrDoubleQuote(firstChar) && !(symbol.flags & SymbolFlags.EnumMember)) { - expression = factory.createStringLiteral(stripQuotes(symbolName).replace(/\\./g, s => s.substring(1)), firstChar === CharacterCodes.singleQuote); + expression = factory.createStringLiteral(stripQuotes(symbolName).replace(/\\./g, s => s.substring(1)), firstChar === CharacterCodes.singleQuote); } else if (("" + +symbolName) === symbolName) { expression = factory.createNumericLiteral(+symbolName); @@ -8156,7 +8231,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return initial; } - function getDeclarationWithTypeAnnotation(symbol: Symbol, enclosingDeclaration: Node | undefined) { return symbol.declarations && find(symbol.declarations, s => !!getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, n => n === enclosingDeclaration))); } @@ -8188,8 +8262,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } const oldFlags = context.flags; - if (type.flags & TypeFlags.UniqueESSymbol && - type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, d => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration!)))) { + if ( + type.flags & TypeFlags.UniqueESSymbol && + type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, d => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration!))) + ) { context.flags |= NodeBuilderFlags.AllowUniqueESSymbolType; } const result = typeToTypeNodeHelper(type, context); @@ -8295,7 +8371,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*modifiers*/ undefined, name, t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(SyntaxKind.QuestionToken) : undefined, - overrideTypeNode || (t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode)) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) + overrideTypeNode || (t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode)) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword), ); })); } @@ -8306,13 +8382,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return factory.createTypeLiteralNode([factory.createIndexSignature( /*modifiers*/ undefined, [factory.createParameterDeclaration( - /*modifiers*/ undefined, + /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "x", /*questionToken*/ undefined, - visitNode(node.typeArguments![0], visitExistingNodeTreeSymbols, isTypeNode) + visitNode(node.typeArguments![0], visitExistingNodeTreeSymbols, isTypeNode), )], - visitNode(node.typeArguments![1], visitExistingNodeTreeSymbols, isTypeNode) + visitNode(node.typeArguments![1], visitExistingNodeTreeSymbols, isTypeNode), )]); } if (isJSDocFunctionType(node)) { @@ -8321,29 +8397,31 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return factory.createConstructorTypeNode( /*modifiers*/ undefined, visitNodes(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), - mapDefined(node.parameters, (p, i) => p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, undefined) : factory.createParameterDeclaration( - /*modifiers*/ undefined, - getEffectiveDotDotDotForParameter(p), - getNameForJSDocFunctionParameter(p, i), - p.questionToken, - visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), - /*initializer*/ undefined - )), - visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) + mapDefined(node.parameters, (p, i) => + p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, undefined) : factory.createParameterDeclaration( + /*modifiers*/ undefined, + getEffectiveDotDotDotForParameter(p), + getNameForJSDocFunctionParameter(p, i), + p.questionToken, + visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), + /*initializer*/ undefined, + )), + visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword), ); } else { return factory.createFunctionTypeNode( visitNodes(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), - map(node.parameters, (p, i) => factory.createParameterDeclaration( - /*modifiers*/ undefined, - getEffectiveDotDotDotForParameter(p), - getNameForJSDocFunctionParameter(p, i), - p.questionToken, - visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), - /*initializer*/ undefined - )), - visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) + map(node.parameters, (p, i) => + factory.createParameterDeclaration( + /*modifiers*/ undefined, + getEffectiveDotDotDotForParameter(p), + getNameForJSDocFunctionParameter(p, i), + p.questionToken, + visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), + /*initializer*/ undefined, + )), + visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword), ); } } @@ -8352,7 +8430,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (isLiteralImportTypeNode(node)) { const nodeSymbol = getNodeLinks(node).resolvedSymbol; - if (isInJSDoc(node) && + if ( + isInJSDoc(node) && nodeSymbol && ( // The import type resolved using jsdoc fallback logic @@ -8369,7 +8448,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node.assertions, node.qualifier, visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode), - node.isTypeOf + node.isTypeOf, ); } @@ -8407,7 +8486,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const resolverHost = { getCanonicalFileName, getCurrentDirectory: () => context.tracker.moduleResolverHost!.getCurrentDirectory(), - getCommonSourceDirectory: () => context.tracker.moduleResolverHost!.getCommonSourceDirectory() + getCommonSourceDirectory: () => context.tracker.moduleResolverHost!.getCommonSourceDirectory(), }; const newName = getResolvedExternalModuleName(resolverHost, targetFile); return factory.createStringLiteral(newName); @@ -8502,9 +8581,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const exportAssignment = find(statements, isExportAssignment); const nsIndex = findIndex(statements, isModuleDeclaration); let ns = nsIndex !== -1 ? statements[nsIndex] as ModuleDeclaration : undefined; - if (ns && exportAssignment && exportAssignment.isExportEquals && + if ( + ns && exportAssignment && exportAssignment.isExportEquals && isIdentifier(exportAssignment.expression) && isIdentifier(ns.name) && idText(ns.name) === idText(exportAssignment.expression) && - ns.body && isModuleBlock(ns.body)) { + ns.body && isModuleBlock(ns.body) + ) { // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from // the top-level exports and exporting them in the targeted ns, as can occur when a js file has both typedefs and `module.export` assignments const excessExports = filter(statements, s => !!(getEffectiveModifierFlags(s) & ModifierFlags.Export)); @@ -8517,13 +8598,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { ns.name, body = factory.updateModuleBlock( body, - factory.createNodeArray([...ns.body.statements, factory.createExportDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createNamedExports(map(flatMap(excessExports, e => getNamesOfDeclaration(e)), id => factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, id))), - /*moduleSpecifier*/ undefined - )]) - ) + factory.createNodeArray([ + ...ns.body.statements, + factory.createExportDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createNamedExports(map(flatMap(excessExports, e => getNamesOfDeclaration(e)), id => factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, id))), + /*moduleSpecifier*/ undefined, + ), + ]), + ), ); statements = [...statements.slice(0, nsIndex), ns, ...statements.slice(nsIndex + 1)]; } @@ -8548,12 +8632,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const exports = filter(statements, d => isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)) as ExportDeclaration[]; if (length(exports) > 1) { const nonExports = filter(statements, d => !isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause); - statements = [...nonExports, factory.createExportDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createNamedExports(flatMap(exports, e => cast(e.exportClause, isNamedExports).elements)), - /*moduleSpecifier*/ undefined - )]; + statements = [ + ...nonExports, + factory.createExportDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createNamedExports(flatMap(exports, e => cast(e.exportClause, isNamedExports).elements)), + /*moduleSpecifier*/ undefined, + ), + ]; } // Pass 2b: Also combine all `export {} from "..."` declarations as needed const reexports = filter(statements, d => isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && isNamedExports(d.exportClause)) as ExportDeclaration[]; @@ -8569,8 +8656,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports(flatMap(group, e => cast(e.exportClause, isNamedExports).elements)), - group[0].moduleSpecifier - ) + group[0].moduleSpecifier, + ), ]; } } @@ -8583,7 +8670,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Pass 3: Move all `export {}`'s to `export` modifiers where possible const index = findIndex(statements, d => isExportDeclaration(d) && !d.moduleSpecifier && !d.assertClause && !!d.exportClause && isNamedExports(d.exportClause)); if (index >= 0) { - const exportDecl = statements[index] as ExportDeclaration & { readonly exportClause: NamedExports }; + const exportDecl = statements[index] as ExportDeclaration & { readonly exportClause: NamedExports; }; const replacements = mapDefined(exportDecl.exportClause.elements, e => { if (!e.propertyName) { // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it @@ -8610,10 +8697,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { exportDecl.isTypeOnly, factory.updateNamedExports( exportDecl.exportClause, - replacements + replacements, ), exportDecl.moduleSpecifier, - exportDecl.assertClause + exportDecl.assertClause, ); } } @@ -8627,9 +8714,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Not a cleanup, but as a final step: If there is a mix of `export` and non-`export` declarations, but no `export =` or `export {}` add a `export {};` so // declaration privacy is respected. - if (enclosingDeclaration && + if ( + enclosingDeclaration && ((isSourceFile(enclosingDeclaration) && isExternalOrCommonJsModule(enclosingDeclaration)) || isModuleDeclaration(enclosingDeclaration)) && - (!some(statements, isExternalModuleIndicator) || (!hasScopeMarker(statements) && some(statements, needsScopeMarker)))) { + (!some(statements, isExternalModuleIndicator) || (!hasScopeMarker(statements) && some(statements, needsScopeMarker))) + ) { statements.push(createEmptyExports(factory)); } return statements; @@ -8684,7 +8773,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias // or a merge of some number of those. // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping @@ -8704,7 +8792,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; // If we need to emit a private with a keyword name, we're done for, since something else will try to refer to it by that name } let needsPostExportDefault = isDefault && !!( - symbol.flags & SymbolFlags.ExportDoesNotSupportDefaultModifier + symbol.flags & SymbolFlags.ExportDoesNotSupportDefaultModifier || (symbol.flags & SymbolFlags.Function && length(getPropertiesOfType(getTypeOfSymbol(symbol)))) ) && !(symbol.flags & SymbolFlags.Alias); // An alias symbol should preclude needing to make an alias ourselves let needsExportDeclaration = !needsPostExportDefault && !isPrivate && isStringANonContextualKeyword(symbolName) && !isDefault; @@ -8725,12 +8813,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // Need to skip over export= symbols below - json source files get a single `Property` flagged // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is. - if (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.FunctionScopedVariable | SymbolFlags.Property | SymbolFlags.Accessor) + if ( + symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.FunctionScopedVariable | SymbolFlags.Property | SymbolFlags.Accessor) && symbol.escapedName !== InternalSymbolName.ExportEquals && !(symbol.flags & SymbolFlags.Prototype) && !(symbol.flags & SymbolFlags.Class) && !(symbol.flags & SymbolFlags.Method) - && !isConstMergedWithNSPrintableAsSignatureMerge) { + && !isConstMergedWithNSPrintableAsSignatureMerge + ) { if (propertyAsAlias) { const createdExport = serializeMaybeAliasAssignment(symbol); if (createdExport) { @@ -8753,31 +8843,39 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { ? NodeFlags.Const // exports are immutable in es6, which is what we emulate and check; so it's safe to mark all exports as `const` (there's no difference to consumers, but it allows unique symbol type declarations) : undefined : isConstantVariable(symbol) - ? NodeFlags.Const - : NodeFlags.Let; + ? NodeFlags.Const + : NodeFlags.Let; const name = (needsPostExportDefault || !(symbol.flags & SymbolFlags.Property)) ? localName : getUnusedName(localName, symbol); let textRange: Node | undefined = symbol.declarations && find(symbol.declarations, d => isVariableDeclaration(d)); if (textRange && isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) { textRange = textRange.parent.parent; } const propertyAccessRequire = symbol.declarations?.find(isPropertyAccessExpression); - if (propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) - && type.symbol?.valueDeclaration && isSourceFile(type.symbol.valueDeclaration)) { + if ( + propertyAccessRequire && isBinaryExpression(propertyAccessRequire.parent) && isIdentifier(propertyAccessRequire.parent.right) + && type.symbol?.valueDeclaration && isSourceFile(type.symbol.valueDeclaration) + ) { const alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right; addResult( factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, - factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)]) + factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, alias, localName)]), ), - ModifierFlags.None + ModifierFlags.None, ); context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, SymbolFlags.Value); } else { - const statement = setTextRange(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) - ], flags)), textRange); + const statement = setTextRange( + factory.createVariableStatement( + /*modifiers*/ undefined, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)), + ], flags), + ), + textRange, + ); addResult(statement, name !== localName ? modifierFlags & ~ModifierFlags.Export : modifierFlags); if (name !== localName && !isPrivate) { // We rename the variable declaration we generate for Property symbols since they may have a name which @@ -8805,9 +8903,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, - factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)]) + factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, name, localName)]), ), - ModifierFlags.None + ModifierFlags.None, ); needsExportDeclaration = false; needsPostExportDefault = false; @@ -8820,10 +8918,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & SymbolFlags.Class) { - if (symbol.flags & SymbolFlags.Property + if ( + symbol.flags & SymbolFlags.Property && symbol.valueDeclaration && isBinaryExpression(symbol.valueDeclaration.parent) - && isClassExpression(symbol.valueDeclaration.parent.right)) { + && isClassExpression(symbol.valueDeclaration.parent.right) + ) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -8861,11 +8961,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { addResult(factory.createExportAssignment(/*modifiers*/ undefined, /*isExportEquals*/ false, factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), ModifierFlags.None); } else if (needsExportDeclaration) { - addResult(factory.createExportDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)]) - ), ModifierFlags.None); + addResult( + factory.createExportDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, getInternalSymbolName(symbol, symbolName), symbolName)]), + ), + ModifierFlags.None, + ); } } @@ -8881,8 +8984,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isExternalImportAlias = !!(symbol.flags & SymbolFlags.Alias) && !some(symbol.declarations, d => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || - (isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference)) - ); + (isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference))); deferredPrivatesStack[isExternalImportAlias ? 0 : (deferredPrivatesStack.length - 1)].set(getSymbolId(symbol), symbol); } @@ -8897,16 +8999,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let newModifierFlags: ModifierFlags = ModifierFlags.None; const enclosingDeclaration = context.enclosingDeclaration && (isJSDocTypeAlias(context.enclosingDeclaration) ? getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); - if (additionalModifierFlags & ModifierFlags.Export && + if ( + additionalModifierFlags & ModifierFlags.Export && enclosingDeclaration && (isExportingScope(enclosingDeclaration) || isModuleDeclaration(enclosingDeclaration)) && canHaveExportModifier(node) ) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= ModifierFlags.Export; } - if (addingDeclare && !(newModifierFlags & ModifierFlags.Export) && + if ( + addingDeclare && !(newModifierFlags & ModifierFlags.Export) && (!enclosingDeclaration || !(enclosingDeclaration.flags & NodeFlags.Ambient)) && - (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node))) { + (isEnumDeclaration(node) || isVariableStatement(node) || isFunctionDeclaration(node) || isClassDeclaration(node) || isModuleDeclaration(node)) + ) { // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope newModifierFlags |= ModifierFlags.Ambient; } @@ -8931,13 +9036,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const oldEnclosingDecl = context.enclosingDeclaration; context.enclosingDeclaration = jsdocAliasDecl; const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression - && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) - && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) + && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) + && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled) || typeToTypeNodeHelper(aliasType, context); - addResult(setSyntheticLeadingComments( - factory.createTypeAliasDeclaration(/*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), - !commentText ? [] : [{ kind: SyntaxKind.MultiLineCommentTrivia, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }] - ), modifierFlags); + addResult( + setSyntheticLeadingComments( + factory.createTypeAliasDeclaration(/*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeNode), + !commentText ? [] : [{ kind: SyntaxKind.MultiLineCommentTrivia, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }], + ), + modifierFlags, + ); context.flags = oldFlags; context.enclosingDeclaration = oldEnclosingDecl; } @@ -8954,13 +9062,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const indexSignatures = serializeIndexSignatures(interfaceType, baseType); const heritageClauses = !length(baseTypes) ? undefined : [factory.createHeritageClause(SyntaxKind.ExtendsKeyword, mapDefined(baseTypes, b => trySerializeAsTypeReference(b, SymbolFlags.Value)))]; - addResult(factory.createInterfaceDeclaration( - /*modifiers*/ undefined, - getInternalSymbolName(symbol, symbolName), - typeParamDecls, - heritageClauses, - [...indexSignatures, ...constructSignatures, ...callSignatures, ...members] - ), modifierFlags); + addResult( + factory.createInterfaceDeclaration( + /*modifiers*/ undefined, + getInternalSymbolName(symbol, symbolName), + typeParamDecls, + heritageClauses, + [...indexSignatures, ...constructSignatures, ...callSignatures, ...members], + ), + modifierFlags, + ); } function getNamespaceMembersForSerialization(symbol: Symbol) { @@ -9003,32 +9114,41 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { includePrivateSymbol(target || s); const targetName = target ? getInternalSymbolName(target, unescapeLeadingUnderscores(target.escapedName)) : localName; return factory.createExportSpecifier(/*isTypeOnly*/ false, name === targetName ? undefined : targetName, name); - })) + })), )]); - addResult(factory.createModuleDeclaration( - /*modifiers*/ undefined, - factory.createIdentifier(localName), - nsBody, - NodeFlags.Namespace - ), ModifierFlags.None); + addResult( + factory.createModuleDeclaration( + /*modifiers*/ undefined, + factory.createIdentifier(localName), + nsBody, + NodeFlags.Namespace, + ), + ModifierFlags.None, + ); } } function serializeEnum(symbol: Symbol, symbolName: string, modifierFlags: ModifierFlags) { - addResult(factory.createEnumDeclaration( - factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? ModifierFlags.Const : 0), - getInternalSymbolName(symbol, symbolName), - map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), p => !!(p.flags & SymbolFlags.EnumMember)), p => { - // TODO: Handle computed names - // I hate that to get the initialized value we need to walk back to the declarations here; but there's no - // other way to get the possible const value of an enum member that I'm aware of, as the value is cached - // _on the declaration_, not on the declaration's symbol... - const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined; - return factory.createEnumMember(unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : - typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : - factory.createNumericLiteral(initializedValue)); - }) - ), modifierFlags); + addResult( + factory.createEnumDeclaration( + factory.createModifiersFromModifierFlags(isConstEnumSymbol(symbol) ? ModifierFlags.Const : 0), + getInternalSymbolName(symbol, symbolName), + map(filter(getPropertiesOfType(getTypeOfSymbol(symbol)), p => !!(p.flags & SymbolFlags.EnumMember)), p => { + // TODO: Handle computed names + // I hate that to get the initialized value we need to walk back to the declarations here; but there's no + // other way to get the possible const value of an enum member that I'm aware of, as the value is cached + // _on the declaration_, not on the declaration's symbol... + const initializedValue = p.declarations && p.declarations[0] && isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined; + return factory.createEnumMember( + unescapeLeadingUnderscores(p.escapedName), + initializedValue === undefined ? undefined : + typeof initializedValue === "string" ? factory.createStringLiteral(initializedValue) : + factory.createNumericLiteral(initializedValue), + ); + }), + ), + modifierFlags, + ); } function serializeAsFunctionNamespaceMerge(type: Type, symbol: Symbol, localName: string, modifierFlags: ModifierFlags) { @@ -9060,11 +9180,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function serializeAsNamespaceDeclaration(props: readonly Symbol[], localName: string, modifierFlags: ModifierFlags, suppressNewPrivateContext: boolean) { if (length(props)) { - const localVsRemoteMap = arrayToMultiMap(props, p => - !length(p.declarations) || some(p.declarations, d => - getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration!) - ) ? "local" : "remote" - ); + const localVsRemoteMap = arrayToMultiMap(props, p => !length(p.declarations) || some(p.declarations, d => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration!)) ? "local" : "remote"); const localProps = localVsRemoteMap.get("local") || emptyArray; // handle remote props first - we need to make an `import` declaration that points at the module containing each remote // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this) @@ -9102,17 +9218,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const declarations = results; results = oldResults; // replace namespace with synthetic version - const defaultReplaced = map(declarations, d => isExportAssignment(d) && !d.isExportEquals && isIdentifier(d.expression) ? factory.createExportDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, factory.createIdentifier(InternalSymbolName.Default))]) - ) : d); + const defaultReplaced = map(declarations, d => + isExportAssignment(d) && !d.isExportEquals && isIdentifier(d.expression) ? factory.createExportDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, d.expression, factory.createIdentifier(InternalSymbolName.Default))]), + ) : d); const exportModifierStripped = every(defaultReplaced, d => hasSyntacticModifier(d, ModifierFlags.Export)) ? map(defaultReplaced as Extract[], removeExportModifier) : defaultReplaced; fakespace = factory.updateModuleDeclaration( fakespace, fakespace.modifiers, fakespace.name, - factory.createModuleBlock(exportModifierStripped)); + factory.createModuleBlock(exportModifierStripped), + ); addResult(fakespace, modifierFlags); // namespaces can never be default exported } } @@ -9137,11 +9255,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return cleanup(/*result*/ undefined); } } - return cleanup(factory.createExpressionWithTypeArguments(expr, + return cleanup(factory.createExpressionWithTypeArguments( + expr, map(e.typeArguments, a => serializeExistingTypeNode(context, a, includePrivateSymbol, bundled) - || typeToTypeNodeHelper(getTypeFromTypeNode(a), context) - ) + || typeToTypeNodeHelper(getTypeFromTypeNode(a), context)), )); function cleanup(result: T): T { @@ -9173,7 +9291,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { : anyType; const heritageClauses = [ ...!length(baseTypes) ? [] : [factory.createHeritageClause(SyntaxKind.ExtendsKeyword, map(baseTypes, b => serializeBaseType(b, staticBaseType, localName)))], - ...!length(implementsExpressions) ? [] : [factory.createHeritageClause(SyntaxKind.ImplementsKeyword, implementsExpressions)] + ...!length(implementsExpressions) ? [] : [factory.createHeritageClause(SyntaxKind.ImplementsKeyword, implementsExpressions)], ]; const symbolProps = getNonInheritedProperties(classType, baseTypes, getPropertiesOfType(classType)); const publicSymbolProps = filter(symbolProps, s => { @@ -9204,12 +9322,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics const staticMembers = flatMap( filter(getPropertiesOfType(staticType), p => !(p.flags & SymbolFlags.Prototype) && p.escapedName !== "prototype" && !isNamespaceMember(p)), - p => serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType)); + p => serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType), + ); // When we encounter an `X.prototype.y` assignment in a JS file, we bind `X` as a class regardless as to whether // the value is ever initialized with a class or function-like value. For cases where `X` could never be // created via `new`, we will inject a `private constructor()` declaration to indicate it is not createable. - const isNonConstructableClassLikeInJsFile = - !isClass && + const isNonConstructableClassLikeInJsFile = !isClass && !!symbol.valueDeclaration && isInJSFile(symbol.valueDeclaration) && !some(getSignaturesOfType(staticType, SignatureKind.Construct)); @@ -9218,13 +9336,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { serializeSignatures(SignatureKind.Construct, staticType, staticBaseType, SyntaxKind.Constructor) as ConstructorDeclaration[]; const indexSignatures = serializeIndexSignatures(classType, baseTypes[0]); context.enclosingDeclaration = oldEnclosing; - addResult(setTextRange(factory.createClassDeclaration( - /*modifiers*/ undefined, - localName, - typeParamDecls, - heritageClauses, - [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties] - ), symbol.declarations && filter(symbol.declarations, d => isClassDeclaration(d) || isClassExpression(d))[0]), modifierFlags); + addResult( + setTextRange( + factory.createClassDeclaration( + /*modifiers*/ undefined, + localName, + typeParamDecls, + heritageClauses, + [...indexSignatures, ...staticMembers, ...constructors, ...publicProperties, ...privateProperties], + ), + symbol.declarations && filter(symbol.declarations, d => isClassDeclaration(d) || isClassExpression(d))[0], + ), + modifierFlags, + ); } function getSomeTargetNameFromDeclarations(declarations: Declaration[] | undefined) { @@ -9274,16 +9398,23 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // const { SomeClass } = require('./lib'); const specifier = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' const { propertyName } = node as BindingElement; - addResult(factory.createImportDeclaration( - /*modifiers*/ undefined, - factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports([factory.createImportSpecifier( - /*isTypeOnly*/ false, - propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : undefined, - factory.createIdentifier(localName) - )])), - factory.createStringLiteral(specifier), - /*assertClause*/ undefined - ), ModifierFlags.None); + addResult( + factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause( + /*isTypeOnly*/ false, + /*name*/ undefined, + factory.createNamedImports([factory.createImportSpecifier( + /*isTypeOnly*/ false, + propertyName && isIdentifier(propertyName) ? factory.createIdentifier(idText(propertyName)) : undefined, + factory.createIdentifier(localName), + )]), + ), + factory.createStringLiteral(specifier), + /*assertClause*/ undefined, + ), + ModifierFlags.None, + ); break; } // We don't know how to serialize this (nested?) binding element @@ -9294,7 +9425,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // module.exports = { SomeClass } serializeExportSpecifier( unescapeLeadingUnderscores(symbol.escapedName), - targetName + targetName, ); } break; @@ -9306,19 +9437,25 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const uniqueName = factory.createUniqueName(localName); // _x const specifier = getSpecifierForModuleSymbol(target.parent || target, context); // 'y' // import _x = require('y'); - addResult(factory.createImportEqualsDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - uniqueName, - factory.createExternalModuleReference(factory.createStringLiteral(specifier)) - ), ModifierFlags.None); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + uniqueName, + factory.createExternalModuleReference(factory.createStringLiteral(specifier)), + ), + ModifierFlags.None, + ); // import x = _x.z - addResult(factory.createImportEqualsDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createIdentifier(localName), - factory.createQualifiedName(uniqueName, initializer.name as Identifier), - ), modifierFlags); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createIdentifier(localName), + factory.createQualifiedName(uniqueName, initializer.name as Identifier), + ), + modifierFlags, + ); break; } // else fall through and treat commonjs require just like import= @@ -9332,14 +9469,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Could be a local `import localName = ns.member` or // an external `import localName = require("whatever")` const isLocalImport = !(target.flags & SymbolFlags.ValueModule) && !isVariableDeclaration(node); - addResult(factory.createImportEqualsDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createIdentifier(localName), - isLocalImport - ? symbolToName(target, context, SymbolFlags.All, /*expectsIdentifier*/ false) - : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))) - ), isLocalImport ? modifierFlags : ModifierFlags.None); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createIdentifier(localName), + isLocalImport + ? symbolToName(target, context, SymbolFlags.All, /*expectsIdentifier*/ false) + : factory.createExternalModuleReference(factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), + ), + isLocalImport ? modifierFlags : ModifierFlags.None, + ); break; case SyntaxKind.NamespaceExportDeclaration: // export as namespace foo @@ -9350,51 +9490,64 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.ImportClause: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); // generate specifier (even though we're reusing and existing one) for ambient module reference include side effects const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : (node as ImportClause).parent.moduleSpecifier; - addResult(factory.createImportDeclaration( - /*modifiers*/ undefined, - factory.createImportClause(/*isTypeOnly*/ false, factory.createIdentifier(localName), /*namedBindings*/ undefined), - specifier, - (node as ImportClause).parent.assertClause - ), ModifierFlags.None); + addResult( + factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause(/*isTypeOnly*/ false, factory.createIdentifier(localName), /*namedBindings*/ undefined), + specifier, + (node as ImportClause).parent.assertClause, + ), + ModifierFlags.None, + ); break; } case SyntaxKind.NamespaceImport: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); // generate specifier (even though we're reusing and existing one) for ambient module reference include side effects const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : (node as NamespaceImport).parent.parent.moduleSpecifier; - addResult(factory.createImportDeclaration( - /*modifiers*/ undefined, - factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(factory.createIdentifier(localName))), - specifier, - (node as NamespaceImport).parent.parent.assertClause - ), ModifierFlags.None); + addResult( + factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(factory.createIdentifier(localName))), + specifier, + (node as NamespaceImport).parent.parent.assertClause, + ), + ModifierFlags.None, + ); break; } case SyntaxKind.NamespaceExport: - addResult(factory.createExportDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createNamespaceExport(factory.createIdentifier(localName)), - factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)) - ), ModifierFlags.None); + addResult( + factory.createExportDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createNamespaceExport(factory.createIdentifier(localName)), + factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)), + ), + ModifierFlags.None, + ); break; case SyntaxKind.ImportSpecifier: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); // generate specifier (even though we're reusing and existing one) for ambient module reference include side effects const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : (node as ImportSpecifier).parent.parent.parent.moduleSpecifier; - addResult(factory.createImportDeclaration( - /*modifiers*/ undefined, - factory.createImportClause( - /*isTypeOnly*/ false, - /*name*/ undefined, - factory.createNamedImports([ - factory.createImportSpecifier( - /*isTypeOnly*/ false, - localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : undefined, - factory.createIdentifier(localName) - ) - ])), - specifier, - (node as ImportSpecifier).parent.parent.parent.assertClause, - ), ModifierFlags.None); + addResult( + factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.createImportClause( + /*isTypeOnly*/ false, + /*name*/ undefined, + factory.createNamedImports([ + factory.createImportSpecifier( + /*isTypeOnly*/ false, + localName !== verbatimTargetName ? factory.createIdentifier(verbatimTargetName) : undefined, + factory.createIdentifier(localName), + ), + ]), + ), + specifier, + (node as ImportSpecifier).parent.parent.parent.assertClause, + ), + ModifierFlags.None, + ); break; } case SyntaxKind.ExportSpecifier: @@ -9406,7 +9559,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { serializeExportSpecifier( unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, - specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : undefined + specifier && isStringLiteralLike(specifier) ? factory.createStringLiteral(specifier.text) : undefined, ); break; case SyntaxKind.ExportAssignment: @@ -9431,12 +9584,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function serializeExportSpecifier(localName: string, targetName: string, specifier?: Expression) { - addResult(factory.createExportDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), - specifier - ), ModifierFlags.None); + addResult( + factory.createExportDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, localName !== targetName ? targetName : undefined, localName)]), + specifier, + ), + ModifierFlags.None, + ); } /** @@ -9479,7 +9635,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { results.push(factory.createExportAssignment( /*modifiers*/ undefined, isExportEquals, - symbolToExpression(target, context, SymbolFlags.All) + symbolToExpression(target, context, SymbolFlags.All), )); } else { @@ -9493,12 +9649,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else { // serialize as `import _Ref = t.arg.et; export { _Ref as name }` const varName = getUnusedName(name, symbol); - addResult(factory.createImportEqualsDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createIdentifier(varName), - symbolToName(target, context, SymbolFlags.All, /*expectsIdentifier*/ false) - ), ModifierFlags.None); + addResult( + factory.createImportEqualsDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createIdentifier(varName), + symbolToName(target, context, SymbolFlags.All, /*expectsIdentifier*/ false), + ), + ModifierFlags.None, + ); serializeExportSpecifier(name, varName); } } @@ -9516,21 +9675,26 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? ModifierFlags.None : ModifierFlags.Export); } else { - const statement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(varName, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) - ], context.enclosingDeclaration?.kind === SyntaxKind.ModuleDeclaration ? NodeFlags.Let : NodeFlags.Const)); + const statement = factory.createVariableStatement( + /*modifiers*/ undefined, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration(varName, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)), + ], context.enclosingDeclaration?.kind === SyntaxKind.ModuleDeclaration ? NodeFlags.Let : NodeFlags.Const), + ); // Inlined JSON types exported with [module.]exports= will already emit an export=, so should use `declare`. // Otherwise, the type itself should be exported. - addResult(statement, + addResult( + statement, target && target.flags & SymbolFlags.Property && target.escapedName === InternalSymbolName.ExportEquals ? ModifierFlags.Ambient - : name === varName ? ModifierFlags.Export - : ModifierFlags.None); + : name === varName ? ModifierFlags.Export + : ModifierFlags.None, + ); } if (isExportAssignmentCompatibleSymbolName) { results.push(factory.createExportAssignment( /*modifiers*/ undefined, isExportEquals, - factory.createIdentifier(varName) + factory.createIdentifier(varName), )); return true; } @@ -9548,39 +9712,51 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it) const ctxSrc = getSourceFileOfNode(context.enclosingDeclaration); return getObjectFlags(typeToSerialize) & (ObjectFlags.Anonymous | ObjectFlags.Mapped) && - !length(getIndexInfosOfType(typeToSerialize)) && - !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class - !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, SignatureKind.Call))) && - !length(getSignaturesOfType(typeToSerialize, SignatureKind.Construct)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && - !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && - !some(getPropertiesOfType(typeToSerialize), p => isLateBoundName(p.escapedName)) && - !some(getPropertiesOfType(typeToSerialize), p => some(p.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && - every(getPropertiesOfType(typeToSerialize), p => isIdentifierText(symbolName(p), languageVersion)); - } - - function makeSerializePropertySymbol(createProperty: ( - modifiers: readonly Modifier[] | undefined, - name: string | PropertyName, - questionOrExclamationToken: QuestionToken | undefined, - type: TypeNode | undefined, - initializer: Expression | undefined - ) => T, methodKind: SignatureDeclaration["kind"], useAccessors: true): (p: Symbol, isStatic: boolean, baseType: Type | undefined) => (T | AccessorDeclaration | (T | AccessorDeclaration)[]); - function makeSerializePropertySymbol(createProperty: ( - modifiers: readonly Modifier[] | undefined, - name: string | PropertyName, - questionOrExclamationToken: QuestionToken | undefined, - type: TypeNode | undefined, - initializer: Expression | undefined - ) => T, methodKind: SignatureDeclaration["kind"], useAccessors: false): (p: Symbol, isStatic: boolean, baseType: Type | undefined) => (T | T[]); - function makeSerializePropertySymbol(createProperty: ( - modifiers: readonly Modifier[] | undefined, - name: string | PropertyName, - questionOrExclamationToken: QuestionToken | undefined, - type: TypeNode | undefined, - initializer: Expression | undefined - ) => T, methodKind: SignatureDeclaration["kind"], useAccessors: boolean): (p: Symbol, isStatic: boolean, baseType: Type | undefined) => (T | AccessorDeclaration | (T | AccessorDeclaration)[]) { - return function serializePropertySymbol(p: Symbol, isStatic: boolean, baseType: Type | undefined): (T | AccessorDeclaration | (T | AccessorDeclaration)[]) { + !length(getIndexInfosOfType(typeToSerialize)) && + !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class + !!(length(filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || length(getSignaturesOfType(typeToSerialize, SignatureKind.Call))) && + !length(getSignaturesOfType(typeToSerialize, SignatureKind.Construct)) && // TODO: could probably serialize as function + ns + class, now that that's OK + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && + !(typeToSerialize.symbol && some(typeToSerialize.symbol.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && + !some(getPropertiesOfType(typeToSerialize), p => isLateBoundName(p.escapedName)) && + !some(getPropertiesOfType(typeToSerialize), p => some(p.declarations, d => getSourceFileOfNode(d) !== ctxSrc)) && + every(getPropertiesOfType(typeToSerialize), p => isIdentifierText(symbolName(p), languageVersion)); + } + + function makeSerializePropertySymbol( + createProperty: ( + modifiers: readonly Modifier[] | undefined, + name: string | PropertyName, + questionOrExclamationToken: QuestionToken | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ) => T, + methodKind: SignatureDeclaration["kind"], + useAccessors: true, + ): (p: Symbol, isStatic: boolean, baseType: Type | undefined) => T | AccessorDeclaration | (T | AccessorDeclaration)[]; + function makeSerializePropertySymbol( + createProperty: ( + modifiers: readonly Modifier[] | undefined, + name: string | PropertyName, + questionOrExclamationToken: QuestionToken | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ) => T, + methodKind: SignatureDeclaration["kind"], + useAccessors: false, + ): (p: Symbol, isStatic: boolean, baseType: Type | undefined) => T | T[]; + function makeSerializePropertySymbol( + createProperty: ( + modifiers: readonly Modifier[] | undefined, + name: string | PropertyName, + questionOrExclamationToken: QuestionToken | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ) => T, + methodKind: SignatureDeclaration["kind"], + useAccessors: boolean, + ): (p: Symbol, isStatic: boolean, baseType: Type | undefined) => T | AccessorDeclaration | (T | AccessorDeclaration)[] { + return function serializePropertySymbol(p: Symbol, isStatic: boolean, baseType: Type | undefined): T | AccessorDeclaration | (T | AccessorDeclaration)[] { const modifierFlags = getDeclarationModifierFlagsFromSymbol(p); const isPrivate = !!(modifierFlags & ModifierFlags.Private); if (isStatic && (p.flags & (SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias))) { @@ -9588,11 +9764,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // need to be merged namespace members return []; } - if (p.flags & SymbolFlags.Prototype || p.escapedName === "constructor" || + if ( + p.flags & SymbolFlags.Prototype || p.escapedName === "constructor" || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)!) === isReadonlySymbol(p) - && (p.flags & SymbolFlags.Optional) === (getPropertyOfType(baseType, p.escapedName)!.flags & SymbolFlags.Optional) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)!))) { + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)!) === isReadonlySymbol(p) + && (p.flags & SymbolFlags.Optional) === (getPropertyOfType(baseType, p.escapedName)!.flags & SymbolFlags.Optional) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)!)) + ) { return []; } const flag = (modifierFlags & ~ModifierFlags.Async) | (isStatic ? ModifierFlags.Static : 0); @@ -9601,55 +9779,67 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (p.flags & SymbolFlags.Accessor && useAccessors) { const result: AccessorDeclaration[] = []; if (p.flags & SymbolFlags.SetAccessor) { - result.push(setTextRange(factory.createSetAccessorDeclaration( - factory.createModifiersFromModifierFlags(flag), - name, - [factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - "arg", - /*questionToken*/ undefined, - isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled) - )], - /*body*/ undefined - ), p.declarations?.find(isSetAccessor) || firstPropertyLikeDecl)); + result.push(setTextRange( + factory.createSetAccessorDeclaration( + factory.createModifiersFromModifierFlags(flag), + name, + [factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + "arg", + /*questionToken*/ undefined, + isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + )], + /*body*/ undefined, + ), + p.declarations?.find(isSetAccessor) || firstPropertyLikeDecl, + )); } if (p.flags & SymbolFlags.GetAccessor) { const isPrivate = modifierFlags & ModifierFlags.Private; - result.push(setTextRange(factory.createGetAccessorDeclaration( - factory.createModifiersFromModifierFlags(flag), - name, - [], - isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - /*body*/ undefined - ), p.declarations?.find(isGetAccessor) || firstPropertyLikeDecl)); + result.push(setTextRange( + factory.createGetAccessorDeclaration( + factory.createModifiersFromModifierFlags(flag), + name, + [], + isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + /*body*/ undefined, + ), + p.declarations?.find(isGetAccessor) || firstPropertyLikeDecl, + )); } return result; } // This is an else/if as accessors and properties can't merge in TS, but might in JS // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (SymbolFlags.Property | SymbolFlags.Variable | SymbolFlags.Accessor)) { - return setTextRange(createProperty( - factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? ModifierFlags.Readonly : 0) | flag), - name, - p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, - isPrivate ? undefined : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), - // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 - // interface members can't have initializers, however class members _can_ - /*initializer*/ undefined - ), p.declarations?.find(or(isPropertyDeclaration, isVariableDeclaration)) || firstPropertyLikeDecl); + return setTextRange( + createProperty( + factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? ModifierFlags.Readonly : 0) | flag), + name, + p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, + isPrivate ? undefined : serializeTypeForDeclaration(context, getWriteTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), + // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 + // interface members can't have initializers, however class members _can_ + /*initializer*/ undefined, + ), + p.declarations?.find(or(isPropertyDeclaration, isVariableDeclaration)) || firstPropertyLikeDecl, + ); } if (p.flags & (SymbolFlags.Method | SymbolFlags.Function)) { const type = getTypeOfSymbol(p); const signatures = getSignaturesOfType(type, SignatureKind.Call); if (flag & ModifierFlags.Private) { - return setTextRange(createProperty( - factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? ModifierFlags.Readonly : 0) | flag), - name, - p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, - /*type*/ undefined, - /*initializer*/ undefined - ), p.declarations?.find(isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0]); + return setTextRange( + createProperty( + factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? ModifierFlags.Readonly : 0) | flag), + name, + p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, + /*type*/ undefined, + /*initializer*/ undefined, + ), + p.declarations?.find(isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0], + ); } const results = []; @@ -9662,8 +9852,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { { name, questionToken: p.flags & SymbolFlags.Optional ? factory.createToken(SyntaxKind.QuestionToken) : undefined, - modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : undefined - } + modifiers: flag ? factory.createModifiersFromModifierFlags(flag) : undefined, + }, ); const location = sig.declaration && isPrototypePropertyAssignment(sig.declaration.parent) ? sig.declaration.parent : sig.declaration; results.push(setTextRange(decl, location)); @@ -9711,11 +9901,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } if (privateProtected) { - return [setTextRange(factory.createConstructorDeclaration( - factory.createModifiersFromModifierFlags(privateProtected), - /*parameters*/ [], - /*body*/ undefined, - ), signatures[0].declaration)]; + return [setTextRange( + factory.createConstructorDeclaration( + factory.createModifiersFromModifierFlags(privateProtected), + /*parameters*/ [], + /*body*/ undefined, + ), + signatures[0].declaration, + )]; } } @@ -9750,9 +9943,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return ref; } const tempName = getUnusedName(`${rootName}_base`); - const statement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(tempName, /*exclamationToken*/ undefined, typeToTypeNodeHelper(staticType, context)) - ], NodeFlags.Const)); + const statement = factory.createVariableStatement( + /*modifiers*/ undefined, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration(tempName, /*exclamationToken*/ undefined, typeToTypeNodeHelper(staticType, context)), + ], NodeFlags.Const), + ); addResult(statement, ModifierFlags.None); return factory.createExpressionWithTypeArguments(factory.createIdentifier(tempName), /*typeArguments*/ undefined); } @@ -9846,7 +10042,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const predicate = factory.createTypePredicateNode( typePredicate.kind === TypePredicateKind.AssertsThis || typePredicate.kind === TypePredicateKind.AssertsIdentifier ? factory.createToken(SyntaxKind.AssertsKeyword) : undefined, typePredicate.kind === TypePredicateKind.Identifier || typePredicate.kind === TypePredicateKind.AssertsIdentifier ? factory.createIdentifier(typePredicate.parameterName) : factory.createThisTypeNode(), - typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName)! // TODO: GH#18217 + typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.WriteTypeParametersInQualifiedName)!, // TODO: GH#18217 ); const printer = createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); @@ -9938,13 +10134,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol: Symbol, context?: NodeBuilderContext): string { - if (context && symbol.escapedName === InternalSymbolName.Default && !(context.flags & NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope) && + if ( + context && symbol.escapedName === InternalSymbolName.Default && !(context.flags & NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope) && // If it's not the first part of an entity name, it must print as `default` (!(context.flags & NodeBuilderFlags.InInitialEntityName) || - // if the symbol is synthesized, it will only be referenced externally it must print as `default` - !symbol.declarations || - // if not in the same binding context (source file, module declaration), it must print as `default` - (context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext))) + ) { return "default"; } if (symbol.declarations && symbol.declarations.length) { @@ -10008,8 +10206,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.BindingElement: return isDeclarationVisible(node.parent.parent); case SyntaxKind.VariableDeclaration: - if (isBindingPattern((node as VariableDeclaration).name) && - !((node as VariableDeclaration).name as BindingPattern).elements.length) { + if ( + isBindingPattern((node as VariableDeclaration).name) && + !((node as VariableDeclaration).name as BindingPattern).elements.length + ) { // If the binding pattern is empty, this variable declaration is not visible return false; } @@ -10027,8 +10227,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) - if (!(getCombinedModifierFlagsCached(node as Declaration) & ModifierFlags.Export) && - !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && parent.flags & NodeFlags.Ambient)) { + if ( + !(getCombinedModifierFlagsCached(node as Declaration) & ModifierFlags.Export) && + !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && parent.flags & NodeFlags.Ambient) + ) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible @@ -10123,8 +10325,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Add the referenced top container visible const internalModuleReference = declaration.moduleReference as Identifier | QualifiedName; const firstIdentifier = getFirstIdentifier(internalModuleReference); - const importSymbol = resolveName(declaration, firstIdentifier.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, - /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + const importSymbol = resolveName(declaration, firstIdentifier.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (importSymbol && visited) { if (tryAddToSet(visited, getSymbolId(importSymbol))) { buildVisibleNodeList(importSymbol.declarations); @@ -10254,7 +10455,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let propType; return getTypeOfPropertyOfType(type, name) || (propType = getApplicableIndexInfoForName(type, name)?.type) && - addOptionality(propType, /*isProperty*/ true, /*isOptional*/ true); + addOptionality(propType, /*isProperty*/ true, /*isOptional*/ true); } function isTypeAny(type: Type | undefined) { @@ -10293,9 +10494,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (const prop of getPropertiesOfType(source)) { const literalTypeFromProperty = getLiteralTypeFromProperty(prop, TypeFlags.StringOrNumberLiteralOrUnique); - if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) + if ( + !isTypeAssignableTo(literalTypeFromProperty, omitKeyType) && !(getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected)) - && isSpreadableProperty(prop)) { + && isSpreadableProperty(prop) + ) { spreadableProperties.push(prop); } else { @@ -10551,9 +10754,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return addOptionality(declaredType, isProperty, isOptional); } - if ((noImplicitAny || isInJSFile(declaration)) && + if ( + (noImplicitAny || isInJSFile(declaration)) && isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && - !(getCombinedModifierFlagsCached(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) { + !(getCombinedModifierFlagsCached(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient) + ) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no // initializer or a 'null' or 'undefined' initializer. @@ -10735,8 +10940,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getFlowTypeOfProperty(reference: Node, prop: Symbol | undefined) { const initialType = prop?.valueDeclaration - && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & ModifierFlags.Ambient) - && getTypeOfPropertyInBaseClass(prop) + && (!isAutoTypedProperty(prop) || getEffectiveModifierFlags(prop.valueDeclaration) & ModifierFlags.Ambient) + && getTypeOfPropertyInBaseClass(prop) || undefinedType; return getFlowTypeOfReference(reference, autoType, initialType); } @@ -10896,9 +11101,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : isDirectExport ? getRegularTypeOfLiteralType(checkExpressionCached(expression.right)) : getWidenedLiteralType(checkExpressionCached(expression.right)); - if (type.flags & TypeFlags.Object && + if ( + type.flags & TypeFlags.Object && kind === AssignmentDeclarationKind.ModuleExports && - symbol.escapedName === InternalSymbolName.ExportEquals) { + symbol.escapedName === InternalSymbolName.ExportEquals + ) { const exportedType = resolveStructuredTypeMembers(type as ObjectType); const members = createSymbolTable(); copyEntries(exportedType.members, members); @@ -10925,10 +11132,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const exportedMemberName = tryCast(exportedMember.valueDeclaration, isNamedDeclaration)?.name || exportedMember.valueDeclaration; addRelatedInfo( error(s.valueDeclaration, Diagnostics.Duplicate_identifier_0, unescapedName), - createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName)); + createDiagnosticForNode(exportedMemberName, Diagnostics._0_was_also_declared_here, unescapedName), + ); addRelatedInfo( error(exportedMemberName, Diagnostics.Duplicate_identifier_0, unescapedName), - createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName)); + createDiagnosticForNode(s.valueDeclaration, Diagnostics._0_was_also_declared_here, unescapedName), + ); } const union = createSymbol(s.flags | exportedMember.flags, name); union.links.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); @@ -10949,7 +11158,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { members, exportedType.callSignatures, exportedType.constructSignatures, - exportedType.indexInfos); + exportedType.indexInfos, + ); if (initialSize === members.size) { if (type.aliasSymbol) { result.aliasSymbol = type.aliasSymbol; @@ -10961,7 +11171,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { result.aliasTypeArguments = length(args) ? args : undefined; } } - result.objectFlags |= (getObjectFlags(type) & ObjectFlags.JSLiteral); // Propagate JSLiteral flag + result.objectFlags |= getObjectFlags(type) & ObjectFlags.JSLiteral; // Propagate JSLiteral flag if (result.symbol && result.symbol.flags & SymbolFlags.Class && type === getDeclaredTypeOfClassOrInterface(result.symbol)) { result.objectFlags |= ObjectFlags.IsClassInstanceClone; // Propagate the knowledge that this type is equivalent to the symbol's class instance type } @@ -11235,10 +11445,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if ( isBinaryExpression(declaration) || (isInJSFile(declaration) && - (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent)))) { + (isCallExpression(declaration) || (isPropertyAccessExpression(declaration) || isBindableStaticElementAccessExpression(declaration)) && isBinaryExpression(declaration.parent))) + ) { type = getWidenedTypeForAssignmentDeclaration(symbol); } - else if (isPropertyAccessExpression(declaration) + else if ( + isPropertyAccessExpression(declaration) || isElementAccessExpression(declaration) || isIdentifier(declaration) || isStringLiteralLike(declaration) @@ -11247,7 +11459,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { || isFunctionDeclaration(declaration) || (isMethodDeclaration(declaration) && !isObjectLiteralMethod(declaration)) || isMethodSignature(declaration) - || isSourceFile(declaration)) { + || isSourceFile(declaration) + ) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) { return getTypeOfFuncClassEnumModule(symbol); @@ -11268,12 +11481,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (isObjectLiteralMethod(declaration)) { type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, CheckMode.Normal); } - else if (isParameter(declaration) - || isPropertyDeclaration(declaration) - || isPropertySignature(declaration) - || isVariableDeclaration(declaration) - || isBindingElement(declaration) - || isJSDocPropertyLikeTag(declaration)) { + else if ( + isParameter(declaration) + || isPropertyDeclaration(declaration) + || isPropertySignature(declaration) + || isVariableDeclaration(declaration) + || isBindingElement(declaration) + || isJSDocPropertyLikeTag(declaration) + ) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. @@ -11432,9 +11647,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (symbol.flags & SymbolFlags.Module && isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration && (declaration.kind === SyntaxKind.BinaryExpression || - isAccessExpression(declaration) && - declaration.parent.kind === SyntaxKind.BinaryExpression)) { + else if ( + declaration && (declaration.kind === SyntaxKind.BinaryExpression || + isAccessExpression(declaration) && + declaration.parent.kind === SyntaxKind.BinaryExpression) + ) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & SymbolFlags.ValueModule && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -11500,14 +11717,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const declaration = symbol.valueDeclaration as VariableLikeDeclaration; // Check if variable has type annotation that circularly references the variable itself if (getEffectiveTypeAnnotationNode(declaration)) { - error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, - symbolToString(symbol)); + error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); return errorType; } // Check if variable has initializer that circularly references the variable itself if (noImplicitAny && (declaration.kind !== SyntaxKind.Parameter || (declaration as HasInitializer).initializer)) { - error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, - symbolToString(symbol)); + error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } // Circularities could also result from parameters in function expressions that end up // having themselves as contextual types following type argument inference. In those cases @@ -11723,11 +11938,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } let result: TypeParameter[] | undefined; for (const node of symbol.declarations) { - if (node.kind === SyntaxKind.InterfaceDeclaration || + if ( + node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || isJSConstructor(node) || - isTypeAlias(node)) { + isTypeAlias(node) + ) { const declaration = node as InterfaceDeclaration | TypeAliasDeclaration | JSDocTypedefTag | JSDocCallbackTag; result = appendTypeParameters(result, getEffectiveTypeParameterDeclarations(declaration)); } @@ -11774,8 +11991,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: readonly TypeNode[] | undefined, location: Node): readonly Signature[] { const typeArgCount = length(typeArgumentNodes); const isJavascript = isInJSFile(location); - return filter(getSignaturesOfType(type, SignatureKind.Construct), - sig => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); + return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); } function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: readonly TypeNode[] | undefined, location: Node): readonly Signature[] { @@ -11909,8 +12125,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const baseTypeNode = getBaseTypeNodeOfClass(type)!; let baseType: Type; const originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; - if (baseConstructorType.symbol && baseConstructorType.symbol.flags & SymbolFlags.Class && - areAllOuterTypeParametersApplied(originalBaseType!)) { + if ( + baseConstructorType.symbol && baseConstructorType.symbol.flags & SymbolFlags.Class && + areAllOuterTypeParametersApplied(originalBaseType!) + ) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the // class and all return the instance type of the class. There is no need for further checks and we can apply the // type arguments in the same manner as a type reference to get the same error reporting experience. @@ -11942,8 +12160,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return type.resolvedBaseTypes = emptyArray; } if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { - error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, - typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType)); + error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType)); return type.resolvedBaseTypes = emptyArray; } if (type.resolvedBaseTypes === resolvingEmptyArray) { @@ -12135,9 +12352,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (hasBindableName(member)) { const memberSymbol = getSymbolOfDeclaration(member); const value = getEnumMemberValue(member); - const memberType = getFreshTypeOfLiteralType(value !== undefined ? - getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : - createComputedEnumType(memberSymbol)); + const memberType = getFreshTypeOfLiteralType( + value !== undefined ? + getEnumLiteralType(value, getSymbolId(symbol), memberSymbol) : + createComputedEnumType(memberSymbol), + ); getSymbolLinks(memberSymbol).declaredType = memberType; memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } @@ -12313,13 +12532,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { continue; } const derived = symbols.get(base.escapedName); - if (!derived + if ( + !derived // non-constructor/static-block assignment declarations are ignored here; they're not treated as overrides || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration) && !isConstructorDeclaredProperty(derived) - && !getContainingClassStaticBlock(derived.valueDeclaration)) { - symbols.set(base.escapedName, base); + && !getContainingClassStaticBlock(derived.valueDeclaration) + ) { + symbols.set(base.escapedName, base); symbols.set(base.escapedName, base); } } @@ -12403,7 +12624,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!symbol.declarations) { symbol.declarations = [member]; } - else if(!member.symbol.isReplaceableByMethod) { + else if (!member.symbol.isReplaceableByMethod) { symbol.declarations.push(member); } if (symbolFlags & SymbolFlags.Value) { @@ -12513,7 +12734,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } const assignments = (symbol.valueDeclaration?.kind === SyntaxKind.ArrowFunction || symbol.valueDeclaration?.kind === SyntaxKind.FunctionExpression) && - getSymbolOfNode(symbol.valueDeclaration.parent)?.assignmentDeclarationMembers || + getSymbolOfNode(symbol.valueDeclaration.parent)?.assignmentDeclarationMembers || symbol.assignmentDeclarationMembers; if (assignments) { @@ -12644,7 +12865,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { resolvedReturnType: Type | undefined, resolvedTypePredicate: TypePredicate | undefined, minArgumentCount: number, - flags: SignatureFlags + flags: SignatureFlags, ): Signature { const sig = new Signature(checker, flags); sig.declaration = declaration; @@ -12663,8 +12884,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function cloneSignature(sig: Signature): Signature { - const result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & SignatureFlags.PropagatingFlags); + const result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & SignatureFlags.PropagatingFlags); result.target = sig.target; result.mapper = sig.mapper; result.compositeSignatures = sig.compositeSignatures; @@ -12694,8 +12914,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function createOptionalCallSignature(signature: Signature, callChainFlags: SignatureFlags) { - Debug.assert(callChainFlags === SignatureFlags.IsInnerCallChain || callChainFlags === SignatureFlags.IsOuterCallChain, - "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); + Debug.assert(callChainFlags === SignatureFlags.IsInnerCallChain || callChainFlags === SignatureFlags.IsOuterCallChain, "An optional call signature can either be for an inner call chain or an outer call chain, but not both."); const result = cloneSignature(signature); result.flags |= callChainFlags; return result; @@ -12908,7 +13127,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const longest = leftCount >= rightCount ? left : right; const shorter = longest === left ? right : left; const longestCount = longest === left ? leftCount : rightCount; - const eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right); const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); for (let i = 0; i < longestCount; i++) { @@ -12932,7 +13151,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { undefined; const paramSymbol = createSymbol( SymbolFlags.FunctionScopedVariable | (isOptional && !isRestParam ? SymbolFlags.Optional : 0), - paramName || `arg${i}` as __String + paramName || `arg${i}` as __String, ); paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType; params[i] = paramSymbol; @@ -12967,7 +13186,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgCount, - (left.flags | right.flags) & SignatureFlags.PropagatingFlags + (left.flags | right.flags) & SignatureFlags.PropagatingFlags, ); result.compositeKind = TypeFlags.Union; result.compositeSignatures = concatenate(left.compositeKind !== TypeFlags.Intersection && left.compositeSignatures || [left], [right]); @@ -12984,8 +13203,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (const info of sourceInfos) { const indexType = info.keyType; if (every(types, t => !!getIndexInfoOfType(t, indexType))) { - result.push(createIndexInfo(indexType, getUnionType(map(types, t => getIndexTypeOfType(t, indexType)!)), - some(types, t => getIndexInfoOfType(t, indexType)!.isReadonly))); + result.push(createIndexInfo(indexType, getUnionType(map(types, t => getIndexTypeOfType(t, indexType)!)), some(types, t => getIndexInfoOfType(t, indexType)!.isReadonly))); } } return result; @@ -13009,9 +13227,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function findMixins(types: readonly Type[]): readonly boolean[] { - const constructorTypeCount = countWhere(types, (t) => getSignaturesOfType(t, SignatureKind.Construct).length > 0); + const constructorTypeCount = countWhere(types, t => getSignaturesOfType(t, SignatureKind.Construct).length > 0); const mixinFlags = map(types, isMixinConstructorType); - if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, (b) => b)) { + if (constructorTypeCount > 0 && constructorTypeCount === countWhere(mixinFlags, b => b)) { const firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true); mixinFlags[firstMixinIndex] = false; } @@ -13039,7 +13257,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let indexInfos: IndexInfo[] | undefined; const types = type.types; const mixinFlags = findMixins(types); - const mixinCount = countWhere(mixinFlags, (b) => b); + const mixinCount = countWhere(mixinFlags, b => b); for (let i = 0; i < types.length; i++) { const t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from @@ -13078,9 +13296,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (let i = 0; i < indexInfos.length; i++) { const info = indexInfos[i]; if (info.keyType === newInfo.keyType) { - indexInfos[i] = createIndexInfo(info.keyType, - union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), - union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly); + indexInfos[i] = createIndexInfo(info.keyType, union ? getUnionType([info.type, newInfo.type]) : getIntersectionType([info.type, newInfo.type]), union ? info.isReadonly || newInfo.isReadonly : info.isReadonly && newInfo.isReadonly); return indexInfos; } } @@ -13145,8 +13361,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (baseConstructorIndexInfo) { indexInfos = append(indexInfos, baseConstructorIndexInfo); } - if (symbol.flags & SymbolFlags.Enum && (getDeclaredTypeOfSymbol(symbol).flags & TypeFlags.Enum || - some(type.properties, prop => !!(getTypeOfSymbol(prop).flags & TypeFlags.NumberLike)))) { + if ( + symbol.flags & SymbolFlags.Enum && (getDeclaredTypeOfSymbol(symbol).flags & TypeFlags.Enum || + some(type.properties, prop => !!(getTypeOfSymbol(prop).flags & TypeFlags.NumberLike))) + ) { indexInfos = append(indexInfos, enumNumberIndexInfo); } } @@ -13163,11 +13381,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const classType = getDeclaredTypeOfClassOrInterface(symbol); let constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get(InternalSymbolName.Constructor)) : emptyArray; if (symbol.flags & SymbolFlags.Function) { - constructSignatures = addRange(constructSignatures.slice(), mapDefined( - type.callSignatures, - sig => isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & SignatureFlags.PropagatingFlags) : - undefined)); + constructSignatures = addRange( + constructSignatures.slice(), + mapDefined( + type.callSignatures, + sig => + isJSConstructor(sig.declaration) ? + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & SignatureFlags.PropagatingFlags) : + undefined, + ), + ); } if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); @@ -13176,7 +13399,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - type ReplaceableIndexedAccessType = IndexedAccessType & { objectType: TypeParameter, indexType: TypeParameter }; + type ReplaceableIndexedAccessType = IndexedAccessType & { objectType: TypeParameter; indexType: TypeParameter; }; function replaceIndexedAccess(instantiable: Type, type: ReplaceableIndexedAccessType, replacement: Type) { // map type.indexType to 0 // map type.objectType to `[TReplacement]` @@ -13197,9 +13420,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { inferredProp.declarations = prop.declarations; inferredProp.links.nameType = getSymbolLinks(prop).nameType; inferredProp.links.propertyType = getTypeOfSymbol(prop); - if (type.constraintType.type.flags & TypeFlags.IndexedAccess + if ( + type.constraintType.type.flags & TypeFlags.IndexedAccess && (type.constraintType.type as IndexedAccessType).objectType.flags & TypeFlags.TypeParameter - && (type.constraintType.type as IndexedAccessType).indexType.flags & TypeFlags.TypeParameter) { + && (type.constraintType.type as IndexedAccessType).indexType.flags & TypeFlags.TypeParameter + ) { // A reverse mapping of `{[K in keyof T[K_1]]: T[K_1]}` is the same as that of `{[K in keyof T]: T}`, since all we care about is // inferring to the "type parameter" (or indexed access) shared by the constraint and template. So, to reduce the number of // type identities produced, we simplify such indexed access occurences @@ -13322,8 +13547,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { !(templateModifiers & MappedTypeModifiers.ExcludeReadonly) && modifiersProp && isReadonlySymbol(modifiersProp)); const stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & SymbolFlags.Optional; const lateFlag: CheckFlags = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0; - const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName, - lateFlag | CheckFlags.Mapped | (isReadonly ? CheckFlags.Readonly : 0) | (stripOptional ? CheckFlags.StripOptional : 0)) as MappedSymbol; + const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName, lateFlag | CheckFlags.Mapped | (isReadonly ? CheckFlags.Readonly : 0) | (stripOptional ? CheckFlags.StripOptional : 0)) as MappedSymbol; prop.links.mappedType = type; prop.links.nameType = propNameType; prop.links.keyType = keyType; @@ -13611,7 +13835,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type.flags & TypeFlags.IndexedAccess && isConstTypeVariable((type as IndexedAccessType).objectType, depth + 1) || type.flags & TypeFlags.Conditional && isConstTypeVariable(getConstraintOfConditionalType(type as ConditionalType), depth + 1) || type.flags & TypeFlags.Substitution && isConstTypeVariable((type as SubstitutionType).baseType, depth) || - isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & ElementFlags.Variadic) && isConstTypeVariable(t, depth)) >= 0)); + isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & ElementFlags.Variadic) && isConstTypeVariable(t, depth)) >= 0 + )); } function getConstraintOfIndexedAccess(type: IndexedAccessType) { @@ -14002,7 +14227,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (prop.flags & SymbolFlags.ClassMember) { optionalFlag ??= isUnion ? SymbolFlags.None : SymbolFlags.Optional; if (isUnion) { - optionalFlag |= (prop.flags & SymbolFlags.Optional); + optionalFlag |= prop.flags & SymbolFlags.Optional; } else { optionalFlag &= prop.flags; @@ -14063,11 +14288,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } } - if (!singleProp || + if ( + !singleProp || isUnion && - (propSet || checkFlags & CheckFlags.Partial) && - checkFlags & (CheckFlags.ContainsPrivate | CheckFlags.ContainsProtected) && - !(propSet && getCommonDeclarationsOfSymbols(propSet.values())) + (propSet || checkFlags & CheckFlags.Partial) && + checkFlags & (CheckFlags.ContainsPrivate | CheckFlags.ContainsProtected) && + !(propSet && getCommonDeclarationsOfSymbols(propSet.values())) ) { // No property was found, or, in a union, a property has a private or protected declaration in one // constituent, but is missing or has a different declaration in another constituent. @@ -14162,7 +14388,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // and do not appear to be present in the union type. function getUnionOrIntersectionProperty(type: UnionOrIntersectionType, name: __String, skipObjectFunctionPropertyAugment?: boolean): Symbol | undefined { let property = type.propertyCacheWithoutObjectFunctionPropertyAugment?.get(name) || - !skipObjectFunctionPropertyAugment ? type.propertyCache?.get(name) : undefined; + !skipObjectFunctionPropertyAugment ? type.propertyCache?.get(name) : undefined; if (!property) { property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment); if (property) { @@ -14273,13 +14499,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (type.flags & TypeFlags.Intersection && getObjectFlags(type) & ObjectFlags.IsNeverIntersection) { const neverProp = find(getPropertiesOfUnionOrIntersectionType(type as IntersectionType), isDiscriminantWithNeverType); if (neverProp) { - return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, - typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTypeReduction), symbolToString(neverProp)); + return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTypeReduction), symbolToString(neverProp)); } const privateProp = find(getPropertiesOfUnionOrIntersectionType(type as IntersectionType), isConflictingPrivateProperty); if (privateProp) { - return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, - typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTypeReduction), symbolToString(privateProp)); + return chainDiagnosticMessages(errorInfo, Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.NoTypeReduction), symbolToString(privateProp)); } } return errorInfo; @@ -14390,8 +14614,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // When more than one index signature is applicable we create a synthetic IndexInfo. Instead of computing // the intersected key type, we just use unknownType for the key type as nothing actually depends on the // keyType property of the returned IndexInfo. - return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, info => info.type)), - reduceLeft(applicableInfos, (isReadonly, info) => isReadonly && info.isReadonly, /*initial*/ true)) : + return applicableInfos ? createIndexInfo(unknownType, getIntersectionType(map(applicableInfos, info => info.type)), reduceLeft(applicableInfos, (isReadonly, info) => isReadonly && info.isReadonly, /*initial*/ true)) : applicableInfo ? applicableInfo : stringIndexInfo && isApplicableIndexType(keyType, stringType) ? stringIndexInfo : undefined; @@ -14611,9 +14834,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === SyntaxKind.GetAccessor || declaration.kind === SyntaxKind.SetAccessor) && + if ( + (declaration.kind === SyntaxKind.GetAccessor || declaration.kind === SyntaxKind.SetAccessor) && hasBindableName(declaration) && - (!hasThisParameter || !thisParameter)) { + (!hasThisParameter || !thisParameter) + ) { const otherKind = declaration.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; const other = getDeclarationOfKind(getSymbolOfDeclaration(declaration), otherKind); if (other) { @@ -14636,13 +14861,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { flags |= SignatureFlags.HasRestParameter; } - if (isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, ModifierFlags.Abstract) || - isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, ModifierFlags.Abstract)) { + if ( + isConstructorTypeNode(declaration) && hasSyntacticModifier(declaration, ModifierFlags.Abstract) || + isConstructorDeclaration(declaration) && hasSyntacticModifier(declaration.parent, ModifierFlags.Abstract) + ) { flags |= SignatureFlags.Abstract; } - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, - minArgumentCount, flags); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -14659,8 +14884,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const lastParam = lastOrUndefined(declaration.parameters); const lastParamTags = lastParam ? getJSDocParameterTags(lastParam) : getJSDocTags(declaration).filter(isJSDocParameterTag); - const lastParamVariadicType = firstDefined(lastParamTags, p => - p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined); + const lastParamVariadicType = firstDefined(lastParamTags, p => p.typeExpression && isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined); const syntheticArgsSymbol = createSymbol(SymbolFlags.Variable, "args" as __String, CheckFlags.RestParameter); if (lastParamVariadicType) { @@ -14782,7 +15006,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { (!isFunctionExpressionOrArrowFunction(decl) && !isObjectLiteralMethod(decl) && getSignatureOfTypeTag(decl)) || - getSignatureFromDeclaration(decl) + getSignatureFromDeclaration(decl), ); } return result; @@ -14838,8 +15062,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const type = node.type && getTypeFromTypeNode(node.type); return parameterName.kind === SyntaxKind.ThisType ? createTypePredicate(node.assertsModifier ? TypePredicateKind.AssertsThis : TypePredicateKind.This, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) : - createTypePredicate(node.assertsModifier ? TypePredicateKind.AssertsIdentifier : TypePredicateKind.Identifier, parameterName.escapedText as string, - findIndex(signature.parameters, p => p.escapedName === parameterName.escapedText), type); + createTypePredicate(node.assertsModifier ? TypePredicateKind.AssertsIdentifier : TypePredicateKind.Identifier, parameterName.escapedText as string, findIndex(signature.parameters, p => p.escapedName === parameterName.escapedText), type); } function getUnionOrIntersectionType(types: Type[], kind: TypeFlags | undefined, unionReduction?: UnionReduction) { @@ -14994,7 +15217,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getSignatureInstantiation( signature, map(signature.typeParameters, tp => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp), - isInJSFile(signature.declaration)); + isInJSFile(signature.declaration), + ); } function getBaseSignature(signature: Signature) { @@ -15067,8 +15291,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (parameter.type) { forEachType(getTypeFromTypeNode(parameter.type), keyType => { if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos, keyType)) { - indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, - hasEffectiveModifier(declaration, ModifierFlags.Readonly), declaration)); + indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, hasEffectiveModifier(declaration, ModifierFlags.Readonly), declaration)); } }); } @@ -15112,9 +15335,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // type Foo = [T, U]; // type Bar = T extends Foo ? Foo : T; // the instantiated constraint for U is X, so we discard that inference. - const mapper = makeDeferredTypeMapper(typeParameters, typeParameters.map((_, index) => () => { - return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index); - })); + const mapper = makeDeferredTypeMapper( + typeParameters, + typeParameters.map((_, index) => () => { + return getEffectiveTypeArgumentAtIndex(typeReference, typeParameters, index); + }), + ); const constraint = instantiateType(declaredConstraint, mapper); if (constraint !== typeParameter) { inferences = append(inferences, constraint); @@ -15125,9 +15351,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. - else if (grandParent.kind === SyntaxKind.Parameter && (grandParent as ParameterDeclaration).dotDotDotToken || + else if ( + grandParent.kind === SyntaxKind.Parameter && (grandParent as ParameterDeclaration).dotDotDotToken || grandParent.kind === SyntaxKind.RestType || - grandParent.kind === SyntaxKind.NamedTupleMember && (grandParent as NamedTupleMember).dotDotDotToken) { + grandParent.kind === SyntaxKind.NamedTupleMember && (grandParent as NamedTupleMember).dotDotDotToken + ) { inferences = append(inferences, createArrayType(unknownType)); } // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string' @@ -15143,15 +15371,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // When an 'infer T' declaration is the template of a mapped type, and that mapped type is the extends // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template // of the check type's mapped type - else if (grandParent.kind === SyntaxKind.MappedType && (grandParent as MappedTypeNode).type && + else if ( + grandParent.kind === SyntaxKind.MappedType && (grandParent as MappedTypeNode).type && skipParentheses((grandParent as MappedTypeNode).type!) === declaration.parent && grandParent.parent.kind === SyntaxKind.ConditionalType && (grandParent.parent as ConditionalTypeNode).extendsType === grandParent && (grandParent.parent as ConditionalTypeNode).checkType.kind === SyntaxKind.MappedType && - ((grandParent.parent as ConditionalTypeNode).checkType as MappedTypeNode).type) { + ((grandParent.parent as ConditionalTypeNode).checkType as MappedTypeNode).type + ) { const checkMappedType = (grandParent.parent as ConditionalTypeNode).checkType as MappedTypeNode; const nodeType = getTypeFromTypeNode(checkMappedType.type!); - inferences = append(inferences, instantiateType(nodeType, - makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType.typeParameter)), checkMappedType.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType.typeParameter.constraint) : keyofConstraintType) - )); + inferences = append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType.typeParameter)), checkMappedType.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType.typeParameter.constraint) : keyofConstraintType))); } } } @@ -15295,7 +15523,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error( type.node || currentNode, type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves, - type.target.symbol && symbolToString(type.target.symbol) + type.target.symbol && symbolToString(type.target.symbol), ); } } @@ -15306,7 +15534,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return length(type.target.typeParameters); } - /** * Get type from type-reference that reference to class or interface */ @@ -15325,8 +15552,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { 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; + 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); @@ -15357,9 +15584,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments); let instantiation = links.instantiations!.get(id); if (!instantiation) { - links.instantiations!.set(id, instantiation = instantiateTypeWithAlias(type, - createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))), - aliasSymbol, aliasTypeArguments)); + links.instantiations!.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments)); } return instantiation; } @@ -15388,13 +15613,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const numTypeArguments = length(node.typeArguments); const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { - error(node, + 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); + typeParameters.length, + ); return errorType; } // We refrain from associating a local type alias with an instantiation of a top-level type alias @@ -15440,7 +15667,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isEntityNameExpression(expr)) { return expr; } - // fall through; + // fall through; } return undefined; @@ -15716,7 +15943,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function getTypeOfGlobalSymbol(symbol: Symbol | undefined, arity: number): ObjectType { - function getTypeDeclaration(symbol: Symbol): Declaration | undefined { const declarations = symbol.declarations; if (declarations) { @@ -16020,9 +16246,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // because it is possibly contained in a circular chain of eagerly resolved types. function isDeferredTypeReferenceNode(node: TypeReferenceNode | ArrayTypeNode | TupleTypeNode, hasDefaultTypeArguments?: boolean) { return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && ( - node.kind === SyntaxKind.ArrayType ? mayResolveTypeAlias(node.elementType) : - node.kind === SyntaxKind.TupleType ? some(node.elements, mayResolveTypeAlias) : - hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias)); + node.kind === SyntaxKind.ArrayType ? mayResolveTypeAlias(node.elementType) : + node.kind === SyntaxKind.TupleType ? some(node.elements, mayResolveTypeAlias) : + hasDefaultTypeArguments || some(node.typeArguments, mayResolveTypeAlias) + ); } // Return true when the given node is transitively contained in type constructs that eagerly @@ -16146,8 +16373,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const flags = elementFlags[i]; combinedFlags |= flags; if (!(combinedFlags & ElementFlags.Variable)) { - const property = createSymbol(SymbolFlags.Property | (flags & ElementFlags.Optional ? SymbolFlags.Optional : 0), - "" + i as __String, readonly ? CheckFlags.Readonly : 0); + const property = createSymbol(SymbolFlags.Property | (flags & ElementFlags.Optional ? SymbolFlags.Optional : 0), "" + i as __String, readonly ? CheckFlags.Readonly : 0); property.links.tupleLabelDeclaration = namedMemberDeclarations?.[i]; property.links.type = typeParameter; properties.push(property); @@ -16230,9 +16456,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (isTupleType(type)) { const elements = getElementTypes(type); if (elements.length + expandedTypes.length >= 10_000) { - error(currentNode, isPartOfTypeNode(currentNode!) - ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent - : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent); + error( + currentNode, + isPartOfTypeNode(currentNode!) + ? Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent + : Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent, + ); return errorType; } // Spread variadic elements with tuple types into the resulting tuple. @@ -16254,8 +16483,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) { // Turn elements between first rest and last optional/rest into a single rest element - expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), - (t, i) => expandedFlags[firstRestIndex + i] & ElementFlags.Variadic ? getIndexedAccessType(t, numberType) : t)); + expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), (t, i) => expandedFlags[firstRestIndex + i] & ElementFlags.Variadic ? getIndexedAccessType(t, numberType) : t)); expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); expandedFlags.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex); @@ -16285,13 +16513,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const target = type.target; const endIndex = getTypeReferenceArity(type) - endSkipCount; return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(emptyArray) : - createTupleType(getTypeArguments(type).slice(index, endIndex), target.elementFlags.slice(index, endIndex), - /*readonly*/ false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex)); + createTupleType(getTypeArguments(type).slice(index, endIndex), target.elementFlags.slice(index, endIndex), /*readonly*/ false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex)); } function getKnownKeysOfTupleType(type: TupleTypeReference) { - return getUnionType(append(arrayOf(type.target.fixedLength, i => getStringLiteralType("" + i)), - getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType))); + return getUnionType(append(arrayOf(type.target.fixedLength, i => getStringLiteralType("" + i)), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType))); } // Return count of starting consecutive tuple elements of the given kind(s) @@ -16436,10 +16662,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { continue; } } - if (isTypeRelatedTo(source, target, strictSubtypeRelation) && ( - !(getObjectFlags(getTargetType(source)) & ObjectFlags.Class) || - !(getObjectFlags(getTargetType(target)) & ObjectFlags.Class) || - isTypeDerivedFrom(source, target))) { + if ( + isTypeRelatedTo(source, target, strictSubtypeRelation) && ( + !(getObjectFlags(getTargetType(source)) & ObjectFlags.Class) || + !(getObjectFlags(getTargetType(target)) & ObjectFlags.Class) || + isTypeDerivedFrom(source, target) + ) + ) { orderedRemoveItemAt(types, i); break; } @@ -16457,8 +16686,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { i--; const t = types[i]; const flags = t.flags; - const remove = - flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) && includes & TypeFlags.String || + const remove = flags & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) && includes & TypeFlags.String || flags & TypeFlags.NumberLiteral && includes & TypeFlags.Number || flags & TypeFlags.BigIntLiteral && includes & TypeFlags.BigInt || flags & TypeFlags.UniqueESSymbol && includes & TypeFlags.ESSymbol || @@ -16474,8 +16702,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const templates = filter(types, t => !!(t.flags & TypeFlags.TemplateLiteral) && isPatternLiteralType(t) && - (t as TemplateLiteralType).types.every(t => !(t.flags & TypeFlags.Intersection) || !areIntersectedTypesAvoidingPrimitiveReduction((t as IntersectionType).types)) - ) as TemplateLiteralType[]; + (t as TemplateLiteralType).types.every(t => !(t.flags & TypeFlags.Intersection) || !areIntersectedTypesAvoidingPrimitiveReduction((t as IntersectionType).types))) as TemplateLiteralType[]; if (templates.length) { let i = types.length; while (i > 0) { @@ -16667,8 +16894,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const links = getNodeLinks(node); if (!links.resolvedType) { const aliasSymbol = getAliasSymbolForTypeNode(node); - links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), UnionReduction.Literal, - aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); + links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), UnionReduction.Literal, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -16721,8 +16947,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { while (i > 0) { i--; const t = types[i]; - const remove = - t.flags & TypeFlags.String && includes & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) || + const remove = t.flags & TypeFlags.String && includes & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) || t.flags & TypeFlags.Number && includes & TypeFlags.NumberLiteral || t.flags & TypeFlags.BigInt && includes & TypeFlags.BigIntLiteral || t.flags & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol || @@ -16863,13 +17088,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (includes & TypeFlags.Never) { return contains(typeSet, silentNeverType) ? silentNeverType : neverType; } - if (strictNullChecks && includes & TypeFlags.Nullable && includes & (TypeFlags.Object | TypeFlags.NonPrimitive | TypeFlags.IncludesEmptyObject) || + if ( + strictNullChecks && includes & TypeFlags.Nullable && includes & (TypeFlags.Object | TypeFlags.NonPrimitive | TypeFlags.IncludesEmptyObject) || includes & TypeFlags.NonPrimitive && includes & (TypeFlags.DisjointDomains & ~TypeFlags.NonPrimitive) || includes & TypeFlags.StringLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.StringLike) || includes & TypeFlags.NumberLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.NumberLike) || includes & TypeFlags.BigIntLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.BigIntLike) || includes & TypeFlags.ESSymbolLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.ESSymbolLike) || - includes & TypeFlags.VoidLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.VoidLike)) { + includes & TypeFlags.VoidLike && includes & (TypeFlags.DisjointDomains & ~TypeFlags.VoidLike) + ) { return neverType; } if (includes & TypeFlags.TemplateLiteral && includes & TypeFlags.StringLiteral && extractRedundantTemplateLiterals(typeSet)) { @@ -16881,12 +17108,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!strictNullChecks && includes & TypeFlags.Nullable) { return includes & TypeFlags.IncludesEmptyObject ? neverType : includes & TypeFlags.Undefined ? undefinedType : nullType; } - if (includes & TypeFlags.String && includes & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) || + if ( + includes & TypeFlags.String && includes & (TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) || includes & TypeFlags.Number && includes & TypeFlags.NumberLiteral || includes & TypeFlags.BigInt && includes & TypeFlags.BigIntLiteral || includes & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol || includes & TypeFlags.Void && includes & TypeFlags.Undefined || - includes & TypeFlags.IncludesEmptyObject && includes & TypeFlags.DefinitelyNonNullable) { + includes & TypeFlags.IncludesEmptyObject && includes & TypeFlags.DefinitelyNonNullable + ) { if (!noSupertypeReduction) removeRedundantSupertypes(typeSet, includes); } if (includes & TypeFlags.IncludesMissingType) { @@ -17063,7 +17292,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // we had to pick apart the constraintType to potentially map/filter it - compare the final resulting list with the original constraintType, // so we can return the union that preserves aliases/origin data if possible const result = indexFlags & IndexFlags.NoIndexSignatures ? filterType(getUnionType(keyTypes), t => !(t.flags & (TypeFlags.Any | TypeFlags.String))) : getUnionType(keyTypes); - if (result.flags & TypeFlags.Union && constraintType.flags & TypeFlags.Union && getTypeListId((result as UnionType).types) === getTypeListId((constraintType as UnionType).types)){ + if (result.flags & TypeFlags.Union && constraintType.flags & TypeFlags.Union && getTypeListId((result as UnionType).types) === getTypeListId((constraintType as UnionType).types)) { return constraintType; } return result; @@ -17089,7 +17318,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type.flags & TypeFlags.Conditional ? (type as ConditionalType).root.isDistributive && (type as ConditionalType).checkType === typeVariable : type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) ? every((type as UnionOrIntersectionType | TemplateLiteralType).types, isDistributive) : type.flags & TypeFlags.IndexedAccess ? isDistributive((type as IndexedAccessType).objectType) && isDistributive((type as IndexedAccessType).indexType) : - type.flags & TypeFlags.Substitution ? isDistributive((type as SubstitutionType).baseType) && isDistributive((type as SubstitutionType).constraint): + type.flags & TypeFlags.Substitution ? isDistributive((type as SubstitutionType).baseType) && isDistributive((type as SubstitutionType).constraint) : type.flags & TypeFlags.StringMapping ? isDistributive((type as StringMappingType).type) : false; } @@ -17137,10 +17366,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getLiteralTypeFromProperties(type: Type, include: TypeFlags, includeOrigin: boolean) { const origin = includeOrigin && (getObjectFlags(type) & (ObjectFlags.ClassOrInterface | ObjectFlags.Reference) || type.aliasSymbol) ? createOriginIndexType(type) : undefined; const propertyTypes = map(getPropertiesOfType(type), prop => getLiteralTypeFromProperty(prop, include)); - const indexKeyTypes = map(getIndexInfosOfType(type), info => info !== enumNumberIndexInfo && isKeyTypeIncluded(info.keyType, include) ? - info.keyType === stringType && include & TypeFlags.Number ? stringOrNumberType : info.keyType : neverType); - return getUnionType(concatenate(propertyTypes, indexKeyTypes), UnionReduction.Literal, - /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, origin); + const indexKeyTypes = map(getIndexInfosOfType(type), info => + info !== enumNumberIndexInfo && isKeyTypeIncluded(info.keyType, include) ? + info.keyType === stringType && include & TypeFlags.Number ? stringOrNumberType : info.keyType : neverType); + return getUnionType(concatenate(propertyTypes, indexKeyTypes), UnionReduction.Literal, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, origin); } function shouldDeferIndexType(type: Type, indexFlags = IndexFlags.None) { @@ -17160,8 +17389,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type === wildcardType ? wildcardType : type.flags & TypeFlags.Unknown ? neverType : type.flags & (TypeFlags.Any | TypeFlags.Never) ? keyofConstraintType : - getLiteralTypeFromProperties(type, (indexFlags & IndexFlags.NoIndexSignatures ? TypeFlags.StringLiteral : TypeFlags.StringLike) | (indexFlags & IndexFlags.StringsOnly ? 0 : TypeFlags.NumberLike | TypeFlags.ESSymbolLike), - indexFlags === defaultIndexFlags); + getLiteralTypeFromProperties(type, (indexFlags & IndexFlags.NoIndexSignatures ? TypeFlags.StringLiteral : TypeFlags.StringLike) | (indexFlags & IndexFlags.StringsOnly ? 0 : TypeFlags.NumberLike | TypeFlags.ESSymbolLike), indexFlags === defaultIndexFlags); } function getExtractStringType(type: Type) { @@ -17204,7 +17432,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!links.resolvedType) { links.resolvedType = getTemplateLiteralType( [node.head.text, ...map(node.templateSpans, span => span.literal.text)], - map(node.templateSpans, span => getTypeFromTypeNode(span.type))); + map(node.templateSpans, span => getTypeFromTypeNode(span.type)), + ); } return links.resolvedType; } @@ -17300,20 +17529,28 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function applyStringMapping(symbol: Symbol, str: string) { switch (intrinsicTypeKinds.get(symbol.escapedName as string)) { - case IntrinsicTypeKind.Uppercase: return str.toUpperCase(); - case IntrinsicTypeKind.Lowercase: return str.toLowerCase(); - case IntrinsicTypeKind.Capitalize: return str.charAt(0).toUpperCase() + str.slice(1); - case IntrinsicTypeKind.Uncapitalize: return str.charAt(0).toLowerCase() + str.slice(1); + case IntrinsicTypeKind.Uppercase: + return str.toUpperCase(); + case IntrinsicTypeKind.Lowercase: + return str.toLowerCase(); + case IntrinsicTypeKind.Capitalize: + return str.charAt(0).toUpperCase() + str.slice(1); + case IntrinsicTypeKind.Uncapitalize: + return str.charAt(0).toLowerCase() + str.slice(1); } return str; } function applyTemplateStringMapping(symbol: Symbol, texts: readonly string[], types: readonly Type[]): [texts: readonly string[], types: readonly Type[]] { switch (intrinsicTypeKinds.get(symbol.escapedName as string)) { - case IntrinsicTypeKind.Uppercase: return [texts.map(t => t.toUpperCase()), types.map(t => getStringMappingType(symbol, t))]; - case IntrinsicTypeKind.Lowercase: return [texts.map(t => t.toLowerCase()), types.map(t => getStringMappingType(symbol, t))]; - case IntrinsicTypeKind.Capitalize: return [texts[0] === "" ? texts : [texts[0].charAt(0).toUpperCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types]; - case IntrinsicTypeKind.Uncapitalize: return [texts[0] === "" ? texts : [texts[0].charAt(0).toLowerCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types]; + case IntrinsicTypeKind.Uppercase: + return [texts.map(t => t.toUpperCase()), types.map(t => getStringMappingType(symbol, t))]; + case IntrinsicTypeKind.Lowercase: + return [texts.map(t => t.toLowerCase()), types.map(t => getStringMappingType(symbol, t))]; + case IntrinsicTypeKind.Capitalize: + return [texts[0] === "" ? texts : [texts[0].charAt(0).toUpperCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types]; + case IntrinsicTypeKind.Uncapitalize: + return [texts[0] === "" ? texts : [texts[0].charAt(0).toLowerCase() + texts[0].slice(1), ...texts.slice(1)], texts[0] === "" ? [getStringMappingType(symbol, types[0]), ...types.slice(1)] : types]; } return [texts, types]; } @@ -17375,10 +17612,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getPropertyNameFromIndex(indexType: Type, accessNode: StringLiteral | Identifier | PrivateIdentifier | ObjectBindingPattern | ArrayBindingPattern | ComputedPropertyName | NumericLiteral | IndexedAccessTypeNode | ElementAccessExpression | SyntheticExpression | undefined) { return isTypeUsableAsPropertyName(indexType) ? getPropertyNameFromType(indexType) : - accessNode && isPropertyName(accessNode) ? - // late bound names are handled in the first branch, so here we only need to handle normal names - getPropertyNameForPropertyNameNode(accessNode) : - undefined; + accessNode && isPropertyName(accessNode) ? + // late bound names are handled in the first branch, so here we only need to handle normal names + getPropertyNameForPropertyNameNode(accessNode) : + undefined; } function isUncalledFunctionReference(node: Node, symbol: Symbol) { @@ -17433,8 +17670,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error(indexNode, Diagnostics.A_tuple_type_cannot_be_indexed_with_a_negative_value); return undefinedType; } - error(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, - typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName)); + error(indexNode, Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), unescapeLeadingUnderscores(propName)); } else { error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); @@ -17469,12 +17705,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // When accessing an enum object with its own type, // e.g. E[E.A] for enum E { A }, undefined shouldn't // be included in the result type - if ((accessFlags & AccessFlags.IncludeUndefined) && + if ( + (accessFlags & AccessFlags.IncludeUndefined) && !(objectType.symbol && objectType.symbol.flags & (SymbolFlags.RegularEnum | SymbolFlags.ConstEnum) && (indexType.symbol && - indexType.flags & TypeFlags.EnumLiteral && - getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + indexType.flags & TypeFlags.EnumLiteral && + getParentOfSymbol(indexType.symbol) === objectType.symbol)) + ) { return getUnionType([indexInfo.type, missingType]); } return indexInfo.type; @@ -17543,7 +17781,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { errorInfo = chainDiagnosticMessages( errorInfo, - Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, typeToString(fullIndexType), typeToString(objectType) + Diagnostics.Element_implicitly_has_an_any_type_because_expression_of_type_0_can_t_be_used_to_index_type_1, + typeToString(fullIndexType), + typeToString(objectType), ); diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(accessExpression), accessExpression, errorInfo)); } @@ -17781,9 +18021,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved // eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== SyntaxKind.IndexedAccessType ? - isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : - isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { + if ( + isGenericIndexType(indexType) || (accessNode && accessNode.kind !== SyntaxKind.IndexedAccessType ? + isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : + isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType)) + ) { if (objectType.flags & TypeFlags.AnyOrUnknown) { return objectType; } @@ -17858,9 +18100,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (type.flags & TypeFlags.Substitution) { return getActualTypeVariable((type as SubstitutionType).baseType); } - if (type.flags & TypeFlags.IndexedAccess && ( - (type as IndexedAccessType).objectType.flags & TypeFlags.Substitution || - (type as IndexedAccessType).indexType.flags & TypeFlags.Substitution)) { + if ( + type.flags & TypeFlags.IndexedAccess && ( + (type as IndexedAccessType).objectType.flags & TypeFlags.Substitution || + (type as IndexedAccessType).indexType.flags & TypeFlags.Substitution + ) + ) { return getIndexedAccessType(getActualTypeVariable((type as IndexedAccessType).objectType), getActualTypeVariable((type as IndexedAccessType).indexType)); } return type; @@ -18061,7 +18306,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isDistributionDependent(root: ConditionalRoot) { return root.isDistributive && ( isTypeParameterPossiblyReferenced(root.checkType as TypeParameter, root.node.trueType) || - isTypeParameterPossiblyReferenced(root.checkType as TypeParameter, root.node.falseType)); + isTypeParameterPossiblyReferenced(root.checkType as TypeParameter, root.node.falseType) + ); } function getTypeFromConditionalTypeNode(node: ConditionalTypeNode): Type { @@ -18081,7 +18327,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { outerTypeParameters, instantiations: undefined, aliasSymbol, - aliasTypeArguments + aliasTypeArguments, }; links.resolvedType = getConditionalType(root, /*mapper*/ undefined); if (outerTypeParameters) { @@ -18476,8 +18722,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false); const parent = container && container.parent; if (parent && (isClassLike(parent) || parent.kind === SyntaxKind.InterfaceDeclaration)) { - if (!isStatic(container) && - (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body))) { + if ( + !isStatic(container) && + (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body)) + ) { return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(parent as ClassLikeDeclaration | InterfaceDeclaration)).thisType!; } } @@ -18532,9 +18780,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getTypeFromNamedTupleTypeNode(node: NamedTupleMember): Type { const links = getNodeLinks(node); - return links.resolvedType || (links.resolvedType = - node.dotDotDotToken ? getTypeFromRestTypeNode(node) : - addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ true, !!node.questionToken)); + return links.resolvedType || (links.resolvedType = node.dotDotDotToken ? getTypeFromRestTypeNode(node) : + addOptionality(getTypeFromTypeNode(node.type), /*isProperty*/ true, !!node.questionToken)); } function getTypeFromTypeNode(node: TypeNode): Type { @@ -18765,9 +19012,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getRestrictiveTypeParameter(tp: TypeParameter) { return !tp.constraint && !getConstraintDeclaration(tp) || tp.constraint === noConstraintType ? tp : tp.restrictiveInstantiation || ( - tp.restrictiveInstantiation = createTypeParameter(tp.symbol), - (tp.restrictiveInstantiation as TypeParameter).constraint = noConstraintType, - tp.restrictiveInstantiation + tp.restrictiveInstantiation = createTypeParameter(tp.symbol), (tp.restrictiveInstantiation as TypeParameter).constraint = noConstraintType, tp.restrictiveInstantiation ); } @@ -18796,13 +19041,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Don't compute resolvedReturnType and resolvedTypePredicate now, // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.) // See GH#17600. - const result = createSignature(signature.declaration, freshTypeParameters, - signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), - instantiateList(signature.parameters, mapper, instantiateSymbol), - /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, - signature.minArgumentCount, - signature.flags & SignatureFlags.PropagatingFlags); + const result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & SignatureFlags.PropagatingFlags); result.target = signature; result.mapper = mapper; return result; @@ -18984,25 +19223,32 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (typeVariable) { const mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapTypeWithAlias(getReducedType(mappedTypeVariable), t => { - if (t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.InstantiableNonPrimitive | TypeFlags.Object | TypeFlags.Intersection) && t !== wildcardType && !isErrorType(t)) { - if (!type.declaration.nameType) { - let constraint; - if (isArrayType(t) || t.flags & TypeFlags.Any && findResolutionCycleStartIndex(typeVariable, TypeSystemPropertyName.ImmediateBaseConstraint) < 0 && - (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, isArrayOrTupleType)) { - return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); - } - if (isGenericTupleType(t)) { - return instantiateMappedGenericTupleType(t, type, typeVariable, mapper); - } - if (isTupleType(t)) { - return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper)); + return mapTypeWithAlias( + getReducedType(mappedTypeVariable), + t => { + if (t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.InstantiableNonPrimitive | TypeFlags.Object | TypeFlags.Intersection) && t !== wildcardType && !isErrorType(t)) { + if (!type.declaration.nameType) { + let constraint; + if ( + isArrayType(t) || t.flags & TypeFlags.Any && findResolutionCycleStartIndex(typeVariable, TypeSystemPropertyName.ImmediateBaseConstraint) < 0 && + (constraint = getConstraintOfTypeParameter(typeVariable)) && everyType(constraint, isArrayOrTupleType) + ) { + return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper)); + } + if (isGenericTupleType(t)) { + return instantiateMappedGenericTupleType(t, type, typeVariable, mapper); + } + if (isTupleType(t)) { + return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper)); + } } + return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); } - return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper)); - } - return t; - }, aliasSymbol, aliasTypeArguments); + return t; + }, + aliasSymbol, + aliasTypeArguments, + ); } } // If the constraint type of the instantiation is the wildcard type, return the wildcard type. @@ -19043,8 +19289,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function instantiateMappedTupleType(tupleType: TupleTypeReference, mappedType: MappedType, mapper: TypeMapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getElementTypes(tupleType), (_, i) => - instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & ElementFlags.Optional), mapper)); + const elementTypes = map(getElementTypes(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & ElementFlags.Optional), mapper)); const modifiers = getMappedTypeModifiers(mappedType); const newTupleModifiers = modifiers & MappedTypeModifiers.IncludeOptional ? map(elementFlags, f => f & ElementFlags.Required ? ElementFlags.Optional : f) : modifiers & MappedTypeModifiers.ExcludeOptional ? map(elementFlags, f => f & ElementFlags.Optional ? ElementFlags.Required : f) : @@ -19216,7 +19461,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const instantiated = inferTypeForHomomorphicMappedType( instantiateType(type.source, mapper), innerMappedType as MappedType, - innerIndexType as IndexType + innerIndexType as IndexType, ); if (instantiated) { return instantiated; @@ -19302,7 +19547,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (node.body.kind !== SyntaxKind.Block) { return isContextSensitive(node.body); } - return !!forEachReturnStatement(node.body as Block, (statement) => !!statement.expression && isContextSensitive(statement.expression)); + return !!forEachReturnStatement(node.body as Block, statement => !!statement.expression && isContextSensitive(statement.expression)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func: Node): func is FunctionExpression | ArrowFunction | MethodDeclaration { @@ -19398,7 +19643,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeAssignableTo(source: Type, target: Type, errorNode: Node | undefined, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined, errorOutputObject?: { errors?: Diagnostic[] }): boolean { + function checkTypeAssignableTo(source: Type, target: Type, errorNode: Node | undefined, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined, errorOutputObject?: { errors?: Diagnostic[]; }): boolean { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); } @@ -19418,7 +19663,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { expr: Expression | undefined, headMessage: DiagnosticMessage | undefined, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ): boolean { if (isTypeRelatedTo(source, target, relation)) return true; if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) { @@ -19438,11 +19683,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { relation: Map, headMessage: DiagnosticMessage | undefined, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ): boolean { if (!node || isOrHasGenericConditional(target)) return false; - if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) - && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) { + if ( + !checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) + && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) + ) { return true; } switch (node.kind) { @@ -19480,22 +19727,27 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { relation: Map, headMessage: DiagnosticMessage | undefined, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ): boolean { const callSignatures = getSignaturesOfType(source, SignatureKind.Call); const constructSignatures = getSignaturesOfType(source, SignatureKind.Construct); for (const signatures of [constructSignatures, callSignatures]) { - if (some(signatures, s => { - const returnType = getReturnTypeOfSignature(s); - return !(returnType.flags & (TypeFlags.Any | TypeFlags.Never)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); - })) { - const resultObj: { errors?: Diagnostic[] } = errorOutputContainer || {}; + if ( + some(signatures, s => { + const returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (TypeFlags.Any | TypeFlags.Never)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + }) + ) { + const resultObj: { errors?: Diagnostic[]; } = errorOutputContainer || {}; checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj); const diagnostic = resultObj.errors![resultObj.errors!.length - 1]; - addRelatedInfo(diagnostic, createDiagnosticForNode( - node, - signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression - )); + addRelatedInfo( + diagnostic, + createDiagnosticForNode( + node, + signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression, + ), + ); return true; } } @@ -19508,7 +19760,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { target: Type, relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ): boolean { // Don't elaborate blocks if (isBlock(node.body)) { @@ -19534,25 +19786,32 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (elaborated) { return elaborated; } - const resultObj: { errors?: Diagnostic[] } = errorOutputContainer || {}; + const resultObj: { errors?: Diagnostic[]; } = errorOutputContainer || {}; checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*headMessage*/ undefined, containingMessageChain, resultObj); if (resultObj.errors) { if (target.symbol && length(target.symbol.declarations)) { - addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode( - target.symbol.declarations![0], - Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature, - )); + addRelatedInfo( + resultObj.errors[resultObj.errors.length - 1], + createDiagnosticForNode( + target.symbol.declarations![0], + Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature, + ), + ); } - if ((getFunctionFlags(node) & FunctionFlags.Async) === 0 + if ( + (getFunctionFlags(node) & FunctionFlags.Async) === 0 // exclude cases where source itself is promisy - this way we don't make a suggestion when relating // an IPromise and a Promise that are slightly different && !getTypeOfPropertyOfType(sourceReturn, "then" as __String) && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined) ) { - addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], createDiagnosticForNode( - node, - Diagnostics.Did_you_mean_to_mark_this_function_as_async - )); + addRelatedInfo( + resultObj.errors[resultObj.errors.length - 1], + createDiagnosticForNode( + node, + Diagnostics.Did_you_mean_to_mark_this_function_as_async, + ), + ); } return true; } @@ -19580,7 +19839,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return result; } - type ElaborationIterator = IterableIterator<{ errorNode: Node, innerExpression: Expression | undefined, nameType: Type, errorMessage?: DiagnosticMessage | undefined }>; + type ElaborationIterator = IterableIterator<{ errorNode: Node; innerExpression: Expression | undefined; nameType: Type; errorMessage?: DiagnosticMessage | undefined; }>; /** * For every element returned from the iterator, checks that element to issue an error on a property of that element's type * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` @@ -19592,7 +19851,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { target: Type, relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span let reportedError = false; @@ -19608,7 +19867,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { reportedError = true; if (!elaborated) { // Issue error on the prop itself, since the prop couldn't elaborate the error - const resultObj: { errors?: Diagnostic[] } = errorOutputContainer || {}; + const resultObj: { errors?: Diagnostic[]; } = errorOutputContainer || {}; // Use the expression type, if available const specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; if (exactOptionalPropertyTypes && isExactOptionalPropertyMismatch(specificSource, targetPropType)) { @@ -19644,12 +19903,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!issuedElaboration && (targetProp && length(targetProp.declarations) || target.symbol && length(target.symbol.declarations))) { const targetNode = targetProp && length(targetProp.declarations) ? targetProp.declarations![0] : target.symbol.declarations![0]; if (!getSourceFileOfNode(targetNode).hasNoDefaultLib) { - addRelatedInfo(reportedDiag, createDiagnosticForNode( - targetNode, - Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, - propertyName && !(nameType.flags & TypeFlags.UniqueESSymbol) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), - typeToString(target) - )); + addRelatedInfo( + reportedDiag, + createDiagnosticForNode( + targetNode, + Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, + propertyName && !(nameType.flags & TypeFlags.UniqueESSymbol) ? unescapeLeadingUnderscores(propertyName) : typeToString(nameType), + typeToString(target), + ), + ); } } } @@ -19669,7 +19931,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { target: Type, relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ) { const tupleOrArrayLikeTargetParts = filterType(target, isArrayOrTupleLikeType); const nonTupleOrArrayLikeTargetParts = filterType(target, t => !isArrayOrTupleLikeType(t)); @@ -19683,7 +19945,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value; let targetPropType = iterationType; const targetIndexedPropType = tupleOrArrayLikeTargetParts !== neverType ? getBestMatchIndexedAccessTypeOrUndefined(source, tupleOrArrayLikeTargetParts, nameType) : undefined; - if (targetIndexedPropType && !(targetIndexedPropType.flags & TypeFlags.IndexedAccess)) { // Don't elaborate on indexes on generic variables + if (targetIndexedPropType && !(targetIndexedPropType.flags & TypeFlags.IndexedAccess)) { // Don't elaborate on indexes on generic variables targetPropType = iterationType ? getUnionType([iterationType, targetIndexedPropType]) : targetIndexedPropType; } if (!targetPropType) continue; @@ -19695,7 +19957,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { reportedError = true; if (!elaborated) { // Issue error on the prop itself, since the prop couldn't elaborate the error - const resultObj: { errors?: Diagnostic[] } = errorOutputContainer || {}; + const resultObj: { errors?: Diagnostic[]; } = errorOutputContainer || {}; // Use the expression type, if available const specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; if (exactOptionalPropertyTypes && isExactOptionalPropertyMismatch(specificSource, targetPropType)) { @@ -19720,8 +19982,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return reportedError; } - - function *generateJsxAttributes(node: JsxAttributes): ElaborationIterator { + function* generateJsxAttributes(node: JsxAttributes): ElaborationIterator { if (!length(node.properties)) return; for (const prop of node.properties) { if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(getTextOfJsxAttributeName(prop.name))) continue; @@ -19729,7 +19990,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - function *generateJsxChildren(node: JsxElement, getInvalidTextDiagnostic: () => DiagnosticMessage): ElaborationIterator { + function* generateJsxChildren(node: JsxElement, getInvalidTextDiagnostic: () => DiagnosticMessage): ElaborationIterator { if (!length(node.children)) return; let memberOffset = 0; for (let i = 0; i < node.children.length; i++) { @@ -19772,7 +20033,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { target: Type, relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ) { let result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer); let invalidTextDiagnostic: DiagnosticMessage | undefined; @@ -19812,7 +20073,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { containingElement.openingElement.tagName, Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, - typeToString(childrenTargetType) + typeToString(childrenTargetType), ); if (errorOutputContainer && errorOutputContainer.skipLogging) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -19825,12 +20086,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const elem = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); if (elem) { result = elaborateElementwise( - (function*() { yield elem; })(), + (function* () { + yield elem; + })(), source, target, relation, containingMessageChain, - errorOutputContainer + errorOutputContainer, ) || result; } } @@ -19841,7 +20104,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { containingElement.openingElement.tagName, Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, - typeToString(childrenTargetType) + typeToString(childrenTargetType), ); if (errorOutputContainer && errorOutputContainer.skipLogging) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); @@ -19864,7 +20127,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - function *generateLimitedTupleElements(node: ArrayLiteralExpression, target: Type): ElaborationIterator { + function* generateLimitedTupleElements(node: ArrayLiteralExpression, target: Type): ElaborationIterator { const len = length(node.elements); if (!len) return; for (let i = 0; i < len; i++) { @@ -19883,7 +20146,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { target: Type, relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ) { if (target.flags & (TypeFlags.Primitive | TypeFlags.Never)) return false; if (isTupleLikeType(source)) { @@ -19900,7 +20163,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } - function *generateObjectLiteralElements(node: ObjectLiteralExpression): ElaborationIterator { + function* generateObjectLiteralElements(node: ObjectLiteralExpression): ElaborationIterator { if (!length(node.properties)) return; for (const prop of node.properties) { if (isSpreadAssignment(prop)) continue; @@ -19930,7 +20193,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { target: Type, relation: Map, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } | undefined + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } | undefined, ) { if (target.flags & (TypeFlags.Primitive | TypeFlags.Never)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); @@ -19944,11 +20207,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); } - function isSignatureAssignableTo(source: Signature, - target: Signature, - ignoreReturnTypes: boolean): boolean { - return compareSignaturesRelated(source, target, ignoreReturnTypes ? SignatureCheckMode.IgnoreReturnTypes : SignatureCheckMode.None, /*reportErrors*/ false, - /*errorReporter*/ undefined, /*incompatibleErrorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== Ternary.False; + function isSignatureAssignableTo(source: Signature, target: Signature, ignoreReturnTypes: boolean): boolean { + return compareSignaturesRelated(source, target, ignoreReturnTypes ? SignatureCheckMode.IgnoreReturnTypes : SignatureCheckMode.None, /*reportErrors*/ false, /*errorReporter*/ undefined, /*incompatibleErrorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== Ternary.False; } type ErrorReporter = (message: DiagnosticMessage, ...args: DiagnosticArguments) => void; @@ -19968,14 +20228,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /** * See signatureRelatedTo, compareSignaturesIdentical */ - function compareSignaturesRelated(source: Signature, - target: Signature, - checkMode: SignatureCheckMode, - reportErrors: boolean, - errorReporter: ErrorReporter | undefined, - incompatibleErrorReporter: ((source: Type, target: Type) => void) | undefined, - compareTypes: TypeComparer, - reportUnreliableMarkers: TypeMapper | undefined): Ternary { + function compareSignaturesRelated(source: Signature, target: Signature, checkMode: SignatureCheckMode, reportErrors: boolean, errorReporter: ErrorReporter | undefined, incompatibleErrorReporter: ((source: Type, target: Type) => void) | undefined, compareTypes: TypeComparer, reportUnreliableMarkers: TypeMapper | undefined): Ternary { // TODO (drosen): De-duplicate code between related functions. if (source === target) { return Ternary.True; @@ -20062,9 +20315,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (!related) { if (reportErrors) { - errorReporter!(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, - unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), - unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); + errorReporter!(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); } return Ternary.False; } @@ -20109,7 +20360,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { incompatibleErrorReporter(sourceReturnType, targetReturnType); } } - } return result; @@ -20120,7 +20370,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { target: TypePredicate, reportErrors: boolean, errorReporter: ErrorReporter | undefined, - compareTypes: (s: Type, t: Type, reportErrors?: boolean) => Ternary): Ternary { + compareTypes: (s: Type, t: Type, reportErrors?: boolean) => Ternary, + ): Ternary { if (source.kind !== target.kind) { if (reportErrors) { errorReporter!(Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -20155,10 +20406,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // First see if the return types are compatible in either direction. const sourceReturnType = getReturnTypeOfSignature(erasedSource); const targetReturnType = getReturnTypeOfSignature(erasedTarget); - if (targetReturnType === voidType + if ( + targetReturnType === voidType || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { - + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation) + ) { return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); } @@ -20184,7 +20436,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isEmptyAnonymousObjectType(type: Type) { return !!(getObjectFlags(type) & ObjectFlags.Anonymous && ( (type as ResolvedType).members && isEmptyResolvedType(type as ResolvedType) || - type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral && getMembersOfSymbol(type.symbol).size === 0)); + type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral && getMembersOfSymbol(type.symbol).size === 0 + )); } function isUnknownLikeUnionType(type: Type) { @@ -20192,7 +20445,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!((type as UnionType).objectFlags & ObjectFlags.IsUnknownLikeUnionComputed)) { const types = (type as UnionType).types; (type as UnionType).objectFlags |= ObjectFlags.IsUnknownLikeUnionComputed | (types.length >= 3 && types[0].flags & TypeFlags.Undefined && - types[1].flags & TypeFlags.Null && some(types, isEmptyAnonymousObjectType) ? ObjectFlags.IsUnknownLikeUnion : 0); + types[1].flags & TypeFlags.Null && some(types, isEmptyAnonymousObjectType) ? ObjectFlags.IsUnknownLikeUnion : 0); } return !!((type as UnionType).objectFlags & ObjectFlags.IsUnknownLikeUnion); } @@ -20229,8 +20482,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & SymbolFlags.EnumMember)) { if (errorReporter) { - errorReporter(Diagnostics.Property_0_is_missing_in_type_1, symbolName(property), - typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType)); + errorReporter(Diagnostics.Property_0_is_missing_in_type_1, symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType)); enumRelation.set(id, RelationComparisonResult.Failed | RelationComparisonResult.Reported); } else { @@ -20251,22 +20503,30 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (t & TypeFlags.Unknown && !(relation === strictSubtypeRelation && s & TypeFlags.Any)) return true; if (t & TypeFlags.Never) return false; if (s & TypeFlags.StringLike && t & TypeFlags.String) return true; - if (s & TypeFlags.StringLiteral && s & TypeFlags.EnumLiteral && + if ( + s & TypeFlags.StringLiteral && s & TypeFlags.EnumLiteral && t & TypeFlags.StringLiteral && !(t & TypeFlags.EnumLiteral) && - (source as StringLiteralType).value === (target as StringLiteralType).value) return true; + (source as StringLiteralType).value === (target as StringLiteralType).value + ) return true; if (s & TypeFlags.NumberLike && t & TypeFlags.Number) return true; - if (s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral && + if ( + s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral && t & TypeFlags.NumberLiteral && !(t & TypeFlags.EnumLiteral) && - (source as NumberLiteralType).value === (target as NumberLiteralType).value) return true; + (source as NumberLiteralType).value === (target as NumberLiteralType).value + ) return true; if (s & TypeFlags.BigIntLike && t & TypeFlags.BigInt) return true; if (s & TypeFlags.BooleanLike && t & TypeFlags.Boolean) return true; if (s & TypeFlags.ESSymbolLike && t & TypeFlags.ESSymbol) return true; - if (s & TypeFlags.Enum && t & TypeFlags.Enum && source.symbol.escapedName === target.symbol.escapedName && - isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if ( + s & TypeFlags.Enum && t & TypeFlags.Enum && source.symbol.escapedName === target.symbol.escapedName && + isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter) + ) return true; if (s & TypeFlags.EnumLiteral && t & TypeFlags.EnumLiteral) { if (s & TypeFlags.Union && t & TypeFlags.Union && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & TypeFlags.Literal && t & TypeFlags.Literal && (source as LiteralType).value === (target as LiteralType).value && - isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if ( + s & TypeFlags.Literal && t & TypeFlags.Literal && (source as LiteralType).value === (target as LiteralType).value && + isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter) + ) return true; } // In non-strictNullChecks mode, `undefined` and `null` are assignable to anything except `never`. // Since unions and intersections may reduce to `never`, we exclude them here. @@ -20279,9 +20539,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // a numeric literal type is assignable any computed numeric enum type or any numeric enum literal type // with a matching value. These rules exist such that enums can be used for bit-flag purposes. if (s & TypeFlags.Number && (t & TypeFlags.Enum || t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral)) return true; - if (s & TypeFlags.NumberLiteral && !(s & TypeFlags.EnumLiteral) && (t & TypeFlags.Enum || - t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral && - (source as NumberLiteralType).value === (target as NumberLiteralType).value)) return true; + if ( + s & TypeFlags.NumberLiteral && !(s & TypeFlags.EnumLiteral) && (t & TypeFlags.Enum || + t & TypeFlags.NumberLiteral && t & TypeFlags.EnumLiteral && + (source as NumberLiteralType).value === (target as NumberLiteralType).value) + ) return true; // Anything is assignable to a union containing undefined, null, and {} if (isUnknownLikeUnionType(target)) return true; } @@ -20376,9 +20638,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { errorNode: Node | undefined, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined, - errorOutputContainer?: { errors?: Diagnostic[], skipLogging?: boolean }, + errorOutputContainer?: { errors?: Diagnostic[]; skipLogging?: boolean; }, ): boolean { - let errorInfo: DiagnosticMessageChain | undefined; let relatedInfo: [DiagnosticRelatedInformation, ...DiagnosticRelatedInformation[]] | undefined; let maybeKeys: string[]; @@ -20445,7 +20706,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error."); } - return result !== Ternary.False; function resetErrorInfo(saved: ReturnType) { @@ -20536,13 +20796,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else { const prefix = (msg.code === Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code || - msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) - ? "new " - : ""; + msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) + ? "new " + : ""; const params = (msg.code === Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code || - msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) - ? "" - : "..."; + msg.code === Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) + ? "" + : "..."; path = `${prefix}${path}(${params})`; } break; @@ -20560,10 +20820,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } if (path) { - reportError(path[path.length - 1] === ")" - ? Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types - : Diagnostics.The_types_of_0_are_incompatible_between_these_types, - path + reportError( + path[path.length - 1] === ")" + ? Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types + : Diagnostics.The_types_of_0_are_incompatible_between_these_types, + path, ); } else { @@ -20621,31 +20882,31 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); } - // If `target` is of indexed access type (And `source` it is not), we use the object type of `target` for better error reporting - const targetFlags = target.flags & TypeFlags.IndexedAccess && !(source.flags & TypeFlags.IndexedAccess) ? - (target as IndexedAccessType).objectType.flags : - target.flags; - - if (targetFlags & TypeFlags.TypeParameter && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { - const constraint = getBaseConstraintOfType(target); - let needsOriginalSource; - if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { - reportError( - Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, - needsOriginalSource ? sourceType : generalizedSourceType, - targetType, - typeToString(constraint), - ); - } - else { - errorInfo = undefined; - reportError( - Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, - targetType, - generalizedSourceType - ); - } + // If `target` is of indexed access type (And `source` it is not), we use the object type of `target` for better error reporting + const targetFlags = target.flags & TypeFlags.IndexedAccess && !(source.flags & TypeFlags.IndexedAccess) ? + (target as IndexedAccessType).objectType.flags : + target.flags; + + if (targetFlags & TypeFlags.TypeParameter && target !== markerSuperTypeForCheck && target !== markerSubTypeForCheck) { + const constraint = getBaseConstraintOfType(target); + let needsOriginalSource; + if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) { + reportError( + Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, + needsOriginalSource ? sourceType : generalizedSourceType, + targetType, + typeToString(constraint), + ); + } + else { + errorInfo = undefined; + reportError( + Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, + targetType, + generalizedSourceType, + ); } + } if (!message) { if (relation === comparableRelation) { @@ -20668,9 +20929,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { message = Diagnostics.Type_0_is_not_assignable_to_type_1; } } - else if (message === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1 + else if ( + message === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1 && exactOptionalPropertyTypes - && getExactOptionalUnassignableProperties(source, target).length) { + && getExactOptionalUnassignableProperties(source, target).length + ) { message = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties; } @@ -20681,10 +20944,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source); const targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target); - if ((globalStringType === source && stringType === target) || + if ( + (globalStringType === source && stringType === target) || (globalNumberType === source && numberType === target) || (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType() === source && esSymbolType === target)) { + (getGlobalESSymbolType() === source && esSymbolType === target) + ) { reportError(Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } @@ -20740,8 +21005,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Before normalization: if `source` is type an object type, and `target` is primitive, // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result if (originalSource.flags & TypeFlags.Object && originalTarget.flags & TypeFlags.Primitive) { - if (relation === comparableRelation && !(originalTarget.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || - isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { + if ( + relation === comparableRelation && !(originalTarget.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || + isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined) + ) { return Ternary.True; } if (reportErrors) { @@ -20788,8 +21055,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - if (relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || - isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return Ternary.True; + if ( + relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || + isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined) + ) return Ternary.True; if (source.flags & TypeFlags.StructuredOrInstantiable || target.flags & TypeFlags.StructuredOrInstantiable) { const isPerformingExcessPropertyChecks = !(intersectionState & IntersectionState.Target) && (isObjectLiteralType(source) && getObjectFlags(source) & ObjectFlags.FreshLiteral); @@ -20814,8 +21083,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target); const calls = getSignaturesOfType(source, SignatureKind.Call); const constructs = getSignaturesOfType(source, SignatureKind.Construct); - if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, RecursionFlags.Source, /*reportErrors*/ false) || - constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, RecursionFlags.Source, /*reportErrors*/ false)) { + if ( + calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, RecursionFlags.Source, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, RecursionFlags.Source, /*reportErrors*/ false) + ) { reportError(Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString); } else { @@ -20869,8 +21140,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const targetTypes = (target as IntersectionType).types; const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); const intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) && - (contains(targetTypes, intrinsicAttributes) || contains(targetTypes, intrinsicClassAttributes))) { + if ( + !isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) && + (contains(targetTypes, intrinsicAttributes) || contains(targetTypes, intrinsicClassAttributes)) + ) { // do not report top error return; } @@ -20917,7 +21190,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { targetId: target.id, targetSize, pos: errorNode?.pos, - end: errorNode?.end + end: errorNode?.end, }); } } @@ -20938,8 +21211,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); - if ((relation === assignableRelation || relation === comparableRelation) && - (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + if ( + (relation === assignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target))) + ) { return false; } let reducedTarget = target; @@ -20993,12 +21268,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } if (suggestion !== undefined) { - reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, - symbolToString(prop), typeToString(errorTarget), suggestion); + reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); } else { - reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, - symbolToString(prop), typeToString(errorTarget)); + reportParentSkippedError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); } } } @@ -21078,9 +21351,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (containsType(targetTypes, source)) { return Ternary.True; } - if (relation !== comparableRelation && getObjectFlags(target) & ObjectFlags.PrimitiveUnion && !(source.flags & TypeFlags.EnumLiteral) && ( - source.flags & (TypeFlags.StringLiteral | TypeFlags.BooleanLiteral | TypeFlags.BigIntLiteral) || - (relation === subtypeRelation || relation === strictSubtypeRelation) && source.flags & TypeFlags.NumberLiteral)) { + if ( + relation !== comparableRelation && getObjectFlags(target) & ObjectFlags.PrimitiveUnion && !(source.flags & TypeFlags.EnumLiteral) && ( + source.flags & (TypeFlags.StringLiteral | TypeFlags.BooleanLiteral | TypeFlags.BigIntLiteral) || + (relation === subtypeRelation || relation === strictSubtypeRelation) && source.flags & TypeFlags.NumberLiteral + ) + ) { // When relating a literal type to a union of primitive types, we know the relation is false unless // the union contains the base primitive type or the literal type in one of its fresh/regular forms. // We exclude numeric literals for non-subtype relations because numeric literals are assignable to @@ -21147,8 +21423,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function getUndefinedStrippedTargetIfNeeded(source: Type, target: Type) { - if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && - !((source as UnionType).types[0].flags & TypeFlags.Undefined) && (target as UnionType).types[0].flags & TypeFlags.Undefined) { + if ( + source.flags & TypeFlags.Union && target.flags & TypeFlags.Union && + !((source as UnionType).types[0].flags & TypeFlags.Undefined) && (target as UnionType).types[0].flags & TypeFlags.Undefined + ) { return extractTypesOfKind(target, ~TypeFlags.Undefined); } return target; @@ -21328,7 +21606,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { targetId: target.id, targetIdStack: targetStack.map(t => t.id), depth: sourceDepth, - targetDepth + targetDepth, }); result = Ternary.Maybe; } @@ -21400,7 +21678,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` if (!result && (source.flags & TypeFlags.Intersection || source.flags & TypeFlags.TypeParameter && target.flags & TypeFlags.Union)) { - const constraint = getEffectiveConstraintOfIntersection(source.flags & TypeFlags.Intersection ? (source as IntersectionType).types: [source], !!(target.flags & TypeFlags.Union)); + const constraint = getEffectiveConstraintOfIntersection(source.flags & TypeFlags.Intersection ? (source as IntersectionType).types : [source], !!(target.flags & TypeFlags.Union)); if (constraint && everyType(constraint, c => c !== source)) { // Skip comparison if expansion contains the source itself // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this result = isRelatedTo(constraint, target, RecursionFlags.Source, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); @@ -21415,8 +21693,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // declare let wrong: { a: { y: string } }; // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type // - if (result && !(intersectionState & IntersectionState.Target) && target.flags & TypeFlags.Intersection && - !isGenericObjectType(target) && source.flags & (TypeFlags.Object | TypeFlags.Intersection)) { + if ( + result && !(intersectionState & IntersectionState.Target) && target.flags & TypeFlags.Intersection && + !isGenericObjectType(target) && source.flags & (TypeFlags.Object | TypeFlags.Intersection) + ) { result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, /*optionalsOnly*/ false, IntersectionState.None); if (result && isObjectLiteralType(source) && getObjectFlags(source) & ObjectFlags.FreshLiteral) { result &= indexSignaturesRelatedTo(source, target, /*sourceIsPrimitive*/ false, reportErrors, IntersectionState.None); @@ -21429,9 +21709,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // x = y; // Mismatched property in source intersection // } // - else if (result && isNonGenericObjectType(target) && !isArrayOrTupleType(target) && + else if ( + result && isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & TypeFlags.Intersection && getApparentType(source).flags & TypeFlags.StructuredType && - !some((source as IntersectionType).types, t => t === target || !!(getObjectFlags(t) & ObjectFlags.NonInferrableType))) { + !some((source as IntersectionType).types, t => t === target || !!(getObjectFlags(t) & ObjectFlags.NonInferrableType)) + ) { result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, /*optionalsOnly*/ true, intersectionState); } } @@ -21500,9 +21782,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Source is an intersection, target is an object (e.g. { a } & { b } <=> { a, b }). // Source is an intersection, target is a union (e.g. { a } & { b: boolean } <=> { a, b: true } | { a, b: false }). // Source is an intersection, target instantiable (e.g. string & { tag } <=> T["a"] constrained to string & { tag }). - if (!(sourceFlags & TypeFlags.Instantiable || - sourceFlags & TypeFlags.Object && targetFlags & TypeFlags.Union || - sourceFlags & TypeFlags.Intersection && targetFlags & (TypeFlags.Object | TypeFlags.Union | TypeFlags.Instantiable))) { + if ( + !(sourceFlags & TypeFlags.Instantiable || + sourceFlags & TypeFlags.Object && targetFlags & TypeFlags.Union || + sourceFlags & TypeFlags.Intersection && targetFlags & (TypeFlags.Object | TypeFlags.Union | TypeFlags.Instantiable)) + ) { return Ternary.False; } } @@ -21510,8 +21794,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // We limit alias variance probing to only object and conditional types since their alias behavior // is more predictable than other, interned types, which may or may not have an alias depending on // the order in which things were checked. - if (sourceFlags & (TypeFlags.Object | TypeFlags.Conditional) && source.aliasSymbol && source.aliasTypeArguments && - source.aliasSymbol === target.aliasSymbol && !(isMarkerType(source) || isMarkerType(target))) { + if ( + sourceFlags & (TypeFlags.Object | TypeFlags.Conditional) && source.aliasSymbol && source.aliasTypeArguments && + source.aliasSymbol === target.aliasSymbol && !(isMarkerType(source) || isMarkerType(target)) + ) { const variances = getAliasVariances(source.aliasSymbol); if (variances === emptyArray) { return Ternary.Unknown; @@ -21528,15 +21814,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // For a generic type T and a type U that is assignable to T, [...U] is assignable to T, U is assignable to readonly [...T], // and U is assignable to [...T] when U is constrained to a mutable array or tuple type. - if (isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target, RecursionFlags.Source)) || - isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0], RecursionFlags.Target))) { + if ( + isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target, RecursionFlags.Source)) || + isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0], RecursionFlags.Target)) + ) { return result; } if (targetFlags & TypeFlags.TypeParameter) { // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. if (getObjectFlags(source) & ObjectFlags.Mapped && !(source as MappedType).declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source as MappedType), RecursionFlags.Both)) { - if (!(getMappedTypeModifiers(source as MappedType) & MappedTypeModifiers.IncludeOptional)) { const templateType = getTemplateTypeFromMappedType(source as MappedType); const indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source as MappedType)); @@ -21605,7 +21892,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { modifiersType, TypeFlags.StringOrNumberLiteralOrUnique, /*stringsOnly*/ false, - t => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(targetType.mapper, getTypeParameterFromMappedType(targetType), t))) + t => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(targetType.mapper, getTypeParameterFromMappedType(targetType), t))), ); // We still need to include the non-apparent (and thus still generic) keys in the target side of the comparison (in case they're in the source side) targetKeys = getUnionType([...mappedKeys, nameType]); @@ -21670,8 +21957,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!(modifiers & MappedTypeModifiers.ExcludeOptional)) { // If the mapped type has shape `{ [P in Q]: T[P] }`, // source `S` is related to target if `T` = `S`, i.e. `S` is related to `{ [P in Q]: S[P] }`. - if (!keysRemapped && templateType.flags & TypeFlags.IndexedAccess && (templateType as IndexedAccessType).objectType === source && - (templateType as IndexedAccessType).indexType === getTypeParameterFromMappedType(target)) { + if ( + !keysRemapped && templateType.flags & TypeFlags.IndexedAccess && (templateType as IndexedAccessType).objectType === source && + (templateType as IndexedAccessType).indexType === getTypeParameterFromMappedType(target) + ) { return Ternary.True; } if (!isGenericMappedType(source)) { @@ -21686,9 +21975,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // A source type `S` is related to a target type `{ [P in Q as R]: T }` if `R` is related to `keyof S` and `S[R]` is related to `T. // A source type `S` is related to a target type `{ [P in Q]?: T }` if some constituent `Q'` of `Q` is related to `keyof S` and `S[Q']` is related to `T`. // A source type `S` is related to a target type `{ [P in Q as R]?: T }` if some constituent `R'` of `R` is related to `keyof S` and `S[R']` is related to `T`. - if (includeOptional - ? !(filteredByApplicability!.flags & TypeFlags.Never) - : isRelatedTo(targetKeys, sourceKeys, RecursionFlags.Both)) { + if ( + includeOptional + ? !(filteredByApplicability!.flags & TypeFlags.Never) + : isRelatedTo(targetKeys, sourceKeys, RecursionFlags.Both) + ) { const templateType = getTemplateTypeFromMappedType(target); const typeParameter = getTypeParameterFromMappedType(target); @@ -21713,8 +22004,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const indexingType = keysRemapped ? (filteredByApplicability || targetKeys) : filteredByApplicability - ? getIntersectionType([filteredByApplicability, typeParameter]) - : typeParameter; + ? getIntersectionType([filteredByApplicability, typeParameter]) + : typeParameter; const indexedAccessType = getIndexedAccessType(source, indexingType); // Compare `S[indexingType]` to `T`, where `T` is the type of a property of the target type. if (result = isRelatedTo(indexedAccessType, templateType, RecursionFlags.Both, reportErrors)) { @@ -21845,8 +22136,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { sourceExtends = instantiateType(sourceExtends, ctx.mapper); mapper = ctx.mapper; } - if (isTypeIdenticalTo(sourceExtends, (target as ConditionalType).extendsType) && - (isRelatedTo((source as ConditionalType).checkType, (target as ConditionalType).checkType, RecursionFlags.Both) || isRelatedTo((target as ConditionalType).checkType, (source as ConditionalType).checkType, RecursionFlags.Both))) { + if ( + isTypeIdenticalTo(sourceExtends, (target as ConditionalType).extendsType) && + (isRelatedTo((source as ConditionalType).checkType, (target as ConditionalType).checkType, RecursionFlags.Both) || isRelatedTo((target as ConditionalType).checkType, (source as ConditionalType).checkType, RecursionFlags.Both)) + ) { if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source as ConditionalType), mapper), getTrueTypeFromConditionalType(target as ConditionalType), RecursionFlags.Both, reportErrors)) { result &= isRelatedTo(getFalseTypeFromConditionalType(source as ConditionalType), getFalseTypeFromConditionalType(target as ConditionalType), RecursionFlags.Both, reportErrors); } @@ -21896,8 +22189,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (isGenericMappedType(source)) { return Ternary.False; } - if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source as TypeReference).target === (target as TypeReference).target && - !isTupleType(source) && !(isMarkerType(source) || isMarkerType(target))) { + if ( + getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source as TypeReference).target === (target as TypeReference).target && + !isTupleType(source) && !(isMarkerType(source) || isMarkerType(target)) + ) { // When strictNullChecks is disabled, the element type of the empty array literal is undefinedWideningType, // and an empty array literal wouldn't be assignable to a `never[]` without this check. if (isEmptyArrayLiteralType(source)) { @@ -22096,7 +22391,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const matchingTypes: Type[] = []; for (const combination of discriminantCombinations) { let hasMatch = false; - outer: for (const type of target.types) { + outer: + for (const type of target.types) { for (let i = 0; i < sourcePropertiesFiltered.length; i++) { const sourceProperty = sourcePropertiesFiltered[i]; const targetProperty = getPropertyOfType(type, sourceProperty.escapedName); @@ -22176,9 +22472,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { reportError(Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), - typeToString(sourcePropFlags & ModifierFlags.Private ? source : target), - typeToString(sourcePropFlags & ModifierFlags.Private ? target : source)); + reportError(Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & ModifierFlags.Private ? source : target), typeToString(sourcePropFlags & ModifierFlags.Private ? target : source)); } } return Ternary.False; @@ -22187,16 +22481,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (targetPropFlags & ModifierFlags.Protected) { if (!isValidOverrideOf(sourceProp, targetProp)) { if (reportErrors) { - reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), - typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); } return Ternary.False; } } else if (sourcePropFlags & ModifierFlags.Protected) { if (reportErrors) { - reportError(Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, - symbolToString(targetProp), typeToString(source), typeToString(target)); + reportError(Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } return Ternary.False; } @@ -22231,8 +22523,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // (M - property in T) // (N - property in S) if (reportErrors) { - reportError(Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, - symbolToString(targetProp), typeToString(source), typeToString(target)); + reportError(Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } return Ternary.False; } @@ -22242,11 +22533,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function reportUnmatchedProperty(source: Type, target: Type, unmatchedProperty: Symbol, requireOptionalProperties: boolean) { let shouldSkipElaboration = false; // give specific error in case where private names have the same description - if (unmatchedProperty.valueDeclaration + if ( + unmatchedProperty.valueDeclaration && isNamedDeclaration(unmatchedProperty.valueDeclaration) && isPrivateIdentifier(unmatchedProperty.valueDeclaration.name) && source.symbol - && source.symbol.flags & SymbolFlags.Class) { + && source.symbol.flags & SymbolFlags.Class + ) { const privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText; const symbolTableKey = getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription); if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) { @@ -22256,13 +22549,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { Diagnostics.Property_0_in_type_1_refers_to_a_different_member_that_cannot_be_accessed_from_within_type_2, diagnosticName(privateIdentifierDescription), diagnosticName(sourceName.escapedText === "" ? anon : sourceName), - diagnosticName(targetName.escapedText === "" ? anon : targetName)); + diagnosticName(targetName.escapedText === "" ? anon : targetName), + ); return; } } const props = arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false)); - if (!headMessage || (headMessage.code !== Diagnostics.Class_0_incorrectly_implements_interface_1.code && - headMessage.code !== Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { + if ( + !headMessage || (headMessage.code !== Diagnostics.Class_0_incorrectly_implements_interface_1.code && + headMessage.code !== Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code) + ) { shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it } if (props.length === 1) { @@ -22473,10 +22769,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); const targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); - const sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === SignatureKind.Construct) ? - SignatureKind.Call : kind); - const targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === SignatureKind.Construct) ? - SignatureKind.Call : kind); + const sourceSignatures = getSignaturesOfType( + source, + (sourceIsJSConstructor && kind === SignatureKind.Construct) ? + SignatureKind.Call : kind, + ); + const targetSignatures = getSignaturesOfType( + target, + (targetIsJSConstructor && kind === SignatureKind.Construct) ? + SignatureKind.Call : kind, + ); if (kind === SignatureKind.Construct && sourceSignatures.length && targetSignatures.length) { const sourceIsAbstract = !!(sourceSignatures[0].flags & SignatureFlags.Abstract); @@ -22500,8 +22802,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const incompatibleReporter = kind === SignatureKind.Construct ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn; const sourceObjectFlags = getObjectFlags(source); const targetObjectFlags = getObjectFlags(target); - if (sourceObjectFlags & ObjectFlags.Instantiated && targetObjectFlags & ObjectFlags.Instantiated && source.symbol === target.symbol || - sourceObjectFlags & ObjectFlags.Reference && targetObjectFlags & ObjectFlags.Reference && (source as TypeReference).target === (target as TypeReference).target) { + if ( + sourceObjectFlags & ObjectFlags.Instantiated && targetObjectFlags & ObjectFlags.Instantiated && source.symbol === target.symbol || + sourceObjectFlags & ObjectFlags.Reference && targetObjectFlags & ObjectFlags.Reference && (source as TypeReference).target === (target as TypeReference).target + ) { // We have instantiations of the same anonymous type (which typically will be the type of a // method). Simply do a pairwise comparison of the signatures in the two signature lists instead // of the much more expensive N * M comparison matrix we explore below. We erase type parameters @@ -22524,17 +22828,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const sourceSignature = first(sourceSignatures); const targetSignature = first(targetSignatures); result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, intersectionState, incompatibleReporter(sourceSignature, targetSignature)); - if (!result && reportErrors && kind === SignatureKind.Construct && (sourceObjectFlags & targetObjectFlags) && - (targetSignature.declaration?.kind === SyntaxKind.Constructor || sourceSignature.declaration?.kind === SyntaxKind.Constructor)) { - const constructSignatureToString = (signature: Signature) => - signatureToString(signature, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrowStyleSignature, kind); + if ( + !result && reportErrors && kind === SignatureKind.Construct && (sourceObjectFlags & targetObjectFlags) && + (targetSignature.declaration?.kind === SyntaxKind.Constructor || sourceSignature.declaration?.kind === SyntaxKind.Constructor) + ) { + const constructSignatureToString = (signature: Signature) => signatureToString(signature, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrowStyleSignature, kind); reportError(Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature)); reportError(Diagnostics.Types_of_construct_signatures_are_incompatible); return result; } } else { - outer: for (const t of targetSignatures) { + outer: + for (const t of targetSignatures) { const saveErrorInfo = captureErrorCalculationState(); // Only elaborate errors from the first failure let shouldElaborateErrors = reportErrors; @@ -22548,9 +22854,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { shouldElaborateErrors = false; } if (shouldElaborateErrors) { - reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, - typeToString(source), - signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); } return Ternary.False; } @@ -22563,8 +22867,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const typeConstructSignatures = getSignaturesOfStructuredType(source, SignatureKind.Construct); const typeProperties = getPropertiesOfObjectType(source); if ((typeCallSignatures.length || typeConstructSignatures.length) && !typeProperties.length) { - if ((getSignaturesOfType(target, SignatureKind.Call).length && typeCallSignatures.length) || - (getSignaturesOfType(target, SignatureKind.Construct).length && typeConstructSignatures.length)) { + if ( + (getSignaturesOfType(target, SignatureKind.Call).length && typeCallSignatures.length) || + (getSignaturesOfType(target, SignatureKind.Construct).length && typeConstructSignatures.length) + ) { return true; // target has similar signature kinds to source, still focus on the unmatched property } return false; @@ -22593,8 +22899,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const checkMode = relation === subtypeRelation ? SignatureCheckMode.StrictTopSignature : relation === strictSubtypeRelation ? SignatureCheckMode.StrictTopSignature | SignatureCheckMode.StrictArity : SignatureCheckMode.None; - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, - checkMode, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, checkMode, reportErrors, reportError, incompatibleReporter, isRelatedToWorker, reportUnreliableMapper); function isRelatedToWorker(source: Type, target: Type, reportErrors?: boolean) { return isRelatedTo(source, target, RecursionFlags.Both, reportErrors, /*headMessage*/ undefined, intersectionState); } @@ -22883,7 +23188,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let unmeasurable = false; let unreliable = false; const oldHandler = outofbandVarianceMarkerHandler; - outofbandVarianceMarkerHandler = (onlyUnreliable) => onlyUnreliable ? unreliable = true : unmeasurable = true; + outofbandVarianceMarkerHandler = onlyUnreliable => onlyUnreliable ? unreliable = true : unmeasurable = true; // We first compare instantiations where the type parameter is replaced with // marker types that have a known subtype relationship. From this we can infer // invariance, covariance, contravariance or bivariance. @@ -23055,15 +23360,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Return true if source property is a valid override of protected parts of target property. function isValidOverrideOf(sourceProp: Symbol, targetProp: Symbol) { - return !forEachProperty(targetProp, tp => getDeclarationModifierFlagsFromSymbol(tp) & ModifierFlags.Protected ? - !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false); + return !forEachProperty(targetProp, tp => + getDeclarationModifierFlagsFromSymbol(tp) & ModifierFlags.Protected ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false); } // Return true if the given class derives from each of the declaring classes of the protected // constituents of the given property. function isClassDerivedFromDeclaringClasses(checkClass: T, prop: Symbol, writing: boolean) { - return forEachProperty(prop, p => getDeclarationModifierFlagsFromSymbol(p, writing) & ModifierFlags.Protected ? - !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? undefined : checkClass; + return forEachProperty(prop, p => + getDeclarationModifierFlagsFromSymbol(p, writing) & ModifierFlags.Protected ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons @@ -23137,7 +23444,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A do { type = (type as IndexedAccessType).objectType; - } while (type.flags & TypeFlags.IndexedAccess); + } + while (type.flags & TypeFlags.IndexedAccess); return type; } if (type.flags & TypeFlags.Conditional) { @@ -23188,9 +23496,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const targetHasRestParameter = hasEffectiveRestParameter(target); // A source signature matches a target signature if the two signatures have the same number of required, // optional, and rest parameters. - if (sourceParameterCount === targetParameterCount && + if ( + sourceParameterCount === targetParameterCount && sourceMinArgumentCount === targetMinArgumentCount && - sourceHasRestParameter === targetHasRestParameter) { + sourceHasRestParameter === targetHasRestParameter + ) { return true; } // A source signature partially matches a target signature if the target signature has no fewer required @@ -23223,8 +23533,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (let i = 0; i < target.typeParameters.length; i++) { const s = source.typeParameters![i]; const t = target.typeParameters[i]; - if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) && - compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) { + if ( + !(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) && + compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType)) + ) { return Ternary.False; } } @@ -23550,7 +23862,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { every(t1.target.elementFlags, (f, i) => (f & ElementFlags.Variable) === (t2.target.elementFlags[i] & ElementFlags.Variable)); } - function isZeroBigInt({value}: BigIntLiteralType) { + function isZeroBigInt({ value }: BigIntLiteralType) { return value.base10Value === "0"; } @@ -23567,11 +23879,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type.flags & TypeFlags.Number ? zeroType : type.flags & TypeFlags.BigInt ? zeroBigIntType : type === regularFalseType || - type === falseType || - type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null | TypeFlags.AnyOrUnknown) || - type.flags & TypeFlags.StringLiteral && (type as StringLiteralType).value === "" || - type.flags & TypeFlags.NumberLiteral && (type as NumberLiteralType).value === 0 || - type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type as BigIntLiteralType) ? type : + type === falseType || + type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null | TypeFlags.AnyOrUnknown) || + type.flags & TypeFlags.StringLiteral && (type as StringLiteralType).value === "" || + type.flags & TypeFlags.NumberLiteral && (type as NumberLiteralType).value === 0 || + type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type as BigIntLiteralType) ? type : neverType; } @@ -23801,9 +24113,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } } - const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, - sameMap(getIndexInfosOfType(type), info => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly))); - result.objectFlags |= (getObjectFlags(type) & (ObjectFlags.JSLiteral | ObjectFlags.NonInferrableType)); // Retain js literal flag through widening + const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, sameMap(getIndexInfosOfType(type), info => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly))); + result.objectFlags |= getObjectFlags(type) & (ObjectFlags.JSLiteral | ObjectFlags.NonInferrableType); // Retain js literal flag through widening return result; } @@ -23910,10 +24221,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const param = declaration as ParameterDeclaration; if (isIdentifier(param.name)) { const originalKeywordKind = identifierToKeywordKind(param.name); - if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && + if ( + (isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.indexOf(param) > -1 && (resolveName(param, param.name.escapedText, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, param.name.escapedText, /*isUse*/ true) || - originalKeywordKind && isTypeNodeKind(originalKeywordKind))) { + originalKeywordKind && isTypeNodeKind(originalKeywordKind)) + ) { const newName = "arg" + param.parent.parameters.indexOf(param); const typeName = declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : ""); errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName); @@ -24037,22 +24350,28 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function makeFixingMapperForContext(context: InferenceContext) { - return makeDeferredTypeMapper(map(context.inferences, i => i.typeParameter), map(context.inferences, (inference, i) => () => { - if (!inference.isFixed) { - // Before we commit to a particular inference (and thus lock out any further inferences), - // we infer from any intra-expression inference sites we have collected. - inferFromIntraExpressionSites(context); - clearCachedInferences(context.inferences); - inference.isFixed = true; - } - return getInferredType(context, i); - })); + return makeDeferredTypeMapper( + map(context.inferences, i => i.typeParameter), + map(context.inferences, (inference, i) => () => { + if (!inference.isFixed) { + // Before we commit to a particular inference (and thus lock out any further inferences), + // we infer from any intra-expression inference sites we have collected. + inferFromIntraExpressionSites(context); + clearCachedInferences(context.inferences); + inference.isFixed = true; + } + return getInferredType(context, i); + }), + ); } function makeNonFixingMapperForContext(context: InferenceContext) { - return makeDeferredTypeMapper(map(context.inferences, i => i.typeParameter), map(context.inferences, (_, i) => () => { - return getInferredType(context, i); - })); + return makeDeferredTypeMapper( + map(context.inferences, i => i.typeParameter), + map(context.inferences, (_, i) => () => { + return getInferredType(context, i); + }), + ); } function clearCachedInferences(inferences: InferenceInfo[]) { @@ -24103,7 +24422,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { priority: undefined, topLevel: true, isFixed: false, - impliedArity: undefined + impliedArity: undefined, }; } @@ -24116,7 +24435,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { priority: inference.priority, topLevel: inference.topLevel, isFixed: inference.isFixed, - impliedArity: inference.impliedArity + impliedArity: inference.impliedArity, }; } @@ -24141,9 +24460,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const result = !!(type.flags & TypeFlags.Instantiable || type.flags & TypeFlags.Object && !isNonGenericTopLevelType(type) && ( - objectFlags & ObjectFlags.Reference && ((type as TypeReference).node || some(getTypeArguments(type as TypeReference), couldContainTypeVariables)) || - objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations || - objectFlags & (ObjectFlags.Mapped | ObjectFlags.ReverseMapped | ObjectFlags.ObjectRestType | ObjectFlags.InstantiationExpressionType)) || + objectFlags & ObjectFlags.Reference && ((type as TypeReference).node || some(getTypeArguments(type as TypeReference), couldContainTypeVariables)) || + objectFlags & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral) && type.symbol.declarations || + objectFlags & (ObjectFlags.Mapped | ObjectFlags.ReverseMapped | ObjectFlags.ObjectRestType | ObjectFlags.InstantiationExpressionType) + ) || type.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral) && !(type.flags & TypeFlags.EnumLiteral) && !isNonGenericTopLevelType(type) && some((type as UnionOrIntersectionType | TemplateLiteralType).types, couldContainTypeVariables)); if (type.flags & TypeFlags.ObjectFlagsType) { (type as ObjectFlagsType).objectFlags |= ObjectFlags.CouldContainTypeVariablesComputed | (result ? ObjectFlags.CouldContainTypeVariables : 0); @@ -24163,8 +24483,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return !!(type === tp || type.flags & TypeFlags.UnionOrIntersection && some((type as UnionOrIntersectionType).types, t => isTypeParameterAtTopLevel(t, tp, depth)) || depth < 3 && type.flags & TypeFlags.Conditional && ( - isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type as ConditionalType), tp, depth + 1) || - isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type as ConditionalType), tp, depth + 1))); + isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type as ConditionalType), tp, depth + 1) || + isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type as ConditionalType), tp, depth + 1) + )); } function isTypeParameterAtTopLevelInReturnType(signature: Signature, typeParameter: TypeParameter) { @@ -24405,7 +24726,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function inferTypesFromTemplateLiteralType(source: Type, target: TemplateLiteralType): Type[] | undefined { return source.flags & TypeFlags.StringLiteral ? inferFromLiteralPartsToTemplateLiteral([(source as StringLiteralType).value], emptyArray, target) : source.flags & TypeFlags.TemplateLiteral ? - arraysEqual((source as TemplateLiteralType).texts, target.texts) ? map((source as TemplateLiteralType).types, getStringLikeTypeForType) : + arraysEqual((source as TemplateLiteralType).texts, target.texts) ? map((source as TemplateLiteralType).types, getStringLikeTypeForType) : inferFromLiteralPartsToTemplateLiteral((source as TemplateLiteralType).texts, (source as TemplateLiteralType).types, target) : undefined; } @@ -24446,8 +24767,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const lastTargetIndex = targetTexts.length - 1; const targetStartText = targetTexts[0]; const targetEndText = targetTexts[lastTargetIndex]; - if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || - !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return undefined; + if ( + lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || + !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText) + ) return undefined; const remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); const matches: Type[] = []; let seg = 0; @@ -24487,7 +24810,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { getStringLiteralType(getSourceText(s).slice(pos, p)) : getTemplateLiteralType( [sourceTexts[seg].slice(pos), ...sourceTexts.slice(seg + 1, s), getSourceText(s).slice(0, p)], - sourceTypes.slice(seg, s)); + sourceTypes.slice(seg, s), + ); matches.push(matchType); seg = s; pos = p; @@ -24654,9 +24978,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } } - if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && ( - (source as TypeReference).target === (target as TypeReference).target || isArrayType(source) && isArrayType(target)) && - !((source as TypeReference).node && (target as TypeReference).node)) { + if ( + getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && ( + (source as TypeReference).target === (target as TypeReference).target || isArrayType(source) && isArrayType(target) + ) && + !((source as TypeReference).node && (target as TypeReference).node) + ) { // If source and target are references to the same generic type, infer from type arguments inferFromTypeArguments(getTypeArguments(source as TypeReference), getTypeArguments(target as TypeReference), getVariances((source as TypeReference).target)); } @@ -24681,7 +25008,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { inferWithPriority(getSubstitutionIntersection(source as SubstitutionType), target, InferencePriority.SubstituteSource); // Make substitute inference at a lower priority } else if (target.flags & TypeFlags.Conditional) { - invokeOnce(source, (target as ConditionalType), inferToConditionalType); + invokeOnce(source, target as ConditionalType, inferToConditionalType); } else if (target.flags & TypeFlags.UnionOrIntersection) { inferToMultipleTypes(source, (target as UnionOrIntersectionType).types, target.flags); @@ -24928,10 +25255,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - inferWithPriority(inferredType, inference.typeParameter, + inferWithPriority( + inferredType, + inference.typeParameter, getObjectFlags(source) & ObjectFlags.NonInferrableType ? InferencePriority.PartialHomomorphicMappedType : - InferencePriority.HomomorphicMappedType); + InferencePriority.HomomorphicMappedType, + ); } } return true; @@ -25011,21 +25341,20 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // for each type in the constraint, find the highest priority matching type const matchingType = reduceLeft(constraintTypes, (left, right) => !(right.flags & allTypeFlags) ? left : - left.flags & TypeFlags.String ? left : right.flags & TypeFlags.String ? source : - left.flags & TypeFlags.TemplateLiteral ? left : right.flags & TypeFlags.TemplateLiteral && isTypeMatchedByTemplateLiteralType(source, right as TemplateLiteralType) ? source : - left.flags & TypeFlags.StringMapping ? left : right.flags & TypeFlags.StringMapping && str === applyStringMapping(right.symbol, str) ? source : - left.flags & TypeFlags.StringLiteral ? left : right.flags & TypeFlags.StringLiteral && (right as StringLiteralType).value === str ? right : - left.flags & TypeFlags.Number ? left : right.flags & TypeFlags.Number ? getNumberLiteralType(+str) : - left.flags & TypeFlags.Enum ? left : right.flags & TypeFlags.Enum ? getNumberLiteralType(+str) : - left.flags & TypeFlags.NumberLiteral ? left : right.flags & TypeFlags.NumberLiteral && (right as NumberLiteralType).value === +str ? right : - left.flags & TypeFlags.BigInt ? left : right.flags & TypeFlags.BigInt ? parseBigIntLiteralType(str) : - left.flags & TypeFlags.BigIntLiteral ? left : right.flags & TypeFlags.BigIntLiteral && pseudoBigIntToString((right as BigIntLiteralType).value) === str ? right : - left.flags & TypeFlags.Boolean ? left : right.flags & TypeFlags.Boolean ? str === "true" ? trueType : str === "false" ? falseType : booleanType : - left.flags & TypeFlags.BooleanLiteral ? left : right.flags & TypeFlags.BooleanLiteral && (right as IntrinsicType).intrinsicName === str ? right : - left.flags & TypeFlags.Undefined ? left : right.flags & TypeFlags.Undefined && (right as IntrinsicType).intrinsicName === str ? right : - left.flags & TypeFlags.Null ? left : right.flags & TypeFlags.Null && (right as IntrinsicType).intrinsicName === str ? right : - left, - neverType as Type); + left.flags & TypeFlags.String ? left : right.flags & TypeFlags.String ? source : + left.flags & TypeFlags.TemplateLiteral ? left : right.flags & TypeFlags.TemplateLiteral && isTypeMatchedByTemplateLiteralType(source, right as TemplateLiteralType) ? source : + left.flags & TypeFlags.StringMapping ? left : right.flags & TypeFlags.StringMapping && str === applyStringMapping(right.symbol, str) ? source : + left.flags & TypeFlags.StringLiteral ? left : right.flags & TypeFlags.StringLiteral && (right as StringLiteralType).value === str ? right : + left.flags & TypeFlags.Number ? left : right.flags & TypeFlags.Number ? getNumberLiteralType(+str) : + left.flags & TypeFlags.Enum ? left : right.flags & TypeFlags.Enum ? getNumberLiteralType(+str) : + left.flags & TypeFlags.NumberLiteral ? left : right.flags & TypeFlags.NumberLiteral && (right as NumberLiteralType).value === +str ? right : + left.flags & TypeFlags.BigInt ? left : right.flags & TypeFlags.BigInt ? parseBigIntLiteralType(str) : + left.flags & TypeFlags.BigIntLiteral ? left : right.flags & TypeFlags.BigIntLiteral && pseudoBigIntToString((right as BigIntLiteralType).value) === str ? right : + left.flags & TypeFlags.Boolean ? left : right.flags & TypeFlags.Boolean ? str === "true" ? trueType : str === "false" ? falseType : booleanType : + left.flags & TypeFlags.BooleanLiteral ? left : right.flags & TypeFlags.BooleanLiteral && (right as IntrinsicType).intrinsicName === str ? right : + left.flags & TypeFlags.Undefined ? left : right.flags & TypeFlags.Undefined && (right as IntrinsicType).intrinsicName === str ? right : + left.flags & TypeFlags.Null ? left : right.flags & TypeFlags.Null && (right as IntrinsicType).intrinsicName === str ? right : + left, neverType as Type); if (!(matchingType.flags & TypeFlags.Never)) { inferFromTypes(matchingType, target); @@ -25041,8 +25370,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function inferFromObjectTypes(source: Type, target: Type) { - if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && ( - (source as TypeReference).target === (target as TypeReference).target || isArrayType(source) && isArrayType(target))) { + if ( + getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && ( + (source as TypeReference).target === (target as TypeReference).target || isArrayType(source) && isArrayType(target) + ) + ) { // If source and target are references to the same generic type, infer from type arguments inferFromTypeArguments(getTypeArguments(source as TypeReference), getTypeArguments(target as TypeReference), getVariances((source as TypeReference).target)); return; @@ -25079,8 +25411,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; } const startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0; - const endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, ElementFlags.Fixed) : 0, - target.target.hasRestElement ? getEndElementCount(target.target, ElementFlags.Fixed) : 0); + const endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, ElementFlags.Fixed) : 0, target.target.hasRestElement ? getEndElementCount(target.target, ElementFlags.Fixed) : 0); // Infer between starting fixed elements. for (let i = 0; i < startLength; i++) { inferFromTypes(getTypeArguments(source)[i], elementTypes[i]); @@ -25124,8 +25455,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const impliedArity = constraint.target.fixedLength; const endIndex = sourceArity - getEndElementCount(target.target, ElementFlags.Fixed); const startIndex = endIndex - impliedArity; - const trailingSlice = createTupleType(getTypeArguments(source).slice(startIndex, endIndex), source.target.elementFlags.slice(startIndex, endIndex), - /*readonly*/ false, source.target.labeledElementDeclarations && source.target.labeledElementDeclarations.slice(startIndex, endIndex)); + const trailingSlice = createTupleType(getTypeArguments(source).slice(startIndex, endIndex), source.target.elementFlags.slice(startIndex, endIndex), /*readonly*/ false, source.target.labeledElementDeclarations && source.target.labeledElementDeclarations.slice(startIndex, endIndex)); inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength, endLength + impliedArity)!, elementTypes[startLength]); inferFromTypes(trailingSlice, elementTypes[startLength + 1]); @@ -25304,10 +25634,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // and has inferences that would conflict. Otherwise, we prefer the contra-variant inference. const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & TypeFlags.Never) && - some(inference.contraCandidates, t => isTypeSubtypeOf(inferredCovariantType, t)) && - every(context.inferences, other => - other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || - every(other.candidates, t => isTypeSubtypeOf(t, inferredCovariantType)))); + some(inference.contraCandidates, t => isTypeSubtypeOf(inferredCovariantType, t)) && + every(context.inferences, other => + other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || + every(other.candidates, t => isTypeSubtypeOf(t, inferredCovariantType)))); inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; } @@ -25423,14 +25753,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !nodeIsMissing(node) && - resolveName( - node, - node.escapedText, - SymbolFlags.Value | SymbolFlags.ExportValue, - getCannotFindNameDiagnosticForName(node), - node, - !isWriteOnlyAccess(node), - /*excludeGlobals*/ false) || unknownSymbol; + resolveName( + node, + node.escapedText, + SymbolFlags.Value | SymbolFlags.ExportValue, + getCannotFindNameDiagnosticForName(node), + node, + !isWriteOnlyAccess(node), + /*excludeGlobals*/ false, + ) || unknownSymbol; } return links.resolvedSymbol; } @@ -25498,7 +25829,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return isThisInTypeQuery(source) ? target.kind === SyntaxKind.ThisKeyword : target.kind === SyntaxKind.Identifier && getResolvedSymbol(source as Identifier) === getResolvedSymbol(target as Identifier) || - (isVariableDeclaration(target) || isBindingElement(target)) && + (isVariableDeclaration(target) || isBindingElement(target)) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source as Identifier)) === getSymbolOfDeclaration(target); case SyntaxKind.ThisKeyword: return target.kind === SyntaxKind.ThisKeyword; @@ -25602,8 +25933,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) { // NOTE: cast to TransientSymbol should be safe because only TransientSymbols can have CheckFlags.SyntheticProperty if ((prop as TransientSymbol).links.isDiscriminantProperty === undefined) { - (prop as TransientSymbol).links.isDiscriminantProperty = - ((prop as TransientSymbol).links.checkFlags & CheckFlags.Discriminant) === CheckFlags.Discriminant && + (prop as TransientSymbol).links.isDiscriminantProperty = ((prop as TransientSymbol).links.checkFlags & CheckFlags.Discriminant) === CheckFlags.Discriminant && !isGenericType(getTypeOfSymbol(prop)); } return !!(prop as TransientSymbol).links.isDiscriminantProperty; @@ -25664,8 +25994,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getKeyPropertyName(unionType: UnionType): __String | undefined { const types = unionType.types; // We only construct maps for unions with many non-primitive constituents. - if (types.length < 10 || getObjectFlags(unionType) & ObjectFlags.PrimitiveUnion || - countWhere(types, t => !!(t.flags & (TypeFlags.Object | TypeFlags.InstantiableNonPrimitive))) < 10) { + if ( + types.length < 10 || getObjectFlags(unionType) & ObjectFlags.PrimitiveUnion || + countWhere(types, t => !!(t.flags & (TypeFlags.Object | TypeFlags.InstantiableNonPrimitive))) < 10 + ) { return undefined; } if (unionType.keyPropertyName === undefined) { @@ -25697,7 +26029,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getMatchingUnionConstituentForObjectLiteral(unionType: UnionType, node: ObjectLiteralExpression) { const keyPropertyName = getKeyPropertyName(unionType); - const propNode = keyPropertyName && find(node.properties, p => p.symbol && p.kind === SyntaxKind.PropertyAssignment && + const propNode = keyPropertyName && find(node.properties, p => + p.symbol && p.kind === SyntaxKind.PropertyAssignment && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer)); const propType = propNode && getContextFreeTypeOfExpression((propNode as PropertyAssignment).initializer); return propType && getConstituentTypeForKeyType(unionType, propType); @@ -25715,8 +26048,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } } - if (expression.expression.kind === SyntaxKind.PropertyAccessExpression && - isOrContainsMatchingReference(reference, (expression.expression as PropertyAccessExpression).expression)) { + if ( + expression.expression.kind === SyntaxKind.PropertyAccessExpression && + isOrContainsMatchingReference(reference, (expression.expression as PropertyAccessExpression).expression) + ) { return true; } return false; @@ -25819,8 +26154,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type as ObjectType) ? strictNullChecks ? TypeFacts.EmptyObjectStrictFacts : TypeFacts.EmptyObjectFacts : isFunctionObjectType(type as ObjectType) ? - strictNullChecks ? TypeFacts.FunctionStrictFacts : TypeFacts.FunctionFacts : - strictNullChecks ? TypeFacts.ObjectStrictFacts : TypeFacts.ObjectFacts; + strictNullChecks ? TypeFacts.FunctionStrictFacts : TypeFacts.FunctionFacts : + strictNullChecks ? TypeFacts.ObjectStrictFacts : TypeFacts.ObjectFacts; } if (flags & TypeFlags.Void) { return TypeFacts.VoidFacts; @@ -25879,12 +26214,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (strictNullChecks) { switch (facts) { case TypeFacts.NEUndefined: - return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQUndefined ? getIntersectionType([t, getTypeFacts(t) & TypeFacts.EQNull && !maybeTypeOfKind(reduced, TypeFlags.Null) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]): t); + return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQUndefined ? getIntersectionType([t, getTypeFacts(t) & TypeFacts.EQNull && !maybeTypeOfKind(reduced, TypeFlags.Null) ? getUnionType([emptyObjectType, nullType]) : emptyObjectType]) : t); case TypeFacts.NENull: - return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQNull ? getIntersectionType([t, getTypeFacts(t) & TypeFacts.EQUndefined && !maybeTypeOfKind(reduced, TypeFlags.Undefined) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]): t); + return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQNull ? getIntersectionType([t, getTypeFacts(t) & TypeFacts.EQUndefined && !maybeTypeOfKind(reduced, TypeFlags.Undefined) ? getUnionType([emptyObjectType, undefinedType]) : emptyObjectType]) : t); case TypeFacts.NEUndefinedOrNull: case TypeFacts.Truthy: - return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQUndefinedOrNull ? getGlobalNonNullableTypeInstantiation(t): t); + return mapType(reduced, t => getTypeFacts(t) & TypeFacts.EQUndefinedOrNull ? getGlobalNonNullableTypeInstantiation(t) : t); } } return reduced; @@ -25925,8 +26260,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function getAssignedTypeOfBinaryExpression(node: BinaryExpression): Type { - const isDestructuringDefaultAssignment = - node.parent.kind === SyntaxKind.ArrayLiteralExpression && isDestructuringAssignmentTarget(node.parent) || + const isDestructuringDefaultAssignment = node.parent.kind === SyntaxKind.ArrayLiteralExpression && isDestructuringAssignmentTarget(node.parent) || node.parent.kind === SyntaxKind.PropertyAssignment && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : @@ -25983,8 +26317,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const type = pattern.kind === SyntaxKind.ObjectBindingPattern ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name as Identifier) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : - getTypeOfDestructuredSpreadExpression(parentType); + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : + getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer!); } @@ -26017,9 +26351,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isEmptyArrayAssignment(node: VariableDeclaration | BindingElement | Expression) { return node.kind === SyntaxKind.VariableDeclaration && (node as VariableDeclaration).initializer && - isEmptyArrayLiteral((node as VariableDeclaration).initializer!) || + isEmptyArrayLiteral((node as VariableDeclaration).initializer!) || node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression && - isEmptyArrayLiteral((node.parent as BinaryExpression).right); + isEmptyArrayLiteral((node.parent as BinaryExpression).right); } function getReferenceCandidate(node: Expression): Expression { @@ -26043,8 +26377,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getReferenceRoot(node: Node): Node { const { parent } = node; return parent.kind === SyntaxKind.ParenthesizedExpression || - parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken && (parent as BinaryExpression).left === node || - parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken && (parent as BinaryExpression).right === node ? + parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken && (parent as BinaryExpression).left === node || + parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken && (parent as BinaryExpression).right === node ? getReferenceRoot(parent) : node; } @@ -26205,13 +26539,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // true intersection because it is more costly and, when applied to union types, generates a large number of // types we don't actually care about. function replacePrimitivesWithLiterals(typeWithPrimitives: Type, typeWithLiterals: Type) { - if (maybeTypeOfKind(typeWithPrimitives, TypeFlags.String | TypeFlags.TemplateLiteral | TypeFlags.Number | TypeFlags.BigInt) && - maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping | TypeFlags.NumberLiteral | TypeFlags.BigIntLiteral)) { + if ( + maybeTypeOfKind(typeWithPrimitives, TypeFlags.String | TypeFlags.TemplateLiteral | TypeFlags.Number | TypeFlags.BigInt) && + maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping | TypeFlags.NumberLiteral | TypeFlags.BigIntLiteral) + ) { return mapType(typeWithPrimitives, t => t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) : - isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) ? extractTypesOfKind(typeWithLiterals, TypeFlags.StringLiteral) : - t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : - t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : t); + isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.TemplateLiteral | TypeFlags.StringMapping) ? extractTypesOfKind(typeWithLiterals, TypeFlags.StringLiteral) : + t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : + t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : t); } return typeWithPrimitives; } @@ -26253,9 +26589,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function createFinalArrayType(elementType: Type) { return elementType.flags & TypeFlags.Never ? autoArrayType : - createArrayType(elementType.flags & TypeFlags.Union ? - getUnionType((elementType as UnionType).types, UnionReduction.Subtype) : - elementType); + createArrayType( + elementType.flags & TypeFlags.Union ? + getUnionType((elementType as UnionType).types, UnionReduction.Subtype) : + elementType, + ); } // We perform subtype reduction upon obtaining the final array type from an evolving array type. @@ -26292,8 +26630,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isLengthPushOrUnshift = isPropertyAccessExpression(parent) && ( parent.name.escapedText === "length" || parent.parent.kind === SyntaxKind.CallExpression - && isIdentifier(parent.name) - && isPushOrUnshiftIdentifier(parent.name)); + && isIdentifier(parent.name) + && isPushOrUnshiftIdentifier(parent.name) + ); const isElementAssignment = parent.kind === SyntaxKind.ElementAccessExpression && (parent as ElementAccessExpression).expression === root && parent.parent.kind === SyntaxKind.BinaryExpression && @@ -26396,7 +26735,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isOptionalChain(node)) { funcType = checkNonNullType( getOptionalExpressionType(checkExpression(node.expression), node.expression), - node.expression + node.expression, ); } else { @@ -26442,8 +26781,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isFalseExpression(expr: Expression): boolean { const node = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true); return node.kind === SyntaxKind.FalseKeyword || node.kind === SyntaxKind.BinaryExpression && ( - (node as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && (isFalseExpression((node as BinaryExpression).left) || isFalseExpression((node as BinaryExpression).right)) || - (node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken && isFalseExpression((node as BinaryExpression).left) && isFalseExpression((node as BinaryExpression).right)); + (node as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && (isFalseExpression((node as BinaryExpression).left) || isFalseExpression((node as BinaryExpression).right)) || + (node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken && isFalseExpression((node as BinaryExpression).left) && isFalseExpression((node as BinaryExpression).right) + ); } function isReachableFlowNodeWorker(flow: FlowNode, noCacheCheck: boolean): boolean { @@ -26683,7 +27023,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (flags & FlowFlags.Start) { // Check if we should continue with the control flow of the containing function. const container = (flow as FlowStart).node; - if (container && container !== flowContainer && + if ( + container && container !== flowContainer && reference.kind !== SyntaxKind.PropertyAccessExpression && reference.kind !== SyntaxKind.ElementAccessExpression && !(reference.kind === SyntaxKind.ThisKeyword && container.kind !== SyntaxKind.ArrowFunction) @@ -26712,9 +27053,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getInitialOrAssignedType(flow: FlowAssignment) { const node = flow.node; - return getNarrowableTypeForReference(node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement ? - getInitialType(node as VariableDeclaration | BindingElement) : - getAssignedType(node), reference); + return getNarrowableTypeForReference( + node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement ? + getInitialType(node as VariableDeclaration | BindingElement) : + getAssignedType(node), + reference, + ); } function getTypeAtFlowAssignment(flow: FlowAssignment) { @@ -26873,12 +27217,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else { if (strictNullChecks) { if (optionalChainContainsReference(expr, reference)) { - type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, - t => !(t.flags & (TypeFlags.Undefined | TypeFlags.Never))); + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, t => !(t.flags & (TypeFlags.Undefined | TypeFlags.Never))); } else if (expr.kind === SyntaxKind.TypeOfExpression && optionalChainContainsReference((expr as TypeOfExpression).expression, reference)) { - type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, - t => !(t.flags & TypeFlags.Never || t.flags & TypeFlags.StringLiteral && (t as StringLiteralType).value === "undefined")); + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, t => !(t.flags & TypeFlags.Never || t.flags & TypeFlags.StringLiteral && (t as StringLiteralType).value === "undefined")); } } const access = getDiscriminantPropertyAccess(expr, type); @@ -27064,15 +27406,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isConstantVariable(symbol)) { const declaration = symbol.valueDeclaration!; // Given 'const x = obj.kind', allow 'x' as an alias for 'obj.kind' - if (isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isAccessExpression(declaration.initializer) && - isMatchingReference(reference, declaration.initializer.expression)) { + if ( + isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isAccessExpression(declaration.initializer) && + isMatchingReference(reference, declaration.initializer.expression) + ) { return declaration.initializer; } // Given 'const { kind: x } = obj', allow 'x' as an alias for 'obj.kind' if (isBindingElement(declaration) && !declaration.initializer) { const parent = declaration.parent.parent; - if (isVariableDeclaration(parent) && !parent.type && parent.initializer && (isIdentifier(parent.initializer) || isAccessExpression(parent.initializer)) && - isMatchingReference(reference, parent.initializer)) { + if ( + isVariableDeclaration(parent) && !parent.type && parent.initializer && (isIdentifier(parent.initializer) || isAccessExpression(parent.initializer)) && + isMatchingReference(reference, parent.initializer) + ) { return declaration; } } @@ -27319,8 +27665,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const facts = doubleEquals ? assumeTrue ? TypeFacts.EQUndefinedOrNull : TypeFacts.NEUndefinedOrNull : valueType.flags & TypeFlags.Null ? - assumeTrue ? TypeFacts.EQNull : TypeFacts.NENull : - assumeTrue ? TypeFacts.EQUndefined : TypeFacts.NEUndefined; + assumeTrue ? TypeFacts.EQNull : TypeFacts.NENull : + assumeTrue ? TypeFacts.EQUndefined : TypeFacts.NEUndefined; return getAdjustedTypeWithFacts(type, facts); } if (assumeTrue) { @@ -27404,8 +27750,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes); } const discriminantType = getUnionType(clauseTypes); - const caseType = - discriminantType.flags & TypeFlags.Never ? neverType : + const caseType = discriminantType.flags & TypeFlags.Never ? neverType : replacePrimitivesWithLiterals(filterType(type, t => areTypesComparable(discriminantType, t)), discriminantType); if (!hasDefaultClause) { return caseType; @@ -27416,14 +27761,22 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function narrowTypeByTypeName(type: Type, typeName: string) { switch (typeName) { - case "string": return narrowTypeByTypeFacts(type, stringType, TypeFacts.TypeofEQString); - case "number": return narrowTypeByTypeFacts(type, numberType, TypeFacts.TypeofEQNumber); - case "bigint": return narrowTypeByTypeFacts(type, bigintType, TypeFacts.TypeofEQBigInt); - case "boolean": return narrowTypeByTypeFacts(type, booleanType, TypeFacts.TypeofEQBoolean); - case "symbol": return narrowTypeByTypeFacts(type, esSymbolType, TypeFacts.TypeofEQSymbol); - case "object": return type.flags & TypeFlags.Any ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, TypeFacts.TypeofEQObject), narrowTypeByTypeFacts(type, nullType, TypeFacts.EQNull)]); - case "function": return type.flags & TypeFlags.Any ? type : narrowTypeByTypeFacts(type, globalFunctionType, TypeFacts.TypeofEQFunction); - case "undefined": return narrowTypeByTypeFacts(type, undefinedType, TypeFacts.EQUndefined); + case "string": + return narrowTypeByTypeFacts(type, stringType, TypeFacts.TypeofEQString); + case "number": + return narrowTypeByTypeFacts(type, numberType, TypeFacts.TypeofEQNumber); + case "bigint": + return narrowTypeByTypeFacts(type, bigintType, TypeFacts.TypeofEQBigInt); + case "boolean": + return narrowTypeByTypeFacts(type, booleanType, TypeFacts.TypeofEQBoolean); + case "symbol": + return narrowTypeByTypeFacts(type, esSymbolType, TypeFacts.TypeofEQSymbol); + case "object": + return type.flags & TypeFlags.Any ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, TypeFacts.TypeofEQObject), narrowTypeByTypeFacts(type, nullType, TypeFacts.EQNull)]); + case "function": + return type.flags & TypeFlags.Any ? type : narrowTypeByTypeFacts(type, globalFunctionType, TypeFacts.TypeofEQFunction); + case "undefined": + return narrowTypeByTypeFacts(type, undefinedType, TypeFacts.EQUndefined); } return narrowTypeByTypeFacts(type, nonPrimitiveType, TypeFacts.TypeofEQHostObject); } @@ -27435,14 +27788,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`, // but are classified as "function" according to `typeof`. isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? getTypeFacts(t) & facts ? t : neverType : - // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied - // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. - isTypeSubtypeOf(impliedType, t) ? impliedType : - // Neither the constituent nor the implied type is a subtype of the other, however their domains may still - // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate - // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. - getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : - neverType); + // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied + // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`. + isTypeSubtypeOf(impliedType, t) ? impliedType : + // Neither the constituent nor the implied type is a subtype of the other, however their domains may still + // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate + // possible overlap, we form an intersection. Otherwise, we eliminate the constituent. + getTypeFacts(t) & facts ? getIntersectionType([t, impliedType]) : + neverType); } function narrowTypeBySwitchOnTypeOf(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): Type { @@ -27507,8 +27860,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // This is because you may have a class `A` that defines some set of properties, and another class `B` // that defines the same set of properties as class `A`, in that case they are structurally the same // type, but when you do something like `instanceOfA.constructor === B` it will return false. - if (source.flags & TypeFlags.Object && getObjectFlags(source) & ObjectFlags.Class || - target.flags & TypeFlags.Object && getObjectFlags(target) & ObjectFlags.Class) { + if ( + source.flags & TypeFlags.Object && getObjectFlags(source) & ObjectFlags.Class || + target.flags & TypeFlags.Object && getObjectFlags(target) & ObjectFlags.Class + ) { return source.symbol === target.symbol; } @@ -27532,8 +27887,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const instanceType = mapType(rightType, getInstanceType); // Don't narrow from `any` if the target type is exactly `Object` or `Function`, and narrow // in the false branch only if the target is a non-empty object type. - if (isTypeAny(type) && (instanceType === globalObjectType || instanceType === globalFunctionType) || - !assumeTrue && !(instanceType.flags & TypeFlags.Object && !isEmptyAnonymousObjectType(instanceType))) { + if ( + isTypeAny(type) && (instanceType === globalObjectType || instanceType === globalFunctionType) || + !assumeTrue && !(instanceType.flags & TypeFlags.Object && !isEmptyAnonymousObjectType(instanceType)) + ) { return type; } return getNarrowedType(type, instanceType, assumeTrue, /*checkDerived*/ true); @@ -27581,9 +27938,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // specific of the two. When t and c are related in both directions, we prefer c for type predicates // because that is the asserted type, but t for `instanceof` because generics aren't reflected in // prototype object types. - const directlyRelated = mapType(matching || type, checkDerived ? - t => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : - t => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType); + const directlyRelated = mapType( + matching || type, + checkDerived ? + t => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : + t => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType, + ); // If no constituents are directly related, create intersections for any generic constituents that // are related by constraint. return directlyRelated.flags & TypeFlags.Never ? @@ -27609,8 +27969,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (containsMissingType(type) && isAccessExpression(reference) && isPropertyAccessExpression(callExpression.expression)) { const callAccess = callExpression.expression; - if (isMatchingReference(reference.expression, getReferenceCandidate(callAccess.expression)) && - isIdentifier(callAccess.name) && callAccess.name.escapedText === "hasOwnProperty" && callExpression.arguments.length === 1) { + if ( + isMatchingReference(reference.expression, getReferenceCandidate(callAccess.expression)) && + isIdentifier(callAccess.name) && callAccess.name.escapedText === "hasOwnProperty" && callExpression.arguments.length === 1 + ) { const argument = callExpression.arguments[0]; if (isStringLiteralLike(argument) && getAccessedPropertyName(reference) === escapeLeadingUnderscores(argument.text)) { return getTypeWithFacts(type, assumeTrue ? TypeFacts.NEUndefined : TypeFacts.EQUndefined); @@ -27628,8 +27990,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, /*checkDerived*/ false); } - if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && - !(getTypeFacts(predicate.type) & TypeFacts.EQUndefined)) { + if ( + strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & TypeFacts.EQUndefined) + ) { type = getAdjustedTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); } const access = getDiscriminantPropertyAccess(predicateArgument, type); @@ -27645,8 +28009,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // will be a subtype or the same type as the argument. function narrowType(type: Type, expr: Expression, assumeTrue: boolean): Type { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (isExpressionOfOptionalChainRoot(expr) || - isBinaryExpression(expr.parent) && (expr.parent.operatorToken.kind === SyntaxKind.QuestionQuestionToken || expr.parent.operatorToken.kind === SyntaxKind.QuestionQuestionEqualsToken) && expr.parent.left === expr) { + if ( + isExpressionOfOptionalChainRoot(expr) || + isBinaryExpression(expr.parent) && (expr.parent.operatorToken.kind === SyntaxKind.QuestionQuestionToken || expr.parent.operatorToken.kind === SyntaxKind.QuestionQuestionEqualsToken) && expr.parent.left === expr + ) { return narrowTypeByOptionality(type, expr, assumeTrue); } switch (expr.kind) { @@ -27714,7 +28080,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const type = removeOptionalTypeMarker( isWriteAccess(location) && location.kind === SyntaxKind.PropertyAccessExpression ? checkPropertyAccessExpression(location as PropertyAccessExpression, /*checkMode*/ undefined, /*writeOnly*/ true) : - getTypeOfExpression(location as Expression) + getTypeOfExpression(location as Expression), ); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -27757,8 +28123,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function hasParentWithAssignmentsMarked(node: Node) { - return !!findAncestor(node.parent, node => - (isFunctionLike(node) || isCatchClause(node)) && !!(getNodeLinks(node).flags & NodeCheckFlags.AssignmentsMarked)); + return !!findAncestor(node.parent, node => (isFunctionLike(node) || isCatchClause(node)) && !!(getNodeLinks(node).flags & NodeCheckFlags.AssignmentsMarked)); } function markNodeAssignments(node: Node) { @@ -27889,7 +28254,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled // (because the const enum value will not be inlined), or if (2) the alias is an export // of a const enum declaration that will be preserved. - if (getIsolatedModules(compilerOptions) || + if ( + getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target)) ) { @@ -28058,8 +28424,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const assignmentKind = getAssignmentTargetKind(node); if (assignmentKind) { - if (!(localOrExportSymbol.flags & SymbolFlags.Variable) && - !(isInJSFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { + if ( + !(localOrExportSymbol.flags & SymbolFlags.Variable) && + !(isInJSFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule) + ) { const assignmentError = localOrExportSymbol.flags & SymbolFlags.Enum ? Diagnostics.Cannot_assign_to_0_because_it_is_an_enum : localOrExportSymbol.flags & SymbolFlags.Class ? Diagnostics.Cannot_assign_to_0_because_it_is_a_class : localOrExportSymbol.flags & SymbolFlags.Module ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace @@ -28117,9 +28485,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === SyntaxKind.FunctionExpression || - flowContainer.kind === SyntaxKind.ArrowFunction || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && - (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol))) { + while ( + flowContainer !== declarationContainer && (flowContainer.kind === SyntaxKind.FunctionExpression || + flowContainer.kind === SyntaxKind.ArrowFunction || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && + (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol)) + ) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze @@ -28127,7 +28497,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // declaration container are the same). const assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void)) !== 0 || - isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || + isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || node.parent.kind === SyntaxKind.NonNullExpression || declaration.kind === SyntaxKind.VariableDeclaration && (declaration as VariableDeclaration).exclamationToken || declaration.flags & NodeFlags.Ambient; @@ -28183,9 +28553,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function isInsideFunctionOrInstancePropertyInitializer(node: Node, threshold: Node): boolean { - return !!findAncestor(node, n => n === threshold ? "quit" : isFunctionLike(n) || ( - n.parent && isPropertyDeclaration(n.parent) && !hasStaticModifier(n.parent) && n.parent.initializer === n - )); + return !!findAncestor(node, n => + n === threshold ? "quit" : isFunctionLike(n) || ( + n.parent && isPropertyDeclaration(n.parent) && !hasStaticModifier(n.parent) && n.parent.initializer === n + )); } function getPartOfForStatementContainingNode(node: Node, container: ForStatement) { @@ -28197,11 +28568,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function checkNestedBlockScopedBinding(node: Identifier, symbol: Symbol): void { - if (languageVersion >= ScriptTarget.ES2015 || + if ( + languageVersion >= ScriptTarget.ES2015 || (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 || !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || - symbol.valueDeclaration.parent.kind === SyntaxKind.CatchClause) { + symbol.valueDeclaration.parent.kind === SyntaxKind.CatchClause + ) { return; } @@ -28333,9 +28706,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression: Node, container: Node) { - if (isPropertyDeclaration(container) && hasStaticModifier(container) && legacyDecorators && - container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent)) { - error(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); + if ( + isPropertyDeclaration(container) && hasStaticModifier(container) && legacyDecorators && + container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent) + ) { + error(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class); } } @@ -28417,8 +28792,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function tryGetThisTypeAt(node: Node, includeGlobalThis = true, container = getThisContainer(node, /*includeArrowFunctions*/ false, /*includeClassComputedPropertyName*/ false)): Type | undefined { const isInJS = isInJSFile(node); - if (isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) { + if ( + isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container)) + ) { let thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container); // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. @@ -28479,53 +28856,63 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getClassNameFromPrototypeMethod(container: Node) { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === SyntaxKind.FunctionExpression && + if ( + container.kind === SyntaxKind.FunctionExpression && isBinaryExpression(container.parent) && - getAssignmentDeclarationKind(container.parent) === AssignmentDeclarationKind.PrototypeProperty) { + getAssignmentDeclarationKind(container.parent) === AssignmentDeclarationKind.PrototypeProperty + ) { // Get the 'x' of 'x.prototype.y = container' - return ((container.parent // x.prototype.y = container - .left as PropertyAccessExpression) // x.prototype.y + return ((container.parent // x.prototype.y = container + .left as PropertyAccessExpression) // x.prototype.y .expression as PropertyAccessExpression) // x.prototype - .expression; // x + .expression; // x } // x.prototype = { method() { } } - else if (container.kind === SyntaxKind.MethodDeclaration && + else if ( + container.kind === SyntaxKind.MethodDeclaration && container.parent.kind === SyntaxKind.ObjectLiteralExpression && isBinaryExpression(container.parent.parent) && - getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.Prototype) { + getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.Prototype + ) { return (container.parent.parent.left as PropertyAccessExpression).expression; } // x.prototype = { method: function() { } } - else if (container.kind === SyntaxKind.FunctionExpression && + else if ( + container.kind === SyntaxKind.FunctionExpression && container.parent.kind === SyntaxKind.PropertyAssignment && container.parent.parent.kind === SyntaxKind.ObjectLiteralExpression && isBinaryExpression(container.parent.parent.parent) && - getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.Prototype) { + getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.Prototype + ) { return (container.parent.parent.parent.left as PropertyAccessExpression).expression; } // Object.defineProperty(x, "method", { value: function() { } }); // Object.defineProperty(x, "method", { set: (x: () => void) => void }); // Object.defineProperty(x, "method", { get: () => function() { }) }); - else if (container.kind === SyntaxKind.FunctionExpression && + else if ( + container.kind === SyntaxKind.FunctionExpression && isPropertyAssignment(container.parent) && isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && isObjectLiteralExpression(container.parent.parent) && isCallExpression(container.parent.parent.parent) && container.parent.parent.parent.arguments[2] === container.parent.parent && - getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty) { + getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty + ) { return (container.parent.parent.parent.arguments[0] as PropertyAccessExpression).expression; } // Object.defineProperty(x, "method", { value() { } }); // Object.defineProperty(x, "method", { set(x: () => void) {} }); // Object.defineProperty(x, "method", { get() { return () => {} } }); - else if (isMethodDeclaration(container) && + else if ( + isMethodDeclaration(container) && isIdentifier(container.name) && (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && isObjectLiteralExpression(container.parent) && isCallExpression(container.parent.parent) && container.parent.parent.arguments[2] === container.parent && - getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty) { + getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty + ) { return (container.parent.parent.arguments[0] as PropertyAccessExpression).expression; } } @@ -28593,9 +28980,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isStatic(container) || isCallExpression) { nodeCheckFlag = NodeCheckFlags.SuperStatic; - if (!isCallExpression && + if ( + !isCallExpression && languageVersion >= ScriptTarget.ES2015 && languageVersion <= ScriptTarget.ES2021 && - (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) { + (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container)) + ) { // for `super.x` or `super[x]` in a static initializer, mark all enclosing // block scope containers so that we can report potential collisions with // `Reflect`. @@ -28761,8 +29150,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getContainingObjectLiteral(func: SignatureDeclaration): ObjectLiteralExpression | undefined { return (func.kind === SyntaxKind.MethodDeclaration || - func.kind === SyntaxKind.GetAccessor || - func.kind === SyntaxKind.SetAccessor) && func.parent.kind === SyntaxKind.ObjectLiteralExpression ? func.parent : + 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 as ObjectLiteralExpression : undefined; } @@ -28890,7 +29279,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isStatic(declaration)) { return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags); } - // By default, do nothing and return undefined - only the above cases have context implied by a parent + // By default, do nothing and return undefined - only the above cases have context implied by a parent } } @@ -29117,7 +29506,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * Try to find a resolved symbol for an expression without also resolving its type, as * getSymbolAtLocation would (as that could be reentrant into contextual typing) */ - function getSymbolForExpression(e: Expression) { + function getSymbolForExpression(e: Expression) { if (canHaveSymbol(e) && e.symbol) { return e.symbol; } @@ -29249,7 +29638,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const thisType = checkThisExpression(thisAccess.expression); const nameStr = getElementOrPropertyAccessName(thisAccess); return nameStr !== undefined && getTypeOfPropertyOfContextualType(thisType, nameStr) || undefined; - } function isCircularMappedProperty(symbol: Symbol) { @@ -29358,10 +29746,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getTypeArguments(t)[getTypeReferenceArity(t) - offset]; } // Return a union of the possible contextual element types with no subtype reduction. - return getElementTypeOfSliceOfTupleType(t, - firstSpreadIndex === undefined ? t.target.fixedLength : Math.min(t.target.fixedLength, firstSpreadIndex), - length === undefined || lastSpreadIndex === undefined ? fixedEndLength : Math.min(fixedEndLength, length - lastSpreadIndex), - /*writing*/ false, /*noReductions*/ true); + return getElementTypeOfSliceOfTupleType(t, firstSpreadIndex === undefined ? t.target.fixedLength : Math.min(t.target.fixedLength, firstSpreadIndex), length === undefined || lastSpreadIndex === undefined ? fixedEndLength : Math.min(fixedEndLength, length - lastSpreadIndex), /*writing*/ false, /*noReductions*/ true); } // If element index is known and a contextual property with that name exists, return it. Otherwise return the // iterated or element type of the contextual type. @@ -29401,8 +29786,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return isJsxAttributeLike(exprParent) ? getContextualType(node, contextFlags) : isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) - : undefined; + ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) + : undefined; } function getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute, contextFlags: ContextFlags | undefined): Type | undefined { @@ -29447,7 +29832,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function discriminateContextualTypeByObjectMembers(node: ObjectLiteralExpression, contextualType: UnionType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems(contextualType, + return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems( + contextualType, concatenate( map( filter(node.properties, (p): p is PropertyAssignment | ShorthandPropertyAssignment => { @@ -29462,24 +29848,25 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } return false; }), - prop => ([() => getContextFreeTypeOfExpression(prop.kind === SyntaxKind.PropertyAssignment ? prop.initializer : prop.name), prop.symbol.escapedName] as const) + prop => ([() => getContextFreeTypeOfExpression(prop.kind === SyntaxKind.PropertyAssignment ? prop.initializer : prop.name), prop.symbol.escapedName] as const), ), map( filter(getPropertiesOfType(contextualType), s => !!(s.flags & SymbolFlags.Optional) && !!node?.symbol?.members && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName)), - s => [() => undefinedType, s.escapedName] as const - ) + s => [() => undefinedType, s.escapedName] as const, + ), ), - isTypeAssignableTo + isTypeAssignableTo, ); } function discriminateContextualTypeByJSXAttributes(node: JsxAttributes, contextualType: UnionType) { const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return discriminateTypeByDiscriminableItems(contextualType, + return discriminateTypeByDiscriminableItems( + contextualType, concatenate( map( filter(node.properties, p => !!p.symbol && p.kind === SyntaxKind.JsxAttribute && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), - prop => ([!(prop as JsxAttribute).initializer ? (() => trueType) : (() => getContextFreeTypeOfExpression((prop as JsxAttribute).initializer!)), prop.symbol.escapedName] as const) + prop => ([!(prop as JsxAttribute).initializer ? (() => trueType) : (() => getContextFreeTypeOfExpression((prop as JsxAttribute).initializer!)), prop.symbol.escapedName] as const), ), map( filter(getPropertiesOfType(contextualType), s => { @@ -29492,10 +29879,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), - s => [() => undefinedType, s.escapedName] as const - ) + s => [() => undefinedType, s.escapedName] as const, + ), ), - isTypeAssignableTo + isTypeAssignableTo, ); } @@ -29514,7 +29901,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // and thus it would prevent `getTypeOfPropertyOfContextualType` from obtaining per-position contextual type for elements of array literal expressions. // Apparent type of other mapped types is already the mapped type itself so we can just avoid calling `getApparentType` here for all mapped types. t => getObjectFlags(t) & ObjectFlags.Mapped ? t : getApparentType(t), - /*noReductions*/ true + /*noReductions*/ true, ); return apparentType.flags & TypeFlags.Union && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType as UnionType) : apparentType.flags & TypeFlags.Union && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType as UnionType) : @@ -29799,10 +30186,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType) : forcedLookupLocation === "" - // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead - ? getReturnTypeOfSignature(sig) - // Otherwise get the type of the property on the signature return type - : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + ? getReturnTypeOfSignature(sig) + // Otherwise get the type of the property on the signature return type + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); if (!attributesType) { // There is no property named 'props' on this instance type @@ -29851,8 +30238,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { signatures, (left: Signature | undefined, right) => left === right || !left ? left - : compareTypeParametersIdentical(left.typeParameters, right!.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right!) - : undefined) + : compareTypeParametersIdentical(left.typeParameters, right!.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right!) + : undefined, + ) : undefined; } @@ -29873,7 +30261,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const longest = leftCount >= rightCount ? left : right; const shorter = longest === left ? right : left; const longestCount = longest === left ? leftCount : rightCount; - const eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right); const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); for (let i = 0; i < longestCount; i++) { @@ -29897,7 +30285,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { undefined; const paramSymbol = createSymbol( SymbolFlags.FunctionScopedVariable | (isOptional && !isRestParam ? SymbolFlags.Optional : 0), - paramName || `arg${i}` as __String + paramName || `arg${i}` as __String, ); paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType; params[i] = paramSymbol; @@ -29932,7 +30320,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgCount, - (left.flags | right.flags) & SignatureFlags.PropagatingFlags + (left.flags | right.flags) & SignatureFlags.PropagatingFlags, ); result.compositeKind = TypeFlags.Intersection; result.compositeSignatures = concatenate(left.compositeKind === TypeFlags.Intersection && left.compositeSignatures || [left], [right]); @@ -30095,7 +30483,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { elementFlags.push(hasOmittedExpression ? ElementFlags.Optional : ElementFlags.Required); if (inTupleContext && checkMode && checkMode & CheckMode.Inferential && !(checkMode & CheckMode.SkipContextSensitive) && isContextSensitive(e)) { const inferenceContext = getInferenceContext(node); - Debug.assert(inferenceContext); // In CheckMode.Inferential we should always have an inference context + Debug.assert(inferenceContext); // In CheckMode.Inferential we should always have an inference context addIntraExpressionInferenceSite(inferenceContext, e, type); } } @@ -30107,9 +30495,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (forceTuple || inConstContext || inTupleContext) { return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext)); } - return createArrayLiteralType(createArrayType(elementTypes.length ? - getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & ElementFlags.Variadic ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), UnionReduction.Subtype) : - strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext)); + return createArrayLiteralType(createArrayType( + elementTypes.length ? + getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & ElementFlags.Variadic ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), UnionReduction.Subtype) : + strictNullChecks ? implicitNeverType : undefinedWideningType, + inConstContext, + )); } function createArrayLiteralType(type: Type) { @@ -30147,9 +30538,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkComputedPropertyName(node: ComputedPropertyName): Type { const links = getNodeLinks(node.expression); if (!links.resolvedType) { - if ((isTypeLiteralNode(node.parent.parent) || isClassLike(node.parent.parent) || isInterfaceDeclaration(node.parent.parent)) + if ( + (isTypeLiteralNode(node.parent.parent) || isClassLike(node.parent.parent) || isInterfaceDeclaration(node.parent.parent)) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === SyntaxKind.InKeyword - && node.parent.kind !== SyntaxKind.GetAccessor && node.parent.kind !== SyntaxKind.SetAccessor) { + && node.parent.kind !== SyntaxKind.GetAccessor && node.parent.kind !== SyntaxKind.SetAccessor + ) { return links.resolvedType = errorType; } links.resolvedType = checkExpression(node.expression); @@ -30169,9 +30562,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // This will allow types number, string, symbol or any. It will also allow enums, the unknown // type, and any union of these types (like string | number). - if (links.resolvedType.flags & TypeFlags.Nullable || + if ( + links.resolvedType.flags & TypeFlags.Nullable || !isTypeAssignableToKind(links.resolvedType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike) && - !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType) + ) { error(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } } @@ -30194,9 +30589,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const propTypes: Type[] = []; for (let i = offset; i < properties.length; i++) { const prop = properties[i]; - if (keyType === stringType && !isSymbolWithSymbolName(prop) || + if ( + keyType === stringType && !isSymbolWithSymbolName(prop) || keyType === numberType && isSymbolWithNumericName(prop) || - keyType === esSymbolType && isSymbolWithSymbolName(prop)) { + keyType === esSymbolType && isSymbolWithSymbolName(prop) + ) { propTypes.push(getTypeOfSymbol(properties[i])); } } @@ -30255,9 +30652,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let member = getSymbolOfDeclaration(memberDecl); const computedNameType = memberDecl.name && memberDecl.name.kind === SyntaxKind.ComputedPropertyName ? checkComputedPropertyName(memberDecl.name) : undefined; - if (memberDecl.kind === SyntaxKind.PropertyAssignment || + if ( + memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment || - isObjectLiteralMethod(memberDecl)) { + isObjectLiteralMethod(memberDecl) + ) { let type = memberDecl.kind === SyntaxKind.PropertyAssignment ? checkPropertyAssignment(memberDecl, checkMode) : // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`. @@ -30286,8 +30685,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - const isOptional = - (memberDecl.kind === SyntaxKind.PropertyAssignment && hasDefaultValue(memberDecl.initializer)) || + const isOptional = (memberDecl.kind === SyntaxKind.PropertyAssignment && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= SymbolFlags.Optional; @@ -30300,10 +30698,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (impliedProp) { prop.flags |= impliedProp.flags & SymbolFlags.Optional; } - else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, stringType)) { - error(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, - symbolToString(member), typeToString(contextualType)); + error(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); } } @@ -30318,10 +30714,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { member = prop; allPropertiesTable?.set(prop.escapedName, prop); - if (contextualType && checkMode & CheckMode.Inferential && !(checkMode & CheckMode.SkipContextSensitive) && - (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.MethodDeclaration) && isContextSensitive(memberDecl)) { + if ( + contextualType && checkMode & CheckMode.Inferential && !(checkMode & CheckMode.SkipContextSensitive) && + (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.MethodDeclaration) && isContextSensitive(memberDecl) + ) { const inferenceContext = getInferenceContext(node); - Debug.assert(inferenceContext); // In CheckMode.Inferential we should always have an inference context + Debug.assert(inferenceContext); // In CheckMode.Inferential we should always have an inference context const inferenceNode = memberDecl.kind === SyntaxKind.PropertyAssignment ? memberDecl.initializer : memberDecl; addIntraExpressionInferenceSite(inferenceContext, inferenceNode, type); } @@ -30400,19 +30798,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const rootPatternParent = findAncestor(contextualType.pattern!.parent, n => n.kind === SyntaxKind.VariableDeclaration || n.kind === SyntaxKind.BinaryExpression || - n.kind === SyntaxKind.Parameter - ); + n.kind === SyntaxKind.Parameter); const spreadOrOutsideRootObject = findAncestor(node, n => n === rootPatternParent || - n.kind === SyntaxKind.SpreadAssignment - )!; + n.kind === SyntaxKind.SpreadAssignment)!; if (spreadOrOutsideRootObject.kind !== SyntaxKind.SpreadAssignment) { for (const prop of getPropertiesOfType(contextualType)) { if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { if (!(prop.flags & SymbolFlags.Optional)) { - error(prop.valueDeclaration || tryCast(prop, isTransientSymbol)?.links.bindingElement, - Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + error(prop.valueDeclaration || tryCast(prop, isTransientSymbol)?.links.bindingElement, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.escapedName, prop); propertiesArray.push(prop); @@ -30501,11 +30896,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // by default, jsx:'react' will use jsxFactory = React.createElement and jsxFragmentFactory = React.Fragment // if jsxFactory compiler option is provided, ensure jsxFragmentFactory compiler option or @jsxFrag pragma is provided too const nodeSourceFile = getSourceFileOfNode(node); - if (getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) - && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) { - error(node, compilerOptions.jsxFactory - ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option - : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments); + if ( + getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) + && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag") + ) { + error( + node, + compilerOptions.jsxFactory + ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option + : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments, + ); } checkJsxChildren(node); @@ -30526,7 +30926,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkJsxAttribute(node: JsxAttribute, checkMode?: CheckMode) { return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) - : trueType; // is sugar for + : trueType; // is sugar for } /** @@ -30577,7 +30977,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (contextualType && checkMode & CheckMode.Inferential && !(checkMode & CheckMode.SkipContextSensitive) && isContextSensitive(attributeDecl)) { const inferenceContext = getInferenceContext(attributes); - Debug.assert(inferenceContext); // In CheckMode.Inferential we should always have an inference context + Debug.assert(inferenceContext); // In CheckMode.Inferential we should always have an inference context const inferenceNode = (attributeDecl.initializer as JsxExpression).expression!; addIntraExpressionInferenceSite(inferenceContext, inferenceNode, exprType); } @@ -30638,9 +31038,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol; const childPropMap = createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, emptyArray), - attributes.symbol, objectFlags, /*readonly*/ false); - + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, emptyArray), attributes.symbol, objectFlags, /*readonly*/ false); } } @@ -30774,8 +31172,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const isClassic = getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic; const errorMessage = isClassic - ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option - : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; + ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option + : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; const mod = resolveExternalModule(location!, runtimeImportSpecifier, errorMessage, location!); const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : undefined; if (links) { @@ -30969,8 +31367,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else if (links.jsxFlags & JsxFlags.IntrinsicIndexedElement) { const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText; - return links.resolvedJsxElementAttributesType = - getApplicableIndexInfoForName(getJsxType(JsxNames.IntrinsicElements, node), propName)?.type || errorType; + return links.resolvedJsxElementAttributesType = getApplicableIndexInfoForName(getJsxType(JsxNames.IntrinsicElements, node), propName)?.type || errorType; } else { return links.resolvedJsxElementAttributesType = errorType; @@ -31017,7 +31414,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (length((declaredManagedType as GenericType).typeParameters) >= typeArguments.length) { const args = fillMissingTypeArguments(typeArguments, (declaredManagedType as GenericType).typeParameters, typeArguments.length, inJs); - return createTypeReference((declaredManagedType as GenericType), args); + return createTypeReference(declaredManagedType as GenericType, args); } return undefined; } @@ -31087,7 +31484,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (isNodeOpeningLikeElement) { - const jsxOpeningLikeNode = node ; + const jsxOpeningLikeNode = node; const sig = getResolvedSignature(jsxOpeningLikeNode); checkDeprecatedSignature(sig, node); @@ -31126,10 +31523,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // For backwards compatibility a symbol-named property is satisfied by a string index signature. This // is incorrect and inconsistent with element access expressions, where it is an error, so eventually // we should remove this exception. - if (getPropertyOfObjectType(targetType, name) || + if ( + getPropertyOfObjectType(targetType, name) || getApplicableIndexInfoForName(targetType, name) || isLateBoundName(name) && getIndexInfoOfType(targetType, stringType) || - isComparingJsxAttributes && isHyphenatedJsxName(name)) { + isComparingJsxAttributes && isHyphenatedJsxName(name) + ) { // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. return true; } @@ -31194,8 +31593,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { */ function checkPropertyAccessibility( node: PropertyAccessExpression | QualifiedName | PropertyAccessExpression | VariableDeclaration | ParameterDeclaration | ImportTypeNode | PropertyAssignment | ShorthandPropertyAssignment | BindingElement, - isSuper: boolean, writing: boolean, type: Type, prop: Symbol, reportError = true): boolean { - + isSuper: boolean, + writing: boolean, + type: Type, + prop: Symbol, + reportError = true, + ): boolean { const errorNode = !reportError ? undefined : node.kind === SyntaxKind.QualifiedName ? node.right : node.kind === SyntaxKind.ImportType ? node : @@ -31214,10 +31617,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * @param prop The symbol for the property being accessed. * @param errorNode The node where we should report an invalid property access error, or undefined if we should not report errors. */ - function checkPropertyAccessibilityAtLocation(location: Node, - isSuper: boolean, writing: boolean, - containingType: Type, prop: Symbol, errorNode?: Node): boolean { - + function checkPropertyAccessibilityAtLocation(location: Node, isSuper: boolean, writing: boolean, containingType: Type, prop: Symbol, errorNode?: Node): boolean { const flags = getDeclarationModifierFlagsFromSymbol(prop, writing); if (isSuper) { @@ -31242,25 +31642,21 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. if (errorNode) { - error(errorNode, - Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, - symbolToString(prop), - typeToString(getDeclaringClass(prop)!)); + error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)!)); } return false; } } // Referencing abstract properties within their own constructors is not allowed - if ((flags & ModifierFlags.Abstract) && symbolHasNonMethodDeclaration(prop) && - (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || isObjectBindingPattern(location.parent) && isThisInitializedDeclaration(location.parent.parent))) { + if ( + (flags & ModifierFlags.Abstract) && symbolHasNonMethodDeclaration(prop) && + (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || isObjectBindingPattern(location.parent) && isThisInitializedDeclaration(location.parent.parent)) + ) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)!); if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(location)) { if (errorNode) { - error(errorNode, - Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, - symbolToString(prop), - getTextOfIdentifierOrLiteral(declaringClassDeclaration.name!)); + error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name!)); } return false; } @@ -31278,10 +31674,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)!)!; if (!isNodeWithinClass(location, declaringClassDeclaration)) { if (errorNode) { - error(errorNode, - Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, - symbolToString(prop), - typeToString(getDeclaringClass(prop)!)); + error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)!)); } return false; } @@ -31309,10 +31702,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { enclosingClass = enclosingClass && isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing); if (flags & ModifierFlags.Static || !enclosingClass) { if (errorNode) { - error(errorNode, - Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, - symbolToString(prop), - typeToString(getDeclaringClass(prop) || containingType)); + error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || containingType)); } return false; } @@ -31327,9 +31717,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (!containingType || !hasBaseType(containingType, enclosingClass)) { if (errorNode) { - error(errorNode, - Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, - symbolToString(prop), typeToString(enclosingClass), typeToString(containingType)); + error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(containingType)); } return false; } @@ -31380,34 +31768,40 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error(node, Diagnostics.The_value_0_cannot_be_used_here, "undefined"); return; } - error(node, facts & TypeFacts.IsUndefined ? facts & TypeFacts.IsNull ? - Diagnostics._0_is_possibly_null_or_undefined : - Diagnostics._0_is_possibly_undefined : - Diagnostics._0_is_possibly_null, - nodeText + error( + node, + facts & TypeFacts.IsUndefined ? facts & TypeFacts.IsNull ? + Diagnostics._0_is_possibly_null_or_undefined : + Diagnostics._0_is_possibly_undefined : + Diagnostics._0_is_possibly_null, + nodeText, ); } else { - error(node, facts & TypeFacts.IsUndefined ? facts & TypeFacts.IsNull ? - Diagnostics.Object_is_possibly_null_or_undefined : - Diagnostics.Object_is_possibly_undefined : - Diagnostics.Object_is_possibly_null + error( + node, + facts & TypeFacts.IsUndefined ? facts & TypeFacts.IsNull ? + Diagnostics.Object_is_possibly_null_or_undefined : + Diagnostics.Object_is_possibly_undefined : + Diagnostics.Object_is_possibly_null, ); } } function reportCannotInvokePossiblyNullOrUndefinedError(node: Node, facts: TypeFacts) { - error(node, facts & TypeFacts.IsUndefined ? facts & TypeFacts.IsNull ? - Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : - Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : - Diagnostics.Cannot_invoke_an_object_which_is_possibly_null + error( + node, + facts & TypeFacts.IsUndefined ? facts & TypeFacts.IsNull ? + Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ); } function checkNonNullTypeWithReporter( type: Type, node: Node, - reportError: (node: Node, facts: TypeFacts) => void + reportError: (node: Node, facts: TypeFacts) => void, ): Type { if (strictNullChecks && type.flags & TypeFlags.Unknown) { if (isEntityNameExpression(node)) { @@ -31562,7 +31956,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { right, Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling, diagName, - typeToString(leftType) + typeToString(leftType), ); addRelatedInfo( @@ -31570,13 +31964,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { createDiagnosticForNode( lexicalValueDecl, Diagnostics.The_shadowing_declaration_of_0_is_defined_here, - diagName + diagName, ), createDiagnosticForNode( typeValueDecl, Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here, - diagName - ) + diagName, + ), ); return true; } @@ -31585,7 +31979,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { right, Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, - diagnosticName(typeClass.name || anon) + diagnosticName(typeClass.name || anon), ); return true; } @@ -31661,11 +32055,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // The exceptions are: // 1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and // 2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`. - if (isIdentifier(left) && parentSymbol && ( - getIsolatedModules(compilerOptions) || - !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & SymbolFlags.EnumMember && node.parent.kind === SyntaxKind.EnumMember)) || - shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node) - )) { + if ( + isIdentifier(left) && parentSymbol && ( + getIsolatedModules(compilerOptions) || + !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & SymbolFlags.EnumMember && node.parent.kind === SyntaxKind.EnumMember)) || + shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node) + ) + ) { markAliasReferenced(parentSymbol, node); } @@ -31752,10 +32148,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (assignmentKind === AssignmentKind.Definite) { return removeMissingType(propType, !!(prop && prop.flags & SymbolFlags.Optional)); } - if (prop && + if ( + prop && !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor)) && !(prop.flags & SymbolFlags.Method && propType.flags & TypeFlags.Union) - && !isDuplicatedCommonJSExport(prop.declarations)) { + && !isDuplicatedCommonJSExport(prop.declarations) + ) { return propType; } if (propType === autoType) { @@ -31778,10 +32176,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } } - else if (strictNullChecks && prop && prop.valueDeclaration && + else if ( + strictNullChecks && prop && prop.valueDeclaration && isPropertyAccessExpression(prop.valueDeclaration) && getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && - getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration) + ) { assumeUninitialized = true; } const flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); @@ -31801,25 +32201,27 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let diagnosticMessage; const declarationName = idText(right); - if (isInPropertyInitializerOrClassStaticBlock(node) + if ( + isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & ModifierFlags.Static) - && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop)) + ) { diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === SyntaxKind.ClassDeclaration && + else if ( + valueDeclaration.kind === SyntaxKind.ClassDeclaration && node.parent.kind !== SyntaxKind.TypeReference && !(valueDeclaration.flags & NodeFlags.Ambient) && - !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + ) { diagnosticMessage = error(right, Diagnostics.Class_0_used_before_its_declaration, declarationName); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, - createDiagnosticForNode(valueDeclaration, Diagnostics._0_is_declared_here, declarationName) - ); + addRelatedInfo(diagnosticMessage, createDiagnosticForNode(valueDeclaration, Diagnostics._0_is_declared_here, declarationName)); } } @@ -32014,7 +32416,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { ["string", "number", "boolean", "object", "bigint", "symbol"], s => symbols.has((s.charAt(0).toUpperCase() + s.slice(1)) as __String) ? createSymbol(SymbolFlags.TypeAlias, s as __String) as Symbol - : undefined); + : undefined, + ); candidates = primitives.concat(arrayFrom(symbols.values())); } else { @@ -32091,7 +32494,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getCandidateName(candidate: Symbol) { const candidateName = symbolName(candidate); - if (startsWith(candidateName, "\"")) { + if (startsWith(candidateName, '"')) { return undefined; } @@ -32161,11 +32564,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * @param property the accessed property's symbol. */ function isValidPropertyAccessForCompletions(node: PropertyAccessExpression | ImportTypeNode | QualifiedName, type: Type, property: Symbol): boolean { - return isPropertyAccessible(node, - node.kind === SyntaxKind.PropertyAccessExpression && node.expression.kind === SyntaxKind.SuperKeyword, - /*isWrite*/ false, - type, - property); + return isPropertyAccessible(node, node.kind === SyntaxKind.PropertyAccessExpression && node.expression.kind === SyntaxKind.SuperKeyword, /*isWrite*/ false, type, property); // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context. } @@ -32173,8 +32572,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node: PropertyAccessExpression | QualifiedName | ImportTypeNode, isSuper: boolean, propertyName: __String, - type: Type): boolean { - + type: Type, + ): boolean { // Short-circuiting for improved performance. if (isTypeAny(type)) { return true; @@ -32199,16 +32598,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isSuper: boolean, isWrite: boolean, containingType: Type, - property: Symbol): boolean { - + property: Symbol, + ): boolean { // Short-circuiting for improved performance. if (isTypeAny(containingType)) { return true; } // A #private property access in an optional chain is an error dealt with by the parser. - // The checker does not check for it, so we need to do our own check here. - if (property.valueDeclaration && isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) { + // The checker does not check for it, so we need to do our own check here. + if (property.valueDeclaration && isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) { const declClass = getContainingClass(property.valueDeclaration); return !isOptionalChain(node) && !!findAncestor(node, parent => parent === declClass); } @@ -32252,10 +32651,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let child: Node = expr; let node = expr.parent; while (node) { - if (node.kind === SyntaxKind.ForInStatement && + if ( + node.kind === SyntaxKind.ForInStatement && child === (node as ForInStatement).statement && getForInVariableSymbol(node as ForInStatement) === symbol && - hasNumericPropertyNames(getTypeOfExpression((node as ForInStatement).expression))) { + hasNumericPropertyNames(getTypeOfExpression((node as ForInStatement).expression)) + ) { return true; } child = node; @@ -32708,12 +33109,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { mapper = createTypeMapper(typeParameters, typeArgumentTypes); } const typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo( - typeArgument, - getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), - reportErrors ? typeArgumentNodes[i] : undefined, - typeArgumentHeadMessage, - errorInfo)) { + if ( + !checkTypeAssignableTo( + typeArgument, + getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), + reportErrors ? typeArgumentNodes[i] : undefined, + typeArgumentHeadMessage, + errorInfo, + ) + ) { return undefined; } } @@ -32748,7 +33152,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkMode: CheckMode, reportErrors: boolean, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, - errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } + errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; }, ) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, @@ -32764,7 +33168,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node.attributes, /*headMessage*/ undefined, containingMessageChain, - errorOutputContainer); + errorOutputContainer, + ); function checkTagNameDoesNotExpectTooManyArguments(): boolean { if (getJsxNamespaceContainerForImplicitImport(node)) { @@ -32853,7 +33258,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { reportErrors: boolean, containingMessageChain: (() => DiagnosticMessageChain | undefined) | undefined, ): readonly Diagnostic[] | undefined { - const errorOutputContainer: { errors?: Diagnostic[], skipLogging?: boolean } = { errors: undefined, skipLogging: true }; + const errorOutputContainer: { errors?: Diagnostic[]; skipLogging?: boolean; } = { errors: undefined, skipLogging: true }; if (isJsxOpeningLikeElement(node)) { if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) { Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors"); @@ -32978,8 +33383,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (spreadType && isTupleType(spreadType)) { forEach(getElementTypes(spreadType), (t, i) => { const flags = spreadType.target.elementFlags[i]; - const syntheticArg = createSyntheticExpression(arg, flags & ElementFlags.Rest ? createArrayType(t) : t, - !!(flags & ElementFlags.Variable), spreadType.target.labeledElementDeclarations?.[i]); + const syntheticArg = createSyntheticExpression(arg, flags & ElementFlags.Rest ? createArrayType(t) : t, !!(flags & ElementFlags.Variable), spreadType.target.labeledElementDeclarations?.[i]); effectiveArgs.push(syntheticArg); }); } @@ -33122,9 +33526,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isVoidPromiseError && isInJSFile(node)) { return getDiagnosticForCallNode(node, Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments); } - const error = - isDecorator(node) ? - hasRestParameter ? Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0 : + const error = isDecorator(node) ? + hasRestParameter ? Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0 : Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0 : hasRestParameter ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : isVoidPromiseError ? Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : @@ -33152,10 +33555,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const parameter = closestSignature?.declaration?.parameters[closestSignature.thisParameter ? args.length + 1 : args.length]; if (parameter) { - const messageAndArgs: DiagnosticAndArguments = - isBindingPattern(parameter.name) ? [Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided] - : isRestParameter(parameter) ? [Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided, idText(getFirstIdentifier(parameter.name))] - : [Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : idText(getFirstIdentifier(parameter.name))]; + const messageAndArgs: DiagnosticAndArguments = isBindingPattern(parameter.name) ? [Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided] + : isRestParameter(parameter) ? [Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided, idText(getFirstIdentifier(parameter.name))] + : [Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : idText(getFirstIdentifier(parameter.name))]; const parameterError = createDiagnosticForNode(parameter, ...messageAndArgs); return addRelatedInfo(diagnostic, parameterError); } @@ -33187,11 +33589,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const min = getMinTypeArgumentCount(sig.typeParameters); const max = length(sig.typeParameters); if (headMessage) { - let chain = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Expected_0_type_arguments_but_got_1, min < max ? min + "-" + max : min , argCount); + let chain = chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Expected_0_type_arguments_but_got_1, min < max ? min + "-" + max : min, argCount); chain = chainDiagnosticMessages(chain, headMessage); return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain); } - return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min < max ? min + "-" + max : min , argCount); + return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min < max ? min + "-" + max : min, argCount); } // Overloads exist let belowArgCount = -Infinity; @@ -33289,8 +33691,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - const signatureHelpTrailingComma = - !!(checkMode & CheckMode.IsForSignatureHelp) && node.kind === SyntaxKind.CallExpression && node.arguments.hasTrailingComma; + const signatureHelpTrailingComma = !!(checkMode & CheckMode.IsForSignatureHelp) && node.kind === SyntaxKind.CallExpression && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument @@ -33379,7 +33780,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { Debug.assert(diags.length > 0, "No errors reported for 3 or fewer overload signatures"); let chain = chainDiagnosticMessages( map(diags, createDiagnosticMessageChainFromDiagnostic), - Diagnostics.No_overload_matches_this_call); + Diagnostics.No_overload_matches_this_call, + ); if (headMessage) { chain = chainDiagnosticMessages(chain, headMessage); } @@ -33550,9 +33952,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const { min: minArgumentCount, max: maxNonRestParam } = minAndMax(candidates, getNumNonRestParameters); const parameters: Symbol[] = []; for (let i = 0; i < maxNonRestParam; i++) { - const symbols = mapDefined(candidates, s => signatureHasRestParameter(s) ? - i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : - i < s.parameters.length ? s.parameters[i] : undefined); + const symbols = mapDefined(candidates, s => + signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined); Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, candidate => tryGetTypeAtPosition(candidate, i)))); } @@ -33574,7 +33977,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), /*resolvedTypePredicate*/ undefined, minArgumentCount, - flags); + flags, + ); } function getNumNonRestParameters(signature: Signature): number { @@ -33686,7 +34090,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { funcType = checkNonNullTypeWithReporter( funcType, node.expression, - reportCannotInvokePossiblyNullOrUndefinedError + reportCannotInvokePossiblyNullOrUndefinedError, ); if (funcType === silentNeverType) { @@ -33934,7 +34338,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; } - function invocationErrorDetails(errorTarget: Node, apparentType: Type, kind: SignatureKind): { messageChain: DiagnosticMessageChain, relatedMessage: DiagnosticMessage | undefined } { + function invocationErrorDetails(errorTarget: Node, apparentType: Type, kind: SignatureKind): { messageChain: DiagnosticMessageChain; relatedMessage: DiagnosticMessage | undefined; } { let errorInfo: DiagnosticMessageChain | undefined; const isCall = kind === SignatureKind.Call; const awaitedType = getAwaitedType(apparentType); @@ -33959,14 +34363,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, - typeToString(constituent) + typeToString(constituent), ); errorInfo = chainDiagnosticMessages( errorInfo, isCall ? Diagnostics.Not_all_constituents_of_type_0_are_callable : Diagnostics.Not_all_constituents_of_type_0_are_constructable, - typeToString(apparentType) + typeToString(apparentType), ); } if (hasSignatures) { @@ -33981,7 +34385,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isCall ? Diagnostics.No_constituent_of_type_0_is_callable : Diagnostics.No_constituent_of_type_0_is_constructable, - typeToString(apparentType) + typeToString(apparentType), ); } if (!errorInfo) { @@ -33990,7 +34394,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isCall ? Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other : Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, - typeToString(apparentType) + typeToString(apparentType), ); } } @@ -34000,7 +34404,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures, - typeToString(apparentType) + typeToString(apparentType), ); } @@ -34045,9 +34449,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target!), kind); if (!sigs || !sigs.length) return; - addRelatedInfo(diagnostic, - createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead) - ); + addRelatedInfo(diagnostic, createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } @@ -34151,10 +34553,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // file would probably be preferable. const typeSymbol = exports && getSymbol(exports, JsxNames.Element, SymbolFlags.Type); const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, SymbolFlags.Type, node); - const declaration = factory.createFunctionTypeNode(/*typeParameters*/ undefined, - [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "props", /*questionToken*/ undefined, nodeBuilder.typeToTypeNode(result, node))], - returnNode ? factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) - ); + const declaration = factory.createFunctionTypeNode(/*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "props", /*questionToken*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : factory.createKeywordTypeNode(SyntaxKind.AnyKeyword)); const parameterSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "props" as __String); parameterSymbol.links.type = result; return createSignature( @@ -34165,7 +34564,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, /*resolvedTypePredicate*/ undefined, 1, - SignatureFlags.None + SignatureFlags.None, ); } @@ -34404,14 +34803,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (node.kind === SyntaxKind.NewExpression) { const declaration = signature.declaration; - if (declaration && + if ( + declaration && declaration.kind !== SyntaxKind.Constructor && declaration.kind !== SyntaxKind.ConstructSignature && declaration.kind !== SyntaxKind.ConstructorType && !(isJSDocSignature(declaration) && getJSDocRoot(declaration)?.parent?.kind === SyntaxKind.Constructor) && !isJSDocConstructSignature(declaration) && - !isJSConstructor(declaration)) { - + !isJSConstructor(declaration) + ) { // When resolved signature is a call signature (and not a construct signature) the result type is any if (noImplicitAny) { error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); @@ -34431,8 +34831,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (returnType.flags & TypeFlags.ESSymbolLike && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent)); } - if (node.kind === SyntaxKind.CallExpression && !node.questionDotToken && node.parent.kind === SyntaxKind.ExpressionStatement && - returnType.flags & TypeFlags.Void && getTypePredicateOfSignature(signature)) { + if ( + node.kind === SyntaxKind.CallExpression && !node.questionDotToken && node.parent.kind === SyntaxKind.ExpressionStatement && + returnType.flags & TypeFlags.Void && getTypePredicateOfSignature(signature) + ) { if (!isDottedName(node.expression)) { error(node.expression, Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name); } @@ -34538,9 +34940,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (moduleSymbol) { const esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontResolveAlias*/ true, /*suppressInteropError*/ false); if (esModuleSymbol) { - return createPromiseReturnType(node, + return createPromiseReturnType( + node, getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || - getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) + getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier), ); } } @@ -34610,8 +35013,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const targetDeclarationKind = resolvedRequire.flags & SymbolFlags.Function ? SyntaxKind.FunctionDeclaration : resolvedRequire.flags & SymbolFlags.Variable - ? SyntaxKind.VariableDeclaration - : SyntaxKind.Unknown; + ? SyntaxKind.VariableDeclaration + : SyntaxKind.Unknown; if (targetDeclarationKind !== SyntaxKind.Unknown) { const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind)!; // function/variable declaration should be ambient @@ -34713,8 +35116,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { addLazyDiagnostic(() => { const widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, errNode, - Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); + checkTypeComparableTo(exprType, targetType, errNode, Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first); } }); } @@ -34920,7 +35322,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return restParameter.escapedName; } - function getParameterIdentifierInfoAtPosition(signature: Signature, pos: number): { parameter: Identifier, parameterName: __String, isRestParameter: boolean } | undefined { + function getParameterIdentifierInfoAtPosition(signature: Signature, pos: number): { parameter: Identifier; parameterName: __String; isRestParameter: boolean; } | undefined { if (signature.declaration?.kind === SyntaxKind.JSDocFunctionType) { return undefined; } @@ -34931,7 +35333,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return paramIdent ? { parameter: paramIdent, parameterName: param.escapedName, - isRestParameter: false + isRestParameter: false, } : undefined; } @@ -34965,7 +35367,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getParameterDeclarationIdentifier(symbol: Symbol) { return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name; } - function isValidDeclarationForTupleLabel(d: Declaration): d is NamedTupleMember | (ParameterDeclaration & { name: Identifier }) { + function isValidDeclarationForTupleLabel(d: Declaration): d is NamedTupleMember | (ParameterDeclaration & { name: Identifier; }) { return d.kind === SyntaxKind.NamedTupleMember || (isParameter(d) && d.name && isIdentifier(d.name)); } @@ -35161,11 +35563,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. const parameter = last(signature.parameters); - if (parameter.valueDeclaration - ? !getEffectiveTypeAnnotationNode(parameter.valueDeclaration as ParameterDeclaration) - // a declarationless parameter may still have a `.type` already set by its construction logic - // (which may pull a type from a jsdoc) - only allow fixing on `DeferredType` parameters with a fallback type - : !!(getCheckFlags(parameter) & CheckFlags.DeferredType) + if ( + parameter.valueDeclaration + ? !getEffectiveTypeAnnotationNode(parameter.valueDeclaration as ParameterDeclaration) + // a declarationless parameter may still have a `.type` already set by its construction logic + // (which may pull a type from a jsdoc) - only allow fixing on `DeferredType` parameters with a fallback type + : !!(getCheckFlags(parameter) & CheckFlags.DeferredType) ) { const contextualParameterType = getRestTypeAtPosition(context, len); assignParameterType(parameter, contextualParameterType); @@ -35262,8 +35665,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isStatic = hasStaticModifier(node); const isPrivate = isPrivateIdentifier(node.name); const nameType = isPrivate ? getStringLiteralType(idText(node.name)) : getLiteralTypeFromPropertyName(node.name); - const contextType = - isMethodDeclaration(node) ? createClassMethodDecoratorContextType(thisType, valueType) : + const contextType = isMethodDeclaration(node) ? createClassMethodDecoratorContextType(thisType, valueType) : isGetAccessorDeclaration(node) ? createClassGetterDecoratorContextType(thisType, valueType) : isSetAccessorDeclaration(node) ? createClassSetterDecoratorContextType(thisType, valueType) : isAutoAccessorPropertyDeclaration(node) ? createClassAccessorDecoratorContextType(thisType, valueType) : @@ -35271,7 +35673,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { Debug.failBadSyntaxKind(node); const overrideType = getClassMemberDecoratorContextOverrideType(nameType, isPrivate, isStatic); return getIntersectionType([contextType, overrideType]); - } function createClassAccessorDecoratorTargetType(thisType: Type, valueType: Type) { @@ -35422,8 +35823,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // In all three cases, the `This` type argument is the "final type" of either the class or // instance, depending on whether the member was `static`. - const valueType = - isMethodDeclaration(node) ? getOrCreateTypeFromSignature(getSignatureFromDeclaration(node)) : + const valueType = isMethodDeclaration(node) ? getOrCreateTypeFromSignature(getSignatureFromDeclaration(node)) : getTypeOfNode(node); const thisType = hasStaticModifier(node) ? @@ -35433,16 +35833,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // We wrap the "input type", if necessary, to match the decoration target. For getters this is // something like `() => inputType`, for setters it's `(value: inputType) => void` and for // methods it is just the input type. - const targetType = - isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : + const targetType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType; const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType); // We also wrap the "output type", as needed. - const returnType = - isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : + const returnType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType; @@ -35468,8 +35866,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // The `target` of an auto-accessor decorator is a `{ get, set }` object, representing the // runtime-generated getter and setter that are added to the class/prototype. The `target` of a // regular field decorator is always `undefined` as it isn't installed until it is initialized. - const targetType = - hasAccessorModifier(node) ? createClassAccessorDecoratorTargetType(thisType, valueType) : + const targetType = hasAccessorModifier(node) ? createClassAccessorDecoratorTargetType(thisType, valueType) : undefinedType; const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType); @@ -35478,8 +35875,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // "output type" in a `ClassAccessorDecoratorResult` type, which allows for // mutation of the runtime-generated getter and setter, as well as the injection of an // initializer mutator. For regular fields, we wrap the "output type" in an initializer mutator. - const returnType = - hasAccessorModifier(node) ? createClassAccessorDecoratorResultType(thisType, valueType) : + const returnType = hasAccessorModifier(node) ? createClassAccessorDecoratorResultType(thisType, valueType) : createClassFieldDecoratorInitializerMutatorType(thisType, valueType); links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType); @@ -35507,14 +35903,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*typeParameters*/ undefined, /*thisParameter*/ undefined, [targetParam], - getUnionType([targetType, voidType]) + getUnionType([targetType, voidType]), ); break; } case SyntaxKind.Parameter: { const node = parent as ParameterDeclaration; - if (!isConstructorDeclaration(node.parent) && - !((isMethodDeclaration(node.parent) || isSetAccessorDeclaration(node.parent) && isClassLike(node.parent.parent)))) { + if ( + !isConstructorDeclaration(node.parent) && + !(isMethodDeclaration(node.parent) || isSetAccessorDeclaration(node.parent) && isClassLike(node.parent.parent)) + ) { break; } @@ -35530,12 +35928,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // A parameter declaration decorator will have three arguments (see `ParameterDecorator` in // core.d.ts). - const targetType = - isConstructorDeclaration(node.parent) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent.parent)) : + const targetType = isConstructorDeclaration(node.parent) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent.parent)) : getParentTypeOfClassElement(node.parent); - const keyType = - isConstructorDeclaration(node.parent) ? undefinedType : + const keyType = isConstructorDeclaration(node.parent) ? undefinedType : getClassElementPropertyKeyType(node.parent); const indexType = getNumberLiteralType(index); @@ -35547,7 +35943,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*typeParameters*/ undefined, /*thisParameter*/ undefined, [targetParam, keyParam, indexParam], - voidType + voidType, ); break; } @@ -35568,8 +35964,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const keyType = getClassElementPropertyKeyType(node); const keyParam = createParameter("propertyKey" as __String, keyType); - const returnType = - isPropertyDeclaration(node) ? voidType : + const returnType = isPropertyDeclaration(node) ? voidType : createTypedPropertyDescriptorType(getTypeOfNode(node)); const hasPropDesc = languageVersion !== ScriptTarget.ES3 && (!isPropertyDeclaration(parent) || hasAccessorModifier(parent)); @@ -35580,7 +35975,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*typeParameters*/ undefined, /*thisParameter*/ undefined, [targetParam, keyParam, descriptorParam], - getUnionType([returnType, voidType]) + getUnionType([returnType, voidType]), ); } else { @@ -35588,7 +35983,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*typeParameters*/ undefined, /*thisParameter*/ undefined, [targetParam, keyParam], - getUnionType([returnType, voidType]) + getUnionType([returnType, voidType]), ); } break; @@ -35632,15 +36027,21 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function createPromiseReturnType(func: FunctionLikeDeclaration | ImportCall, promisedType: Type) { const promiseType = createPromiseType(promisedType); if (promiseType === unknownType) { - error(func, isImportCall(func) ? - Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : - Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + error( + func, + isImportCall(func) ? + Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option, + ); return errorType; } else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { - error(func, isImportCall(func) ? - Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : - Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + error( + func, + isImportCall(func) ? + Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option, + ); } return promiseType; @@ -35718,9 +36119,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (yieldType) reportErrorsFromWidening(func, yieldType, WideningKind.GeneratorYield); if (returnType) reportErrorsFromWidening(func, returnType, WideningKind.FunctionReturn); if (nextType) reportErrorsFromWidening(func, nextType, WideningKind.GeneratorNext); - if (returnType && isUnitType(returnType) || + if ( + returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || - nextType && isUnitType(nextType)) { + nextType && isUnitType(nextType) + ) { const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); const contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : @@ -35745,7 +36148,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(IterationTypeKind.Next, func) || unknownType, - isAsync); + isAsync, + ); } else { // From within an async function you can return either a non-promise value or a promise. Any @@ -35771,8 +36175,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined; const iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType; const iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType; - if (isTypeAssignableTo(returnType, iterableIteratorReturnType) && - isTypeAssignableTo(iterableIteratorNextType, nextType)) { + if ( + isTypeAssignableTo(returnType, iterableIteratorReturnType) && + isTypeAssignableTo(iterableIteratorNextType, nextType) + ) { if (globalType !== emptyGenericType) { return createTypeFromGenericGlobalType(globalType, [yieldType]); } @@ -35802,7 +36208,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const iterationTypes = getIterationTypesOfIterable( yieldExpressionType, isAsync ? IterationUse.AsyncYieldStar : IterationUse.YieldStar, - yieldExpression.expression); + yieldExpression.expression, + ); nextType = iterationTypes && iterationTypes.nextType; } else { @@ -35817,9 +36224,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const errorNode = node.expression || node; // A `yield*` expression effectively yields everything that its operand yields const yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? IterationUse.AsyncYieldStar : IterationUse.YieldStar, expressionType, sentType, errorNode) : expressionType; - return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken - ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + return !isAsync ? yieldedType : getAwaitedType( + yieldedType, + errorNode, + node.asteriskToken + ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member, + ); } // Return the combined not-equal type facts for all cases except those between the start and end indices. @@ -35835,14 +36246,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isExhaustiveSwitchStatement(node: SwitchStatement): boolean { const links = getNodeLinks(node); if (links.isExhaustive === undefined) { - links.isExhaustive = 0; // Indicate resolution is in process + links.isExhaustive = 0; // Indicate resolution is in process const exhaustive = computeExhaustiveSwitchStatement(node); if (links.isExhaustive === 0) { links.isExhaustive = exhaustive; } } else if (links.isExhaustive === 0) { - links.isExhaustive = false; // Resolve circularity to false + links.isExhaustive = false; // Resolve circularity to false } return links.isExhaustive; } @@ -35888,9 +36299,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const expr = returnStatement.expression; if (expr) { // Bare calls to this same function don't contribute to inference - if (expr.kind === SyntaxKind.CallExpression && + if ( + expr.kind === SyntaxKind.CallExpression && (expr as CallExpression).expression.kind === SyntaxKind.Identifier && - checkExpressionCached((expr as CallExpression).expression).symbol === func.symbol) { + checkExpressionCached((expr as CallExpression).expression).symbol === func.symbol + ) { hasReturnOfTypeNever = true; return; } @@ -35915,8 +36328,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJSConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol))) { + if ( + strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJSConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol)) + ) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined pushIfUnique(aggregatedTypes, undefinedType); } @@ -36133,7 +36548,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { errorAndMaybeSuggestAwait( operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), - diagnostic); + diagnostic, + ); return false; } return true; @@ -36183,8 +36599,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Constant || symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || symbol.flags & SymbolFlags.EnumMember || - some(symbol.declarations, isReadonlyAssignmentDeclaration) - ); + some(symbol.declarations, isReadonlyAssignmentDeclaration)); } function isAssignmentToReadonlyEntity(expr: Expression, symbol: Symbol, assignmentKind: AssignmentKind) { @@ -36194,9 +36609,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (isReadonlySymbol(symbol)) { // Allow assignments to readonly properties within constructors of the same class declaration. - if (symbol.flags & SymbolFlags.Property && + if ( + symbol.flags & SymbolFlags.Property && isAccessExpression(expr) && - expr.expression.kind === SyntaxKind.ThisKeyword) { + expr.expression.kind === SyntaxKind.ThisKeyword + ) { // Look for if this is the constructor for the class that `symbol` is a property of. const ctor = getContainingFunction(expr); if (!(ctor && (ctor.kind === SyntaxKind.Constructor || isJSConstructor(ctor)))) { @@ -36208,8 +36625,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isLocalParameterProperty = ctor === symbol.valueDeclaration.parent; const isLocalThisPropertyAssignment = isAssignmentDeclaration && symbol.parent?.valueDeclaration === ctor.parent; const isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration && symbol.parent?.valueDeclaration === ctor; - const isWriteableSymbol = - isLocalPropertyDeclaration + const isWriteableSymbol = isLocalPropertyDeclaration || isLocalParameterProperty || isLocalThisPropertyAssignment || isLocalThisPropertyAssignmentConstructorFunction; @@ -36269,9 +36685,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkDeleteExpressionMustBeOptional(expr: AccessExpression, symbol: Symbol) { const type = getTypeOfSymbol(symbol); - if (strictNullChecks && + if ( + strictNullChecks && !(type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Never)) && - !(exactOptionalPropertyTypes ? symbol.flags & SymbolFlags.Optional : getTypeFacts(type) & TypeFacts.IsUndefined)) { + !(exactOptionalPropertyTypes ? symbol.flags & SymbolFlags.Optional : getTypeFacts(type) & TypeFacts.IsUndefined) + ) { error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_optional); } } @@ -36316,7 +36734,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (sourceFile.impliedNodeFormat === ModuleKind.CommonJS) { span ??= getSpanOfTokenAtPosition(sourceFile, node.pos); diagnostics.add( - createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level) + createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level), ); hasError = true; break; @@ -36395,7 +36813,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (node.operator === SyntaxKind.MinusToken) { return getFreshTypeOfLiteralType(getBigIntLiteralType({ negative: true, - base10Value: parsePseudoBigInt((node.operand as BigIntLiteral).text) + base10Value: parsePseudoBigInt((node.operand as BigIntLiteral).text), })); } } @@ -36422,14 +36840,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { booleanType; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: - const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression( node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access); + Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access, + ); } return getUnaryResultType(operandType); } @@ -36444,13 +36862,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const ok = checkArithmeticOperandType( node.operand, checkNonNullType(operandType, node.operand), - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type, + ); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression( node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access, - Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access); + Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access, + ); } return getUnaryResultType(operandType); } @@ -36533,8 +36953,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, TypeFlags.Primitive)) { + if ( + !isTypeAny(leftType) && + allTypesAssignableToKind(leftType, TypeFlags.Primitive) + ) { error(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -36646,7 +37068,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). const possiblyOutOfBoundsType = checkIteratedTypeOrElementType(IterationUse.Destructuring | IterationUse.PossiblyOutOfBounds, sourceType, undefinedType, node) || errorType; - let inBoundsType: Type | undefined = compilerOptions.noUncheckedIndexedAccess ? undefined: possiblyOutOfBoundsType; + let inBoundsType: Type | undefined = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType; for (let i = 0; i < elements.length; i++) { let type = possiblyOutOfBoundsType; if (node.elements[i].kind === SyntaxKind.SpreadElement) { @@ -36657,8 +37079,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return sourceType; } - function checkArrayLiteralDestructuringElementAssignment(node: ArrayLiteralExpression, sourceType: Type, - elementIndex: number, elementType: Type, checkMode?: CheckMode) { + function checkArrayLiteralDestructuringElementAssignment(node: ArrayLiteralExpression, sourceType: Type, elementIndex: number, elementType: Type, checkMode?: CheckMode) { const elements = node.elements; const element = elements[elementIndex]; if (element.kind !== SyntaxKind.OmittedExpression) { @@ -36702,8 +37123,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && - !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & TypeFacts.IsUndefined)) { + if ( + strictNullChecks && + !(getTypeFacts(checkExpression(prop.objectAssignmentInitializer)) & TypeFacts.IsUndefined) + ) { sourceType = getTypeWithFacts(sourceType, TypeFacts.NEUndefined); } checkBinaryLikeExpression(prop.name, prop.equalsToken!, prop.objectAssignmentInitializer, checkMode); @@ -36791,7 +37214,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } return isSideEffectFree((node as BinaryExpression).left) && - isSideEffectFree((node as BinaryExpression).right); + isSideEffectFree((node as BinaryExpression).right); case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: @@ -36999,7 +37422,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { leftType: Type, rightType: Type, checkMode?: CheckMode, - errorNode?: Node + errorNode?: Node, ): Type { const operator = operatorToken.kind; switch (operator) { @@ -37035,9 +37458,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let suggestedOperator: PunctuationSyntaxKind | undefined; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion - if ((leftType.flags & TypeFlags.BooleanLike) && + if ( + (leftType.flags & TypeFlags.BooleanLike) && (rightType.flags & TypeFlags.BooleanLike) && - (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined + ) { error(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator)); return numberType; } @@ -37047,7 +37472,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type, /*isAwaitValid*/ true); let resultType: Type; // If both are any or unknown, allow operation; assume it will resolve to number - if ((isTypeAssignableToKind(leftType, TypeFlags.AnyOrUnknown) && isTypeAssignableToKind(rightType, TypeFlags.AnyOrUnknown)) || + if ( + (isTypeAssignableToKind(leftType, TypeFlags.AnyOrUnknown) && isTypeAssignableToKind(rightType, TypeFlags.AnyOrUnknown)) || // Or, if neither could be bigint, implicit coercion results in a number result !(maybeTypeOfKind(leftType, TypeFlags.BigIntLike) || maybeTypeOfKind(rightType, TypeFlags.BigIntLike)) ) { @@ -37122,7 +37548,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const closeEnoughKind = TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.StringLike | TypeFlags.AnyOrUnknown; reportOperatorError((left, right) => isTypeAssignableToKind(left, closeEnoughKind) && - isTypeAssignableToKind(right, closeEnoughKind)); + isTypeAssignableToKind(right, closeEnoughKind) + ); return anyType; } @@ -37206,12 +37633,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : AssignmentDeclarationKind.None; checkAssignmentDeclaration(declKind, rightType); if (isAssignmentDeclaration(declKind)) { - if (!(rightType.flags & TypeFlags.Object) || + if ( + !(rightType.flags & TypeFlags.Object) || declKind !== AssignmentDeclarationKind.ModuleExports && - declKind !== AssignmentDeclarationKind.Prototype && - !isEmptyObjectType(rightType) && - !isFunctionObjectType(rightType as ObjectType) && - !(getObjectFlags(rightType) & ObjectFlags.Class)) { + declKind !== AssignmentDeclarationKind.Prototype && + !isEmptyObjectType(rightType) && + !isFunctionObjectType(rightType as ObjectType) && + !(getObjectFlags(rightType) & ObjectFlags.Class) + ) { // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete checkAssignmentOperator(rightType); } @@ -37270,8 +37699,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator: PunctuationSyntaxKind): boolean { - const offendingSymbolOperand = - maybeTypeOfKindConsideringBaseConstraint(leftType, TypeFlags.ESSymbolLike) ? left : + const offendingSymbolOperand = maybeTypeOfKindConsideringBaseConstraint(leftType, TypeFlags.ESSymbolLike) ? left : maybeTypeOfKindConsideringBaseConstraint(rightType, TypeFlags.ESSymbolLike) ? right : undefined; @@ -37319,11 +37747,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non-compound operation to be assignable to the type of VarExpr. - if (checkReferenceExpression(left, - Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, - Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access) - ) { - + if (checkReferenceExpression(left, Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)) { let headMessage: DiagnosticMessage | undefined; if (exactOptionalPropertyTypes && isPropertyAccessExpression(left) && maybeTypeOfKind(valueType, TypeFlags.Undefined)) { const target = getTypeOfPropertyOfType(getTypeOfExpression(left.expression), left.name.escapedText); @@ -37405,7 +37829,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { errNode, maybeMissingAwait, Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap, - leftStr, rightStr); + leftStr, + rightStr, + ); default: return undefined; } @@ -37415,14 +37841,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isLeftNaN = isGlobalNaN(skipParentheses(left)); const isRightNaN = isGlobalNaN(skipParentheses(right)); if (isLeftNaN || isRightNaN) { - const err = error(errorNode, Diagnostics.This_condition_will_always_return_0, - tokenToString(operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.EqualsEqualsToken ? SyntaxKind.FalseKeyword : SyntaxKind.TrueKeyword)); + const err = error(errorNode, Diagnostics.This_condition_will_always_return_0, tokenToString(operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.EqualsEqualsToken ? SyntaxKind.FalseKeyword : SyntaxKind.TrueKeyword)); if (isLeftNaN && isRightNaN) return; const operatorString = operator === SyntaxKind.ExclamationEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsToken ? tokenToString(SyntaxKind.ExclamationToken) : ""; const location = isLeftNaN ? right : left; const expression = skipParentheses(location); - addRelatedInfo(err, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, - `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`)); + addRelatedInfo(err, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`)); } } @@ -37444,7 +37868,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { effectiveLeft = leftBase; effectiveRight = rightBase; } - return [ effectiveLeft, effectiveRight ]; + return [effectiveLeft, effectiveRight]; } function checkYieldExpression(node: YieldExpression): Type { @@ -37615,7 +38039,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkDeclarationInitializer( declaration: HasExpressionInitializer, checkMode: CheckMode, - contextualType?: Type | undefined + contextualType?: Type | undefined, ) { const initializer = getEffectiveInitializer(declaration)!; if (isInJSFile(declaration)) { @@ -37629,7 +38053,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, checkMode || CheckMode.Normal) : checkExpressionCached(initializer, checkMode)); return isParameter(declaration) && declaration.name.kind === SyntaxKind.ArrayBindingPattern && - isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? + isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; } @@ -37864,7 +38288,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { while (len > 1 && (baseName as string).charCodeAt(len - 1) >= CharacterCodes._0 && (baseName as string).charCodeAt(len - 1) <= CharacterCodes._9) len--; const s = (baseName as string).slice(0, len); for (let index = 1; true; index++) { - const augmentedName = (s + index as __String); + const augmentedName = s + index as __String; if (!hasTypeParameterByName(typeParameters, augmentedName)) { return augmentedName; } @@ -37979,8 +38403,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - const ok = - (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent as PropertyAccessExpression).expression === node) || + const ok = (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent as PropertyAccessExpression).expression === node) || (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent as ElementAccessExpression).expression === node) || ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node as Identifier) || (node.parent.kind === SyntaxKind.TypeQuery && (node.parent as TypeQueryNode).exprName === node)) || @@ -38051,7 +38474,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkGrammarBigIntLiteral(node as BigIntLiteral); return getFreshTypeOfLiteralType(getBigIntLiteralType({ negative: false, - base10Value: parsePseudoBigInt((node as BigIntLiteral).text) + base10Value: parsePseudoBigInt((node as BigIntLiteral).text), })); case SyntaxKind.TrueKeyword: return trueType; @@ -38257,19 +38680,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else { if (typePredicate.type) { const leadingError = () => chainDiagnosticMessages(/*details*/ undefined, Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); - checkTypeAssignableTo(typePredicate.type, - getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), - node.type, - /*headMessage*/ undefined, - leadingError); + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } } else if (parameterName) { let hasReportedError = false; for (const { name } of parent.parameters) { - if (isBindingPattern(name) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + if ( + isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName) + ) { hasReportedError = true; break; } @@ -38300,7 +38721,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkIfTypePredicateVariableIsDeclaredInBindingPattern( pattern: BindingPattern, predicateVariableNode: Node, - predicateVariableName: string) { + predicateVariableName: string, + ) { for (const element of pattern.elements) { if (isOmittedExpression(element)) { continue; @@ -38308,16 +38730,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const name = element.name; if (name.kind === SyntaxKind.Identifier && name.escapedText === predicateVariableName) { - error(predicateVariableNode, - Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, - predicateVariableName); + error(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } else if (name.kind === SyntaxKind.ArrayBindingPattern || name.kind === SyntaxKind.ObjectBindingPattern) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern( - name, - predicateVariableNode, - predicateVariableName)) { + if ( + checkIfTypePredicateVariableIsDeclaredInBindingPattern( + name, + predicateVariableNode, + predicateVariableName, + ) + ) { return true; } } @@ -38330,9 +38753,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.ConstructorType || + else if ( + node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.ConstructorType || node.kind === SyntaxKind.CallSignature || node.kind === SyntaxKind.Constructor || - node.kind === SyntaxKind.ConstructSignature) { + node.kind === SyntaxKind.ConstructSignature + ) { checkGrammarFunctionLikeDeclaration(node as FunctionLikeDeclaration); } @@ -38447,8 +38872,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const isPrivate = isPrivateIdentifier(name); const privateStaticFlags = isPrivate && isStaticMember ? DeclarationMeaning.PrivateStatic : 0; - const names = - isPrivate ? privateIdentifiers : + const names = isPrivate ? privateIdentifiers : isStaticMember ? staticNames : instanceNames; @@ -38585,7 +39009,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration const indexSymbol = getIndexSymbol(getSymbolOfDeclaration(node)!); if (indexSymbol?.declarations) { - const indexSignatureMap = new Map(); + const indexSignatureMap = new Map(); for (const declaration of (indexSymbol.declarations as IndexSignatureDeclaration[])) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { forEachType(getTypeFromTypeNode(declaration.parameters[0].type), type => { @@ -38731,10 +39155,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - const superCallShouldBeRootLevel = - !emitStandardClassFields && + const superCallShouldBeRootLevel = !emitStandardClassFields && (some((node.parent as ClassDeclaration).members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - some(node.parameters, p => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier))); + some(node.parameters, p => hasSyntacticModifier(p, ModifierFlags.ParameterPropertyModifier))); if (superCallShouldBeRootLevel) { // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional @@ -38830,8 +39253,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); error(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); } - if (((getterFlags & ModifierFlags.Protected) && !(setterFlags & (ModifierFlags.Protected | ModifierFlags.Private))) || - ((getterFlags & ModifierFlags.Private) && !(setterFlags & ModifierFlags.Private))) { + if ( + ((getterFlags & ModifierFlags.Protected) && !(setterFlags & (ModifierFlags.Protected | ModifierFlags.Private))) || + ((getterFlags & ModifierFlags.Private) && !(setterFlags & ModifierFlags.Private)) + ) { error(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); error(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter); } @@ -38856,8 +39281,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function getEffectiveTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments | NodeWithTypeArguments, typeParameters: readonly TypeParameter[]): Type[] { - return fillMissingTypeArguments(map(node.typeArguments!, getTypeFromTypeNode), typeParameters, - getMinTypeArgumentCount(typeParameters), isInJSFile(node)); + return fillMissingTypeArguments(map(node.typeArguments!, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(node)); } function checkTypeArgumentConstraints(node: TypeReferenceNode | ExpressionWithTypeArguments | NodeWithTypeArguments, typeParameters: readonly TypeParameter[]): boolean { @@ -38875,7 +39299,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { typeArguments[i], instantiateType(constraint, mapper), node.typeArguments![i], - Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + Diagnostics.Type_0_does_not_satisfy_the_constraint_1, + ); } } return result; @@ -38930,7 +39355,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { addDeprecatedSuggestion( getDeprecatedSuggestionNode(node), symbol.declarations!, - symbol.escapedName as string + symbol.escapedName as string, ); } } @@ -39018,8 +39443,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const objectType = (type as IndexedAccessType).objectType; const indexType = (type as IndexedAccessType).indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType, IndexFlags.None))) { - if (accessNode.kind === SyntaxKind.ElementAccessExpression && isAssignmentTarget(accessNode) && - getObjectFlags(objectType) & ObjectFlags.Mapped && getMappedTypeModifiers(objectType as MappedType) & MappedTypeModifiers.IncludeReadonly) { + if ( + accessNode.kind === SyntaxKind.ElementAccessExpression && isAssignmentTarget(accessNode) && + getObjectFlags(objectType) & ObjectFlags.Mapped && getMappedTypeModifiers(objectType as MappedType) & MappedTypeModifiers.IncludeReadonly + ) { error(accessNode, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } return type; @@ -39164,10 +39591,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== SyntaxKind.InterfaceDeclaration && + if ( + n.parent.kind !== SyntaxKind.InterfaceDeclaration && n.parent.kind !== SyntaxKind.ClassDeclaration && n.parent.kind !== SyntaxKind.ClassExpression && - n.flags & NodeFlags.Ambient) { + n.flags & NodeFlags.Ambient + ) { const container = getEnclosingContainer(n); if ((container && container.flags & NodeFlags.ExportContext) && !(flags & ModifierFlags.Ambient) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient export context, which means it is automatically exported @@ -39263,17 +39692,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (subsequentNode.kind === node.kind) { const errorNode: Node = (subsequentNode as FunctionLikeDeclaration).name || subsequentNode; const subsequentName = (subsequentNode as FunctionLikeDeclaration).name; - if (node.name && subsequentName && ( - // both are private identifiers - isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || - // Both are computed property names - isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) && isTypeIdenticalTo(checkComputedPropertyName(node.name), checkComputedPropertyName(subsequentName)) || - // Both are literal property names that are the same. - isPropertyNameLiteral(node.name) && isPropertyNameLiteral(subsequentName) && - getEscapedTextOfIdentifierOrLiteral(node.name) === getEscapedTextOfIdentifierOrLiteral(subsequentName) - )) { - const reportError = - (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && + if ( + node.name && subsequentName && ( + // both are private identifiers + isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || + // Both are computed property names + isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) && isTypeIdenticalTo(checkComputedPropertyName(node.name), checkComputedPropertyName(subsequentName)) || + // Both are literal property names that are the same. + isPropertyNameLiteral(node.name) && isPropertyNameLiteral(subsequentName) && + getEscapedTextOfIdentifierOrLiteral(node.name) === getEscapedTextOfIdentifierOrLiteral(subsequentName) + ) + ) { + const reportError = (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && isStatic(node) !== isStatic(subsequentNode); // we can get here in two cases // 1. mixed static and instance class members @@ -39399,22 +39829,24 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { forEach(declarations, declaration => { const diagnostic = declaration.kind === SyntaxKind.ClassDeclaration - ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 - : declaration.kind === SyntaxKind.FunctionDeclaration - ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient - : undefined; + ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 + : declaration.kind === SyntaxKind.FunctionDeclaration + ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient + : undefined; if (diagnostic) { addRelatedInfo( error(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)), - ...relatedDiagnostics + ...relatedDiagnostics, ); } }); } // Abstract methods can't have an implementation -- in particular, they don't need one. - if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !hasSyntacticModifier(lastSeenNonAmbientDeclaration, ModifierFlags.Abstract) && !lastSeenNonAmbientDeclaration.questionToken) { + if ( + lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !hasSyntacticModifier(lastSeenNonAmbientDeclaration, ModifierFlags.Abstract) && !lastSeenNonAmbientDeclaration.questionToken + ) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -39434,7 +39866,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { : signature.declaration; addRelatedInfo( error(errorNode, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), - createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here) + createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here), ); break; } @@ -39555,12 +39987,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.FunctionDeclaration: case SyntaxKind.ImportSpecifier: // https://github.com/Microsoft/TypeScript/pull/7591 case SyntaxKind.Identifier: // https://github.com/microsoft/TypeScript/issues/36098 - // Identifiers are used as declarations of assignment declarations whose parents may be - // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` - // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it) - // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;` - // all of which are pretty much always values, or at least imply a value meaning. - // It may be apprpriate to treat these as aliases in the future. + // Identifiers are used as declarations of assignment declarations whose parents may be + // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});` + // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it) + // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;` + // all of which are pretty much always values, or at least imply a value meaning. + // It may be apprpriate to treat these as aliases in the future. return DeclarationSpaces.ExportValue; case SyntaxKind.MethodSignature: case SyntaxKind.PropertySignature: @@ -39581,7 +40013,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * @param type The type of the promise. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. */ - function getPromisedTypeOfPromise(type: Type, errorNode?: Node, thisTypeForErrorOut?: { value?: Type }): Type | undefined { + function getPromisedTypeOfPromise(type: Type, errorNode?: Node, thisTypeForErrorOut?: { value?: Type; }): Type | undefined { // // { // type // then( // thenFunction @@ -39724,9 +40156,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const baseConstraint = getBaseConstraintOfType(type); // We only need `Awaited` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, // or is promise-like. - if (baseConstraint ? - baseConstraint.flags & TypeFlags.AnyOrUnknown || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : - maybeTypeOfKind(type, TypeFlags.TypeVariable)) { + if ( + baseConstraint ? + baseConstraint.flags & TypeFlags.AnyOrUnknown || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : + maybeTypeOfKind(type, TypeFlags.TypeVariable) + ) { return true; } } @@ -39825,7 +40259,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return typeAsAwaitable.awaitedTypeOfType = type; } - const thisTypeForErrorOut: { value: Type | undefined } = { value: undefined }; + const thisTypeForErrorOut: { value: Type | undefined; } = { value: undefined }; const promisedType = getPromisedTypeOfPromise(type, /*errorNode*/ undefined, thisTypeForErrorOut); if (promisedType) { if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { @@ -40006,9 +40440,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); const collidingSymbol = getSymbol(node.locals!, rootName.escapedText, SymbolFlags.Value); if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, - idText(rootName), - entityNameToString(promiseConstructorName)); + error(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, idText(rootName), entityNameToString(promiseConstructorName)); return; } } @@ -40081,7 +40513,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { returnType: Type, typePredicate?: TypePredicate, minArgumentCount: number = parameters.length, - flags: SignatureFlags = SignatureFlags.None + flags: SignatureFlags = SignatureFlags.None, ) { const decl = factory.createFunctionTypeNode(/*typeParameters*/ undefined, emptyArray, factory.createKeywordTypeNode(SyntaxKind.AnyKeyword)); return createSignature(decl, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags); @@ -40097,7 +40529,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { returnType: Type, typePredicate?: TypePredicate, minArgumentCount?: number, - flags?: SignatureFlags + flags?: SignatureFlags, ) { const signature = createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags); return getOrCreateTypeFromSignature(signature); @@ -40127,17 +40559,21 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const meaning = (typeName.kind === SyntaxKind.Identifier ? SymbolFlags.Type : SymbolFlags.Namespace) | SymbolFlags.Alias; const rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (rootSymbol && rootSymbol.flags & SymbolFlags.Alias) { - if (canCollectSymbolAliasAccessabilityData + if ( + canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) - && !getTypeOnlyAliasDeclaration(rootSymbol)) { + && !getTypeOnlyAliasDeclaration(rootSymbol) + ) { markAliasSymbolAsReferenced(rootSymbol); } - else if (forDecoratorMetadata + else if ( + forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= ModuleKind.ES2015 && !symbolIsValue(rootSymbol) - && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { + && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration) + ) { const diag = error(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration); if (aliasDeclaration) { @@ -40206,9 +40642,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Keep this in sync with serializeUnionOrIntersectionType // Verify if they refer to same entity and is identifier // return undefined if they dont match because we would emit object - if (!isIdentifier(commonEntityName) || + if ( + !isIdentifier(commonEntityName) || !isIdentifier(individualEntityName) || - commonEntityName.escapedText !== individualEntityName.escapedText) { + commonEntityName.escapedText !== individualEntityName.escapedText + ) { return undefined; } } @@ -40464,7 +40902,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. const firstDeclaration = localSymbol.declarations?.find( // Get first non javascript function declaration - declaration => declaration.kind === node.kind && !(declaration.flags & NodeFlags.JavaScriptFile)); + declaration => declaration.kind === node.kind && !(declaration.flags & NodeFlags.JavaScriptFile), + ); // Only type check the symbol once if (node === firstDeclaration) { @@ -40526,11 +40965,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - type PotentiallyUnusedIdentifier = - | SourceFile | ModuleDeclaration | ClassLikeDeclaration | InterfaceDeclaration - | Block | CaseBlock | ForStatement | ForInStatement | ForOfStatement - | Exclude | TypeAliasDeclaration - | InferTypeNode; + type PotentiallyUnusedIdentifier = SourceFile | ModuleDeclaration | ClassLikeDeclaration | InterfaceDeclaration | Block | CaseBlock | ForStatement | ForInStatement | ForOfStatement | Exclude | TypeAliasDeclaration | InferTypeNode; function checkUnusedIdentifiers(potentiallyUnusedIdentifiers: readonly PotentiallyUnusedIdentifier[], addDiagnostic: AddUnusedDiagnostic) { for (const node of potentiallyUnusedIdentifiers) { @@ -40601,9 +41036,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; } const symbol = getSymbolOfDeclaration(member); - if (!symbol.isReferenced + if ( + !symbol.isReferenced && (hasEffectiveModifier(member, ModifierFlags.Private) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) - && !(member.flags & NodeFlags.Ambient)) { + && !(member.flags & NodeFlags.Ambient) + ) { addDiagnostic(member, UnusedKind.Local, createDiagnosticForNode(member.name!, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; @@ -40655,7 +41092,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Include the `<>` in the error message : rangeOfTypeParameters(sourceFile, parent.typeParameters!); const only = parent.typeParameters!.length === 1; - //TODO: following line is possible reason for bug #41974, unusedTypeParameters_TemplateTag + // TODO: following line is possible reason for bug #41974, unusedTypeParameters_TemplateTag const messageAndArg: DiagnosticAndArguments = only ? [Diagnostics._0_is_declared_but_its_value_is_never_read, name] : [Diagnostics.All_type_parameters_are_unused]; @@ -40663,7 +41100,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } else { - //TODO: following line is possible reason for bug #41974, unusedTypeParameters_TemplateTag + // TODO: following line is possible reason for bug #41974, unusedTypeParameters_TemplateTag addDiagnostic(typeParameter, UnusedKind.Parameter, createDiagnosticForNode(typeParameter, Diagnostics._0_is_declared_but_its_value_is_never_read, name)); } } @@ -40764,9 +41201,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { (importClause.namedBindings.kind === SyntaxKind.NamespaceImport ? 1 : importClause.namedBindings.elements.length) : 0); if (nDeclarations === unuseds.length) { - addDiagnostic(importDecl, UnusedKind.Local, unuseds.length === 1 - ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name!)) - : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused)); + addDiagnostic( + importDecl, + UnusedKind.Local, + unuseds.length === 1 + ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name!)) + : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused), + ); } else { for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name!), addDiagnostic); @@ -40779,9 +41220,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - addDiagnostic(bindingPattern, kind, bindingElements.length === 1 - ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) - : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused)); + addDiagnostic( + bindingPattern, + kind, + bindingElements.length === 1 + ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) + : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused), + ); } } else { @@ -40792,9 +41237,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { }); unusedVariables.forEach(([declarationList, declarations]) => { if (declarationList.declarations.length === declarations.length) { - addDiagnostic(declarationList, UnusedKind.Local, declarations.length === 1 - ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) - : createDiagnosticForNode(declarationList.parent.kind === SyntaxKind.VariableStatement ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused)); + addDiagnostic( + declarationList, + UnusedKind.Local, + declarations.length === 1 + ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) + : createDiagnosticForNode(declarationList.parent.kind === SyntaxKind.VariableStatement ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused), + ); } else { for (const decl of declarations) { @@ -40814,7 +41263,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // entire parameter does not have type annotation, suggest adding an annotation addRelatedInfo( diagnostic, - createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName)) + createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName)), ); } diagnostics.add(diagnostic); @@ -40883,13 +41332,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } - if (node.kind === SyntaxKind.PropertyDeclaration || + if ( + node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature || node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor || - node.kind === SyntaxKind.PropertyAssignment) { + node.kind === SyntaxKind.PropertyAssignment + ) { // it is ok to have member named '_super', '_this', `Promise`, etc. - member access is always qualified return false; } @@ -40967,8 +41418,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const parent = getDeclarationContainer(node); if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent as SourceFile)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords - errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, - declarationNameToString(name), declarationNameToString(name)); + errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name)); } } @@ -40986,14 +41436,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const parent = getDeclarationContainer(node); if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent as SourceFile) && parent.flags & NodeFlags.HasAsyncFunctions) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. - errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, - declarationNameToString(name), declarationNameToString(name)); + errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name)); } } function recordPotentialCollisionWithWeakMapSetInGeneratedCode(node: Node, name: Identifier): void { - if (languageVersion <= ScriptTarget.ES2021 - && (needCollisionCheckForIdentifier(node, name, "WeakMap") || needCollisionCheckForIdentifier(node, name, "WeakSet"))) { + if ( + languageVersion <= ScriptTarget.ES2021 + && (needCollisionCheckForIdentifier(node, name, "WeakMap") || needCollisionCheckForIdentifier(node, name, "WeakSet")) + ) { potentialWeakMapSetCollisions.push(node); } } @@ -41007,8 +41458,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function recordPotentialCollisionWithReflectInGeneratedCode(node: Node, name: Identifier | undefined): void { - if (name && languageVersion >= ScriptTarget.ES2015 && languageVersion <= ScriptTarget.ES2021 - && needCollisionCheckForIdentifier(node, name, "Reflect")) { + if ( + name && languageVersion >= ScriptTarget.ES2015 && languageVersion <= ScriptTarget.ES2021 + && needCollisionCheckForIdentifier(node, name, "Reflect") + ) { potentialReflectCollisions.push(node); } } @@ -41038,9 +41491,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (hasCollision) { Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name), "The target of a Reflect collision check should be an identifier"); - errorSkippedOn("noEmit", node, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, - declarationNameToString(node.name), - "Reflect"); + errorSkippedOn("noEmit", node, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, declarationNameToString(node.name), "Reflect"); } } @@ -41099,20 +41550,20 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (symbol.flags & SymbolFlags.FunctionScopedVariable) { if (!isIdentifier(node.name)) return Debug.fail(); const localDeclarationSymbol = resolveName(node, node.name.escapedText, SymbolFlags.Variable, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); - if (localDeclarationSymbol && + if ( + localDeclarationSymbol && localDeclarationSymbol !== symbol && - localDeclarationSymbol.flags & SymbolFlags.BlockScopedVariable) { + localDeclarationSymbol.flags & SymbolFlags.BlockScopedVariable + ) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & NodeFlags.BlockScoped) { const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList)!; - const container = - varDeclList.parent.kind === SyntaxKind.VariableStatement && varDeclList.parent.parent - ? varDeclList.parent.parent - : undefined; + const container = varDeclList.parent.kind === SyntaxKind.VariableStatement && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) - const namesShareScope = - container && + const namesShareScope = container && (container.kind === SyntaxKind.Block && isFunctionLike(container.parent) || container.kind === SyntaxKind.ModuleBlock || container.kind === SyntaxKind.ModuleDeclaration || @@ -41158,10 +41609,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isBindingElement(node)) { if ( - node.propertyName && - isIdentifier(node.name) && - isParameterDeclaration(node) && - nodeIsMissing((getContainingFunction(node) as FunctionLikeDeclaration).body)) { + node.propertyName && + isIdentifier(node.name) && + isParameterDeclaration(node) && + nodeIsMissing((getContainingFunction(node) as FunctionLikeDeclaration).body) + ) { // type F = ({a: string}) => void; // ^^^^^^ // variable renaming in function type notation is confusing, @@ -41289,9 +41741,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // initializer is consistent with type associated with the node const declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (!isErrorType(type) && !isErrorType(declarationType) && + if ( + !isErrorType(type) && !isErrorType(declarationType) && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & SymbolFlags.Assignment)) { + !(symbol.flags & SymbolFlags.Assignment) + ) { errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType); } if (hasOnlyExpressionInitializer(node) && node.initializer) { @@ -41322,18 +41776,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { message, declName, typeToString(firstType), - typeToString(nextType) + typeToString(nextType), ); if (firstDeclaration) { - addRelatedInfo(err, - createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName) - ); + addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName)); } } function areDeclarationFlagsIdentical(left: Declaration, right: Declaration) { - if ((left.kind === SyntaxKind.Parameter && right.kind === SyntaxKind.VariableDeclaration) || - (left.kind === SyntaxKind.VariableDeclaration && right.kind === SyntaxKind.Parameter)) { + if ( + (left.kind === SyntaxKind.Parameter && right.kind === SyntaxKind.VariableDeclaration) || + (left.kind === SyntaxKind.VariableDeclaration && right.kind === SyntaxKind.Parameter) + ) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -41455,7 +41909,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { location, /*maybeMissingAwait*/ true, Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined, - getTypeNameForErrorDisplay(type)); + getTypeNameForErrorDisplay(type), + ); } else { error(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead); @@ -41477,8 +41932,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let testedExpression = testedNode.parent; let childExpression = childNode.parent; while (testedExpression && childExpression) { - if (isIdentifier(testedExpression) && isIdentifier(childExpression) || - testedExpression.kind === SyntaxKind.ThisKeyword && childExpression.kind === SyntaxKind.ThisKeyword) { + if ( + isIdentifier(testedExpression) && isIdentifier(childExpression) || + testedExpression.kind === SyntaxKind.ThisKeyword && childExpression.kind === SyntaxKind.ThisKeyword + ) { return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); } else if (isPropertyAccessExpression(testedExpression) && isPropertyAccessExpression(childExpression)) { @@ -41618,7 +42075,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkReferenceExpression( varExpr, Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access, - Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access); + Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access, + ); // iteratedType will be undefined if the rightType was missing properties/signatures // required to get its iteratedType (like [Symbol.iterator] or next). This may be @@ -41671,7 +42129,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkReferenceExpression( varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access, - Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access); + Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access, + ); } } @@ -41723,8 +42182,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined); if (checkAssignability) { if (iterationTypes) { - const diagnostic = - use & IterationUse.ForOfFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 : + const diagnostic = use & IterationUse.ForOfFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 : use & IterationUse.SpreadFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 : use & IterationUse.DestructuringFlag ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 : use & IterationUse.YieldStarFlag ? Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 : @@ -41790,7 +42248,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, - typeToString(arrayType)); + typeToString(arrayType), + ); } return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined; } @@ -41868,9 +42327,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // more frequently created (i.e. `Iterator`). Iteration types // are also cached on the type they are requested for, so we shouldn't need to maintain // the cache for less-frequently used types. - if (yieldType.flags & TypeFlags.Intrinsic && + if ( + yieldType.flags & TypeFlags.Intrinsic && returnType.flags & (TypeFlags.Any | TypeFlags.Never | TypeFlags.Unknown | TypeFlags.Void | TypeFlags.Undefined) && - nextType.flags & (TypeFlags.Any | TypeFlags.Never | TypeFlags.Unknown | TypeFlags.Void | TypeFlags.Undefined)) { + nextType.flags & (TypeFlags.Any | TypeFlags.Never | TypeFlags.Unknown | TypeFlags.Void | TypeFlags.Undefined) + ) { const id = getTypeListId([yieldType, returnType, nextType]); let iterationTypes = iterationTypesCache.get(id); if (!iterationTypes) { @@ -41908,7 +42369,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return createIterationTypes( yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), - nextTypes && getIntersectionType(nextTypes)); + nextTypes && getIntersectionType(nextTypes), + ); } return noIterationTypes; } @@ -41948,7 +42410,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (!(type.flags & TypeFlags.Union)) { - const errorOutputContainer: { errors: Diagnostic[] | undefined } | undefined = errorNode ? { errors: undefined } : undefined; + const errorOutputContainer: { errors: Diagnostic[] | undefined; } | undefined = errorNode ? { errors: undefined } : undefined; const iterationTypes = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes === noIterationTypes) { if (errorNode) { @@ -41973,7 +42435,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let allIterationTypes: IterationTypes[] | undefined; for (const constituent of (type as UnionType).types) { - const errorOutputContainer: { errors: Diagnostic[] | undefined } | undefined = errorNode ? { errors: undefined } : undefined; + const errorOutputContainer: { errors: Diagnostic[] | undefined; } | undefined = errorNode ? { errors: undefined } : undefined; const iterationTypes = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer); if (iterationTypes === noIterationTypes) { if (errorNode) { @@ -42010,7 +42472,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return createIterationTypes( getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, - nextType); + nextType, + ); } /** @@ -42023,7 +42486,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableWorker(type: Type, use: IterationUse, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined } | undefined) { + function getIterationTypesOfIterableWorker(type: Type, use: IterationUse, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined; } | undefined) { if (isTypeAny(type)) { return anyIterationTypes; } @@ -42033,8 +42496,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let noCache = false; if (use & IterationUse.AllowsAsyncIterablesFlag) { - const iterationTypes = - getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || + const iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver); if (iterationTypes) { if (iterationTypes === noIterationTypes && errorNode) { @@ -42050,8 +42512,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (use & IterationUse.AllowsSyncIterablesFlag) { - let iterationTypes = - getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || + let iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver); if (iterationTypes) { if (iterationTypes === noIterationTypes && errorNode) { @@ -42108,8 +42569,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function getIterationTypesOfGlobalIterableType(globalType: Type, resolver: IterationTypesResolver) { - const globalIterationTypes = - getIterationTypesOfIterableCached(globalType, resolver) || + const globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; } @@ -42132,8 +42592,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // - `Iterable` or `AsyncIterable` // - `IterableIterator` or `AsyncIterableIterator` let globalType: Type; - if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) || - isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) { + if ( + isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false)) + ) { const [yieldType] = getTypeArguments(type as GenericType); // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins. @@ -42168,7 +42630,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterable` instead. */ - function getIterationTypesOfIterableSlow(type: Type, resolver: IterationTypesResolver, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined } | undefined, noCache: boolean) { + function getIterationTypesOfIterableSlow(type: Type, resolver: IterationTypesResolver, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined; } | undefined, noCache: boolean) { const method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName)); const methodType = method && !(method.flags & SymbolFlags.Optional) ? getTypeOfSymbol(method) : undefined; if (isTypeAny(methodType)) { @@ -42198,8 +42660,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType(/*reportErrors*/ false) !== emptyGenericType && - isTypeAssignableTo(type, getGlobalAsyncIterableType(/*reportErrors*/ false) - )); + isTypeAssignableTo(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) + ); return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } @@ -42209,7 +42671,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, `undefined` is returned. */ - function getIterationTypesOfIterator(type: Type, resolver: IterationTypesResolver, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined } | undefined) { + function getIterationTypesOfIterator(type: Type, resolver: IterationTypesResolver, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined; } | undefined) { return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, /*noCache*/ false); } @@ -42222,13 +42684,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIteratorWorker(type: Type, resolver: IterationTypesResolver, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined } | undefined, noCache: boolean) { + function getIterationTypesOfIteratorWorker(type: Type, resolver: IterationTypesResolver, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined; } | undefined, noCache: boolean) { if (isTypeAny(type)) { return anyIterationTypes; } - let iterationTypes = - getIterationTypesOfIteratorCached(type, resolver) || + let iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || getIterationTypesOfIteratorFast(type, resolver); if (iterationTypes === noIterationTypes && errorNode) { @@ -42275,14 +42736,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any` // and `undefined` in our libs by default, a custom lib *could* use different definitions. - const globalIterationTypes = - getIterationTypesOfIteratorCached(globalType, resolver) || + const globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined, /*errorOutputContainer*/ undefined, /*noCache*/ false); const { returnType, nextType } = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } - if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) || - isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) { + if ( + isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) || + isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false)) + ) { const [yieldType, returnType, nextType] = getTypeArguments(type as GenericType); return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } @@ -42358,7 +42820,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes` * record is returned. Otherwise, we return `undefined`. */ - function getIterationTypesOfMethod(type: Type, resolver: IterationTypesResolver, methodName: "next" | "return" | "throw", errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined } | undefined): IterationTypes | undefined { + function getIterationTypesOfMethod(type: Type, resolver: IterationTypesResolver, methodName: "next" | "return" | "throw", errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined; } | undefined): IterationTypes | undefined { const method = getPropertyOfType(type, methodName as __String); // Ignore 'return' or 'throw' if they are missing. @@ -42411,7 +42873,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return createIterationTypes( getMappedType(globalType.typeParameters![0], mapper!), getMappedType(globalType.typeParameters![1], mapper!), - methodName === "next" ? getMappedType(globalType.typeParameters![2], mapper!) : undefined); + methodName === "next" ? getMappedType(globalType.typeParameters![2], mapper!) : undefined, + ); } } @@ -42478,7 +42941,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * NOTE: You probably don't want to call this directly and should be calling * `getIterationTypesOfIterator` instead. */ - function getIterationTypesOfIteratorSlow(type: Type, resolver: IterationTypesResolver, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined } | undefined, noCache: boolean) { + function getIterationTypesOfIteratorSlow(type: Type, resolver: IterationTypesResolver, errorNode: Node | undefined, errorOutputContainer: { errors: Diagnostic[] | undefined; } | undefined, noCache: boolean) { const iterationTypes = combineIterationTypes([ getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer), getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer), @@ -42544,7 +43007,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const container = getContainingFunctionOrClassStaticBlock(node); - if(container && isClassStaticBlockDeclaration(container)) { + if (container && isClassStaticBlockDeclaration(container)) { grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block); return; } @@ -42765,7 +43228,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const indexInfos = getApplicableIndexInfos(type, propNameType); const interfaceDeclaration = getObjectFlags(type) & ObjectFlags.Interface ? getDeclarationOfKind(type.symbol, SyntaxKind.InterfaceDeclaration) : undefined; const propDeclaration = declaration && declaration.kind === SyntaxKind.BinaryExpression || - name && name.kind === SyntaxKind.ComputedPropertyName ? declaration : undefined; + name && name.kind === SyntaxKind.ComputedPropertyName ? declaration : undefined; const localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; for (const info of indexInfos) { const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -42775,8 +43238,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type as InterfaceType), base => !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : undefined); if (errorNode && !isTypeAssignableTo(propType, info.type)) { - const diagnostic = createError(errorNode, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, - symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); + const diagnostic = createError(errorNode, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type)); if (propDeclaration && errorNode !== propDeclaration) { addRelatedInfo(diagnostic, createDiagnosticForNode(propDeclaration, Diagnostics._0_is_declared_here, symbolToString(prop))); } @@ -42799,8 +43261,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type as InterfaceType), base => !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : undefined); if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) { - error(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, - typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type)); + error(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type)); } } } @@ -42827,8 +43288,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * The name cannot be used as 'Object' of user defined types with special target. */ function checkClassNameCollisionWithObject(name: Identifier): void { - if (languageVersion >= ScriptTarget.ES5 && name.escapedText === "Object" - && (moduleKind < ModuleKind.ES2015 || getSourceFileOfNode(name).impliedNodeFormat === ModuleKind.CommonJS)) { + if ( + languageVersion >= ScriptTarget.ES5 && name.escapedText === "Object" + && (moduleKind < ModuleKind.ES2015 || getSourceFileOfNode(name).impliedNodeFormat === ModuleKind.CommonJS) + ) { error(name, Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 } } @@ -42853,8 +43316,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (containsArguments) { const lastJSDocParamIndex = jsdocParameters.length - 1; const lastJSDocParam = jsdocParameters[lastJSDocParamIndex]; - if (isJs && lastJSDocParam && isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && - lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !excludedParameters.has(lastJSDocParamIndex) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) { + if ( + isJs && lastJSDocParam && isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && + lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !excludedParameters.has(lastJSDocParamIndex) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type)) + ) { error(lastJSDocParam.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(lastJSDocParam.name)); } } @@ -42999,8 +43464,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function getFirstTransformableStaticClassElement(node: ClassLikeDeclaration) { - const willTransformStaticElementsOfDecoratedClass = - !legacyDecorators && languageVersion < ScriptTarget.ESNext && + const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < ScriptTarget.ESNext && classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node); const willTransformPrivateElementsOrClassStaticBlocks = languageVersion <= ScriptTarget.ES2022; const willTransformInitializers = !emitStandardClassFields; @@ -43014,8 +43478,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return member; } else if (isStatic(member)) { - if (isPrivateIdentifierClassElementDeclaration(member) || - willTransformInitializers && isInitializedProperty(member)) { + if ( + isPrivateIdentifierClassElementDeclaration(member) || + willTransformInitializers && isInitializedProperty(member) + ) { return member; } } @@ -43127,8 +43593,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else { // Report static side error only when instance type is assignable - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, - Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); } if (baseConstructorType.flags & TypeFlags.TypeVariable) { if (!isMixinConstructorType(staticType)) { @@ -43218,7 +43683,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type, typeWithThis, param, - /*memberIsParameterProperty*/ true + /*memberIsParameterProperty*/ true, ); } }); @@ -43252,7 +43717,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { reportErrors = true, ): MemberOverrideStatus { const declaredProp = member.name - && getSymbolAtLocation(member.name) + && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); if (!declaredProp) { return MemberOverrideStatus.Ok; @@ -43316,13 +43781,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, baseClassName, - symbolToString(suggestion)) : + symbolToString(suggestion), + ) : error( errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0, - baseClassName); + baseClassName, + ); } return MemberOverrideStatus.HasInvalidOverride; } @@ -43339,8 +43806,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : isJs ? - Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : - Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; + Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : + Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0; error(errorNode, diag, baseClassName); } return MemberOverrideStatus.NeedsOverride; @@ -43361,7 +43828,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class, - className); + className, + ); } return MemberOverrideStatus.HasInvalidOverride; } @@ -43381,13 +43849,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); const baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName); if (prop && baseProp) { - const rootChain = () => chainDiagnosticMessages( - /*details*/ undefined, - Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, - symbolToString(declaredProp), - typeToString(typeWithThis), - typeToString(baseWithThis) - ); + const rootChain = () => + chainDiagnosticMessages( + /*details*/ undefined, + Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, + symbolToString(declaredProp), + typeToString(typeWithThis), + typeToString(baseWithThis), + ); if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*headMessage*/ undefined, rootChain)) { issuedMemberError = true; } @@ -43462,8 +43931,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function getClassOrInterfaceDeclarationsOfSymbol(symbol: Symbol) { - return filter(symbol.declarations, (d: Declaration): d is ClassDeclaration | InterfaceDeclaration => - d.kind === SyntaxKind.ClassDeclaration || d.kind === SyntaxKind.InterfaceDeclaration); + return filter(symbol.declarations, (d: Declaration): d is ClassDeclaration | InterfaceDeclaration => d.kind === SyntaxKind.ClassDeclaration || d.kind === SyntaxKind.InterfaceDeclaration); } function checkKindsOfPropertyMemberOverrides(type: InterfaceType, baseType: BaseType): void { @@ -43484,7 +43952,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // NOTE: assignability is checked in checkClassDeclaration const baseProperties = getPropertiesOfType(baseType); let inheritedAbstractMemberNotImplementedError: Diagnostic | undefined; - basePropertyCheck: for (const baseProperty of baseProperties) { + basePropertyCheck: + for (const baseProperty of baseProperties) { const base = getTargetSymbol(baseProperty); if (base.flags & SymbolFlags.Prototype) { @@ -43524,10 +43993,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!inheritedAbstractMemberNotImplementedError) { inheritedAbstractMemberNotImplementedError = error( - derivedClassDecl, - Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1, - typeToString(type), typeToString(baseType)); - + derivedClassDecl, + Diagnostics.Non_abstract_class_0_does_not_implement_all_abstract_members_of_1, + typeToString(type), + typeToString(baseType), + ); } if (derivedClassDecl.kind === SyntaxKind.ClassExpression) { addRelatedInfo( @@ -43535,7 +44005,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { createDiagnosticForNode( baseProperty.valueDeclaration ?? (baseProperty.declarations && first(baseProperty.declarations)) ?? derivedClassDecl, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, - symbolToString(baseProperty), typeToString(baseType))); + symbolToString(baseProperty), + typeToString(baseType), + ), + ); } else { addRelatedInfo( @@ -43543,7 +44016,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { createDiagnosticForNode( baseProperty.valueDeclaration ?? (baseProperty.declarations && first(baseProperty.declarations)) ?? derivedClassDecl, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, - typeToString(type), symbolToString(baseProperty), typeToString(baseType))); + typeToString(type), + symbolToString(baseProperty), + typeToString(baseType), + ), + ); } } } @@ -43560,11 +44037,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const derivedPropertyFlags = derived.flags & SymbolFlags.PropertyOrAccessor; if (basePropertyFlags && derivedPropertyFlags) { // property/accessor is overridden with property/accessor - if ((getCheckFlags(base) & CheckFlags.Synthetic - ? base.declarations?.some(d => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) - : base.declarations?.every(d => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) + if ( + (getCheckFlags(base) & CheckFlags.Synthetic + ? base.declarations?.some(d => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) + : base.declarations?.every(d => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & CheckFlags.Mapped - || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) { + || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration) + ) { // when the base property is abstract or from an interface, base/derived flags don't need to match // for intersection properties, this must be true of *any* of the declarations, for others it must be true of *all* // same when the derived property is from an assignment @@ -43581,18 +44060,22 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else if (useDefineForClassFields) { const uninitialized = derived.declarations?.find(d => d.kind === SyntaxKind.PropertyDeclaration && !(d as PropertyDeclaration).initializer); - if (uninitialized + if ( + uninitialized && !(derived.flags & SymbolFlags.Transient) && !(baseDeclarationFlags & ModifierFlags.Abstract) && !(derivedDeclarationFlags & ModifierFlags.Abstract) - && !derived.declarations?.some(d => !!(d.flags & NodeFlags.Ambient))) { + && !derived.declarations?.some(d => !!(d.flags & NodeFlags.Ambient)) + ) { const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)!); const propName = (uninitialized as PropertyDeclaration).name; - if ((uninitialized as PropertyDeclaration).exclamationToken + if ( + (uninitialized as PropertyDeclaration).exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks - || !isPropertyInitializedInConstructor(propName, type, constructor)) { + || !isPropertyInitializedInConstructor(propName, type, constructor) + ) { const errorMessage = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, symbolToString(base), typeToString(baseType)); } @@ -43657,7 +44140,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; } - interface InheritanceInfoMap { prop: Symbol; containingType: Type; } + interface InheritanceInfoMap { + prop: Symbol; + containingType: Type; + } const seen = new Map<__String, InheritanceInfoMap>(); forEach(resolveDeclaredMembers(type).declaredProperties, p => { seen.set(p.escapedName, { prop: p, containingType: type }); @@ -43748,7 +44234,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return !containsUndefinedType(flowType); } - function checkInterfaceDeclaration(node: InterfaceDeclaration) { // Grammar checking if (!checkGrammarModifiers(node)) checkGrammarInterfaceDeclaration(node); @@ -43856,9 +44341,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const value = evaluate(initializer, member); if (value !== undefined) { if (isConstEnum && typeof value === "number" && !isFinite(value)) { - error(initializer, isNaN(value) ? - Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : - Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + error( + initializer, + isNaN(value) ? + Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : + Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value, + ); } } else if (isConstEnum) { @@ -43879,9 +44367,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const value = evaluate((expr as PrefixUnaryExpression).operand, location); if (typeof value === "number") { switch ((expr as PrefixUnaryExpression).operator) { - case SyntaxKind.PlusToken: return value; - case SyntaxKind.MinusToken: return -value; - case SyntaxKind.TildeToken: return ~value; + case SyntaxKind.PlusToken: + return value; + case SyntaxKind.MinusToken: + return -value; + case SyntaxKind.TildeToken: + return ~value; } } break; @@ -43890,23 +44381,37 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const right = evaluate((expr as BinaryExpression).right, location); if (typeof left === "number" && typeof right === "number") { switch ((expr as BinaryExpression).operatorToken.kind) { - case SyntaxKind.BarToken: return left | right; - case SyntaxKind.AmpersandToken: return left & right; - case SyntaxKind.GreaterThanGreaterThanToken: return left >> right; - case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: return left >>> right; - case SyntaxKind.LessThanLessThanToken: return left << right; - case SyntaxKind.CaretToken: return left ^ right; - case SyntaxKind.AsteriskToken: return left * right; - case SyntaxKind.SlashToken: return left / right; - case SyntaxKind.PlusToken: return left + right; - case SyntaxKind.MinusToken: return left - right; - case SyntaxKind.PercentToken: return left % right; - case SyntaxKind.AsteriskAsteriskToken: return left ** right; - } - } - else if ((typeof left === "string" || typeof left === "number") && + case SyntaxKind.BarToken: + return left | right; + case SyntaxKind.AmpersandToken: + return left & right; + case SyntaxKind.GreaterThanGreaterThanToken: + return left >> right; + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + return left >>> right; + case SyntaxKind.LessThanLessThanToken: + return left << right; + case SyntaxKind.CaretToken: + return left ^ right; + case SyntaxKind.AsteriskToken: + return left * right; + case SyntaxKind.SlashToken: + return left / right; + case SyntaxKind.PlusToken: + return left + right; + case SyntaxKind.MinusToken: + return left - right; + case SyntaxKind.PercentToken: + return left % right; + case SyntaxKind.AsteriskAsteriskToken: + return left ** right; + } + } + else if ( + (typeof left === "string" || typeof left === "number") && (typeof right === "string" || typeof right === "number") && - (expr as BinaryExpression).operatorToken.kind === SyntaxKind.PlusToken) { + (expr as BinaryExpression).operatorToken.kind === SyntaxKind.PlusToken + ) { return "" + left + right; } break; @@ -44057,9 +44562,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const declarations = symbol.declarations; if (declarations) { for (const declaration of declarations) { - if ((declaration.kind === SyntaxKind.ClassDeclaration || - (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration as FunctionLikeDeclaration).body))) && - !(declaration.flags & NodeFlags.Ambient)) { + if ( + (declaration.kind === SyntaxKind.ClassDeclaration || + (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration as FunctionLikeDeclaration).body))) && + !(declaration.flags & NodeFlags.Ambient) + ) { return declaration; } } @@ -44122,7 +44629,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const symbol = getSymbolOfDeclaration(node); // The following checks only apply on a non-ambient instantiated module declaration. - if (symbol.flags & SymbolFlags.ValueModule + if ( + symbol.flags & SymbolFlags.ValueModule && !inAmbientContext && isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions)) ) { @@ -44146,12 +44654,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. const mergedClass = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration); - if (mergedClass && - inSameLexicalScope(node, mergedClass)) { + if ( + mergedClass && + inSameLexicalScope(node, mergedClass) + ) { getNodeLinks(node).flags |= NodeCheckFlags.LexicalModuleMergesWithClass; } } - if (compilerOptions.verbatimModuleSyntax && + if ( + compilerOptions.verbatimModuleSyntax && node.parent.kind === SyntaxKind.SourceFile && (moduleKind === ModuleKind.CommonJS || node.parent.impliedNodeFormat === ModuleKind.CommonJS) ) { @@ -44245,7 +44756,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.QualifiedName: do { node = node.left; - } while (node.kind !== SyntaxKind.Identifier); + } + while (node.kind !== SyntaxKind.Identifier); return node; case SyntaxKind.PropertyAccessExpression: do { @@ -44253,7 +44765,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return node.name; } node = node.expression; - } while (node.kind !== SyntaxKind.Identifier); + } + while (node.kind !== SyntaxKind.Identifier); return node; } } @@ -44270,9 +44783,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && isAmbientModule(node.parent.parent); if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) { - error(moduleName, node.kind === SyntaxKind.ExportDeclaration ? - Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : - Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + error( + moduleName, + node.kind === SyntaxKind.ExportDeclaration ? + Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module, + ); return false; } if (inAmbientExternalModule && isExternalModuleNameRelative(moduleName.text)) { @@ -44315,8 +44831,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // A type-only import/export will already have a grammar error in a JS file, so no need to issue more errors within if (isInJSFile(node) && !(target.flags & SymbolFlags.Value) && !isTypeOnlyImportOrExportDeclaration(node)) { - const errorNode = - isImportOrExportSpecifier(node) ? node.propertyName || node.name : + const errorNode = isImportOrExportSpecifier(node) ? node.propertyName || node.name : isNamedDeclaration(node) ? node.name : node; @@ -44327,10 +44842,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (alreadyExportedSymbol === target) { const exportingDeclaration = alreadyExportedSymbol.declarations?.find(isJSDocNode); if (exportingDeclaration) { - addRelatedInfo(diag, createDiagnosticForNode( - exportingDeclaration, - Diagnostics._0_is_automatically_exported_here, - unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName))); + addRelatedInfo( + diag, + createDiagnosticForNode( + exportingDeclaration, + Diagnostics._0_is_automatically_exported_here, + unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName), + ), + ); } } } @@ -44343,14 +44862,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { errorNode, Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation, importedIdentifier, - `import("${moduleSpecifier}").${importedIdentifier}`); + `import("${moduleSpecifier}").${importedIdentifier}`, + ); } return; } const targetFlags = getSymbolFlags(target); - const excludedMeanings = - (symbol.flags & (SymbolFlags.Value | SymbolFlags.ExportValue) ? SymbolFlags.Value : 0) | + const excludedMeanings = (symbol.flags & (SymbolFlags.Value | SymbolFlags.ExportValue) ? SymbolFlags.Value : 0) | (symbol.flags & SymbolFlags.Type ? SymbolFlags.Type : 0) | (symbol.flags & SymbolFlags.Namespace ? SymbolFlags.Namespace : 0); if (targetFlags & excludedMeanings) { @@ -44360,9 +44879,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error(node, message, symbolToString(symbol)); } - if (getIsolatedModules(compilerOptions) + if ( + getIsolatedModules(compilerOptions) && !isTypeOnlyImportOrExportDeclaration(node) - && !(node.flags & NodeFlags.Ambient)) { + && !(node.flags & NodeFlags.Ambient) + ) { const typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); const isType = !(targetFlags & SymbolFlags.Value); if (isType || typeOnlyAlias) { @@ -44375,17 +44896,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType - ? compilerOptions.verbatimModuleSyntax - ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled - : Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled - : compilerOptions.verbatimModuleSyntax - ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled - : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled; + ? compilerOptions.verbatimModuleSyntax + ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled + : Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled + : compilerOptions.verbatimModuleSyntax + ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled + : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_preserveValueImports_and_isolatedModules_are_both_enabled; const name = idText(node.kind === SyntaxKind.ImportSpecifier ? node.propertyName || node.name : node.name); addTypeOnlyDeclarationRelatedInfo( error(node, message, name), isType ? undefined : typeOnlyAlias, - name + name, ); } if (isType && node.kind === SyntaxKind.ImportEqualsDeclaration && hasEffectiveModifier(node, ModifierFlags.Export)) { @@ -44409,7 +44930,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - if (compilerOptions.verbatimModuleSyntax && + if ( + compilerOptions.verbatimModuleSyntax && node.kind !== SyntaxKind.ImportEqualsDeclaration && !isInJSFile(node) && (moduleKind === ModuleKind.CommonJS || getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.CommonJS) @@ -44460,10 +44982,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkImportBinding(node: ImportEqualsDeclaration | ImportClause | NamespaceImport | ImportSpecifier) { checkCollisionsForDeclarationName(node, node.name); checkAliasSymbol(node); - if (node.kind === SyntaxKind.ImportSpecifier && + if ( + node.kind === SyntaxKind.ImportSpecifier && idText(node.propertyName || node.name) === "default" && getESModuleInterop(compilerOptions) && - moduleKind !== ModuleKind.System && (moduleKind < ModuleKind.ES2015 || getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.CommonJS)) { + moduleKind !== ModuleKind.System && (moduleKind < ModuleKind.ES2015 || getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.CommonJS) + ) { checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportDefault); } } @@ -44485,10 +45009,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const mode = (moduleKind === ModuleKind.NodeNext) && declaration.moduleSpecifier && getUsageModeForExpression(declaration.moduleSpecifier); if (mode !== ModuleKind.ESNext && moduleKind !== ModuleKind.ESNext) { - return grammarErrorOnNode(declaration.assertClause, + return grammarErrorOnNode( + declaration.assertClause, moduleKind === ModuleKind.NodeNext ? Diagnostics.Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls - : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext); + : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext, + ); } if (isImportDeclaration(declaration) ? declaration.importClause?.isTypeOnly : declaration.isTypeOnly) { @@ -44684,7 +45210,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (canConvertImportDeclarationToTypeOnly(statement) || canConvertImportEqualsDeclarationToTypeOnly(statement)) { error( statement, - Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error); + Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error, + ); } } } @@ -44697,8 +45224,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!node.parent.parent.moduleSpecifier) { const exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, - /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); } @@ -44713,10 +45239,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } else { - if (getESModuleInterop(compilerOptions) && + if ( + getESModuleInterop(compilerOptions) && moduleKind !== ModuleKind.System && (moduleKind < ModuleKind.ES2015 || getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.CommonJS) && - idText(node.propertyName || node.name) === "default") { + idText(node.propertyName || node.name) === "default" + ) { checkExternalEmitHelpers(node, ExternalEmitHelpers.ImportDefault); } } @@ -44767,19 +45295,23 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // However if it is a value, we need to check it's being used correctly checkExpressionCached(id); if (!isIllegalExportDefaultInCJS && !(node.flags & NodeFlags.Ambient) && compilerOptions.verbatimModuleSyntax && getTypeOnlyAliasDeclaration(sym, SymbolFlags.Value)) { - error(id, + error( + id, node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration, - idText(id)); + idText(id), + ); } } else if (!isIllegalExportDefaultInCJS && !(node.flags & NodeFlags.Ambient) && compilerOptions.verbatimModuleSyntax) { - error(id, + error( + id, node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type, - idText(id)); + idText(id), + ); } } else { @@ -44806,9 +45338,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (node.isExportEquals) { // Forbid export= in esm implementation files, and esm mode declaration files - if (moduleKind >= ModuleKind.ES2015 && + if ( + moduleKind >= ModuleKind.ES2015 && ((node.flags & NodeFlags.Ambient && getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.ESNext) || - (!(node.flags & NodeFlags.Ambient) && getSourceFileOfNode(node).impliedNodeFormat !== ModuleKind.CommonJS))) { + (!(node.flags & NodeFlags.Ambient) && getSourceFileOfNode(node).impliedNodeFormat !== ModuleKind.CommonJS)) + ) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } @@ -45102,9 +45636,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { : Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1; const typeNode = node.type; const type = getTypeFromTypeNode(typeNode); - grammarErrorOnNode(node, diagnostic, token, typeToString( - isJSDocNullableType(node) && !(type === neverType || type === voidType) - ? getUnionType(append([type, undefinedType], node.postfix ? undefined : nullType)) : type)); + grammarErrorOnNode( + node, + diagnostic, + token, + typeToString( + isJSDocNullableType(node) && !(type === neverType || type === voidType) + ? getUnionType(append([type, undefinedType], node.postfix ? undefined : nullType)) : type, + ), + ); } else { grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); @@ -45167,8 +45707,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { ? lastOrUndefined((paramTag.parent.parent as unknown as JSDocCallbackTag).typeExpression.parameters) : lastOrUndefined(host!.parameters); const symbol = getParameterSymbolFromJSDoc(paramTag); - if (!lastParamDeclaration || - symbol && lastParamDeclaration.symbol === symbol && isRestParameter(lastParamDeclaration)) { + if ( + !lastParamDeclaration || + symbol && lastParamDeclaration.symbol === symbol && isRestParameter(lastParamDeclaration) + ) { return createArrayType(type); } } @@ -45322,7 +45864,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } }); - if (compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error && + if ( + compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error && !node.isDeclarationFile && isExternalModule(node) ) { @@ -45654,9 +46197,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getSymbolOfNode(name.parent); } - if (isInJSFile(name) && + if ( + isInJSFile(name) && name.parent.kind === SyntaxKind.PropertyAccessExpression && - name.parent === (name.parent.parent as BinaryExpression).left) { + name.parent === (name.parent.parent as BinaryExpression).left + ) { // Check if this is a special property assignment if (!isPrivateIdentifier(name) && !isJSDocMemberName(name) && !isThisPropertyAndThisTyped(name.parent as PropertyAccessExpression)) { const specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name); @@ -45668,8 +46213,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (name.parent.kind === SyntaxKind.ExportAssignment && isEntityNameExpression(name)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression - const success = resolveEntityName(name, - /*all meanings*/ SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*ignoreErrors*/ true); + const success = resolveEntityName(name, /*all meanings*/ SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -45723,7 +46267,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (name.parent.kind === SyntaxKind.TypeParameter && name.parent.parent.kind === SyntaxKind.JSDocTemplateTag) { Debug.assert(!isInJSFile(name)); // Otherwise `isDeclarationName` would have been true. - const typeParameter = getTypeParameterFromJsDoc(name.parent as TypeParameterDeclaration & { parent: JSDocTemplateTag }); + const typeParameter = getTypeParameterFromJsDoc(name.parent as TypeParameterDeclaration & { parent: JSDocTemplateTag; }); return typeParameter && typeParameter.symbol; } @@ -45878,9 +46422,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isInRightSideOfImportOrExportAssignment(node as Identifier)) { return getSymbolOfNameOrPropertyAccessExpression(node as Identifier); } - else if (parent.kind === SyntaxKind.BindingElement && + else if ( + parent.kind === SyntaxKind.BindingElement && grandParent.kind === SyntaxKind.ObjectBindingPattern && - node === (parent as BindingElement).propertyName) { + node === (parent as BindingElement).propertyName + ) { const typeOfPattern = getTypeOfNode(grandParent); const propertyDeclaration = getPropertyOfType(typeOfPattern, (node as Identifier).escapedText); @@ -45948,7 +46494,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript // 4). type A = import("./f/*gotToDefinitionHere*/oo") - if ((isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + if ( + (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && (node.parent as ImportDeclaration).moduleSpecifier === node) || ((isInJSFile(node) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Bundler && isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false)) || isImportCall(node.parent)) || (isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) @@ -45965,8 +46512,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const objectType = isElementAccessExpression(parent) ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined : isLiteralTypeNode(parent) && isIndexedAccessTypeNode(grandParent) - ? getTypeFromTypeNode(grandParent.objectType) - : undefined; + ? getTypeFromTypeNode(grandParent.objectType) + : undefined; return objectType && getPropertyOfType(objectType, escapeLeadingUnderscores((node as StringLiteral | NumericLiteral).text)); case SyntaxKind.DefaultKeyword: @@ -46241,9 +46788,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!node) return false; const parent = node.parent; if (!parent) return false; - const isPropertyName = ((isPropertyAccessExpression(parent) - || isPropertyAssignment(parent)) - && parent.name === node); + const isPropertyName = (isPropertyAccessExpression(parent) + || isPropertyAssignment(parent)) + && parent.name === node; return !isPropertyName && getReferencedValueSymbol(node) === argumentsSymbol; } @@ -46480,9 +47027,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; } const target = getSymbolLinks(symbol).aliasTarget; - if (target && getEffectiveModifierFlags(node) & ModifierFlags.Export && + if ( + target && getEffectiveModifierFlags(node) & ModifierFlags.Export && getSymbolFlags(target) & SymbolFlags.Value && - (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { + (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)) + ) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -46681,8 +47230,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - if (type.flags & TypeFlags.UniqueESSymbol && - type.symbol === symbol) { + if ( + type.flags & TypeFlags.UniqueESSymbol && + type.symbol === symbol + ) { flags |= NodeBuilderFlags.AllowUniqueESSymbolType; } if (addUndefined) { @@ -46753,7 +47304,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /*nameArg*/ undefined, /*isUse*/ true, /*excludeGlobals*/ undefined, - /*getSpellingSuggestions*/ undefined); + /*getSpellingSuggestions*/ undefined, + ); } function getReferencedValueDeclaration(referenceIn: Identifier): Declaration | undefined { @@ -46946,7 +47498,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { firstAccessor, secondAccessor, setAccessor, - getAccessor + getAccessor, }; }, getSymbolOfExternalModuleSpecifier: moduleName => resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined), @@ -47220,11 +47772,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const list = arrayFrom(conflictingSymbols.keys()).join(", "); diagnostics.add(addRelatedInfo( createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), - createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file) + createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file), )); diagnostics.add(addRelatedInfo( createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), - createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file) + createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file), )); } }); @@ -47274,33 +47826,60 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getHelperNames(helper: ExternalEmitHelpers) { switch (helper) { - case ExternalEmitHelpers.Extends: return ["__extends"]; - case ExternalEmitHelpers.Assign: return ["__assign"]; - case ExternalEmitHelpers.Rest: return ["__rest"]; - case ExternalEmitHelpers.Decorate: return legacyDecorators ? ["__decorate"] : ["__esDecorate", "__runInitializers"]; - case ExternalEmitHelpers.Metadata: return ["__metadata"]; - case ExternalEmitHelpers.Param: return ["__param"]; - case ExternalEmitHelpers.Awaiter: return ["__awaiter"]; - case ExternalEmitHelpers.Generator: return ["__generator"]; - case ExternalEmitHelpers.Values: return ["__values"]; - case ExternalEmitHelpers.Read: return ["__read"]; - case ExternalEmitHelpers.SpreadArray: return ["__spreadArray"]; - case ExternalEmitHelpers.Await: return ["__await"]; - case ExternalEmitHelpers.AsyncGenerator: return ["__asyncGenerator"]; - case ExternalEmitHelpers.AsyncDelegator: return ["__asyncDelegator"]; - case ExternalEmitHelpers.AsyncValues: return ["__asyncValues"]; - case ExternalEmitHelpers.ExportStar: return ["__exportStar"]; - case ExternalEmitHelpers.ImportStar: return ["__importStar"]; - case ExternalEmitHelpers.ImportDefault: return ["__importDefault"]; - case ExternalEmitHelpers.MakeTemplateObject: return ["__makeTemplateObject"]; - case ExternalEmitHelpers.ClassPrivateFieldGet: return ["__classPrivateFieldGet"]; - case ExternalEmitHelpers.ClassPrivateFieldSet: return ["__classPrivateFieldSet"]; - case ExternalEmitHelpers.ClassPrivateFieldIn: return ["__classPrivateFieldIn"]; - case ExternalEmitHelpers.CreateBinding: return ["__createBinding"]; - case ExternalEmitHelpers.SetFunctionName: return ["__setFunctionName"]; - case ExternalEmitHelpers.PropKey: return ["__propKey"]; - case ExternalEmitHelpers.AddDisposableResourceAndDisposeResources: return ["__addDisposableResource", "__disposeResources"]; - default: return Debug.fail("Unrecognized helper"); + case ExternalEmitHelpers.Extends: + return ["__extends"]; + case ExternalEmitHelpers.Assign: + return ["__assign"]; + case ExternalEmitHelpers.Rest: + return ["__rest"]; + case ExternalEmitHelpers.Decorate: + return legacyDecorators ? ["__decorate"] : ["__esDecorate", "__runInitializers"]; + case ExternalEmitHelpers.Metadata: + return ["__metadata"]; + case ExternalEmitHelpers.Param: + return ["__param"]; + case ExternalEmitHelpers.Awaiter: + return ["__awaiter"]; + case ExternalEmitHelpers.Generator: + return ["__generator"]; + case ExternalEmitHelpers.Values: + return ["__values"]; + case ExternalEmitHelpers.Read: + return ["__read"]; + case ExternalEmitHelpers.SpreadArray: + return ["__spreadArray"]; + case ExternalEmitHelpers.Await: + return ["__await"]; + case ExternalEmitHelpers.AsyncGenerator: + return ["__asyncGenerator"]; + case ExternalEmitHelpers.AsyncDelegator: + return ["__asyncDelegator"]; + case ExternalEmitHelpers.AsyncValues: + return ["__asyncValues"]; + case ExternalEmitHelpers.ExportStar: + return ["__exportStar"]; + case ExternalEmitHelpers.ImportStar: + return ["__importStar"]; + case ExternalEmitHelpers.ImportDefault: + return ["__importDefault"]; + case ExternalEmitHelpers.MakeTemplateObject: + return ["__makeTemplateObject"]; + case ExternalEmitHelpers.ClassPrivateFieldGet: + return ["__classPrivateFieldGet"]; + case ExternalEmitHelpers.ClassPrivateFieldSet: + return ["__classPrivateFieldSet"]; + case ExternalEmitHelpers.ClassPrivateFieldIn: + return ["__classPrivateFieldIn"]; + case ExternalEmitHelpers.CreateBinding: + return ["__createBinding"]; + case ExternalEmitHelpers.SetFunctionName: + return ["__setFunctionName"]; + case ExternalEmitHelpers.PropKey: + return ["__propKey"]; + case ExternalEmitHelpers.AddDisposableResourceAndDisposeResources: + return ["__addDisposableResource", "__disposeResources"]; + default: + return Debug.fail("Unrecognized helper"); } } @@ -47360,7 +47939,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!hasParseDiagnostics(sourceFile)) { addRelatedInfo( error(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export), - createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here)); + createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here), + ); return true; } return false; @@ -47398,8 +47978,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(SyntaxKind.ConstKeyword)); } const parent = node.parent; - if (node.kind === SyntaxKind.TypeParameter && !(isFunctionLikeDeclaration(parent) || isClassLike(parent) || isFunctionTypeNode(parent) || - isConstructorTypeNode(parent) || isCallSignatureDeclaration(parent) || isConstructSignatureDeclaration(parent) || isMethodSignature(parent))) { + if ( + node.kind === SyntaxKind.TypeParameter && !(isFunctionLikeDeclaration(parent) || isClassLike(parent) || isFunctionTypeNode(parent) || + isConstructorTypeNode(parent) || isCallSignatureDeclaration(parent) || isConstructSignatureDeclaration(parent) || isMethodSignature(parent)) + ) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind)); } break; @@ -47525,7 +48107,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; case SyntaxKind.ExportKeyword: - if (compilerOptions.verbatimModuleSyntax && + if ( + compilerOptions.verbatimModuleSyntax && !(node.flags & NodeFlags.Ambient) && node.kind !== SyntaxKind.TypeAliasDeclaration && node.kind !== SyntaxKind.InterfaceDeclaration && @@ -47621,12 +48204,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (flags & ModifierFlags.Abstract) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== SyntaxKind.ClassDeclaration && - node.kind !== SyntaxKind.ConstructorType) { - if (node.kind !== SyntaxKind.MethodDeclaration && + if ( + node.kind !== SyntaxKind.ClassDeclaration && + node.kind !== SyntaxKind.ConstructorType + ) { + if ( + node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.PropertyDeclaration && node.kind !== SyntaxKind.GetAccessor && - node.kind !== SyntaxKind.SetAccessor) { + node.kind !== SyntaxKind.SetAccessor + ) { return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } if (!(node.parent.kind === SyntaxKind.ClassDeclaration && hasSyntacticModifier(node.parent, ModifierFlags.Abstract))) { @@ -47733,9 +48320,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function findFirstModifierExcept(node: HasModifiers, allowedModifier: SyntaxKind): Modifier | undefined { - const modifier = find(node.modifiers, isModifier); - return modifier && modifier.kind !== allowedModifier ? modifier : undefined; - } + const modifier = find(node.modifiers, isModifier); + return modifier && modifier.kind !== allowedModifier ? modifier : undefined; + } function findFirstIllegalModifier(node: HasModifiers | HasIllegalModifiers): Modifier | undefined { switch (node.kind) { @@ -47873,7 +48460,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { forEach(nonSimpleParameters, parameter => { addRelatedInfo( error(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), - createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here) + createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here), ); }); @@ -48083,8 +48670,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (node.asteriskToken) { Debug.assert( node.kind === SyntaxKind.FunctionDeclaration || - node.kind === SyntaxKind.FunctionExpression || - node.kind === SyntaxKind.MethodDeclaration); + node.kind === SyntaxKind.FunctionExpression || + node.kind === SyntaxKind.MethodDeclaration, + ); if (node.flags & NodeFlags.Ambient) { return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -48142,7 +48730,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else if (canHaveIllegalModifiers(prop) && prop.modifiers) { for (const mod of prop.modifiers) { - if (isModifier(mod)) { + if (isModifier(mod)) { grammarErrorOnNode(mod, Diagnostics._0_modifier_cannot_be_used_here, getTextOfNode(mod)); } } @@ -48265,15 +48853,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isInTopLevelContext(forInOrOfStatement)) { if (!hasParseDiagnostics(sourceFile)) { if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { - diagnostics.add(createDiagnosticForNode(forInOrOfStatement.awaitModifier, - Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); + diagnostics.add(createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module)); } switch (moduleKind) { case ModuleKind.Node16: case ModuleKind.NodeNext: if (sourceFile.impliedNodeFormat === ModuleKind.CommonJS) { diagnostics.add( - createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level) + createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level), ); break; } @@ -48287,9 +48874,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // fallthrough default: diagnostics.add( - createDiagnosticForNode(forInOrOfStatement.awaitModifier, - Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher - ) + createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher), ); break; } @@ -48313,8 +48898,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & NodeFlags.AwaitContext) && - isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") { + if ( + isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & NodeFlags.AwaitContext) && + isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async" + ) { grammarErrorOnNode(forInOrOfStatement.initializer, Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async); return false; } @@ -48385,10 +48972,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_have_type_parameters); } if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, + return grammarErrorOnNode( + accessor.name, accessor.kind === SyntaxKind.GetAccessor ? Diagnostics.A_get_accessor_cannot_have_parameters : - Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + Diagnostics.A_set_accessor_must_have_exactly_one_parameter, + ); } if (accessor.kind === SyntaxKind.SetAccessor) { if (accessor.type) { @@ -48449,8 +49038,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; case SyntaxKind.PropertyDeclaration: - if (!isStatic(parent) || - !hasEffectiveReadonlyModifier(parent)) { + if ( + !isStatic(parent) || + !hasEffectiveReadonlyModifier(parent) + ) { return grammarErrorOnNode((parent as PropertyDeclaration).name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; @@ -48604,18 +49195,20 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isStringOrNumberLiteralExpression(expr: Expression) { return isStringOrNumericLiteralLike(expr) || expr.kind === SyntaxKind.PrefixUnaryExpression && (expr as PrefixUnaryExpression).operator === SyntaxKind.MinusToken && - (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.NumericLiteral; + (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.NumericLiteral; } function isBigIntLiteralExpression(expr: Expression) { return expr.kind === SyntaxKind.BigIntLiteral || expr.kind === SyntaxKind.PrefixUnaryExpression && (expr as PrefixUnaryExpression).operator === SyntaxKind.MinusToken && - (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.BigIntLiteral; + (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.BigIntLiteral; } function isSimpleLiteralEnumReference(expr: Expression) { - if ((isPropertyAccessExpression(expr) || (isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && - isEntityNameExpression(expr.expression)) { + if ( + (isPropertyAccessExpression(expr) || (isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + isEntityNameExpression(expr.expression) + ) { return !!(checkExpressionCached(expr).flags & TypeFlags.EnumLike); } } @@ -48676,13 +49269,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type - ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations - : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; + ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations + : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; return grammarErrorOnNode(node.exclamationToken, message); } - if ((moduleKind < ModuleKind.ES2015 || getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.CommonJS) && moduleKind !== ModuleKind.System && - !(node.parent.parent.flags & NodeFlags.Ambient) && hasSyntacticModifier(node.parent.parent, ModifierFlags.Export)) { + if ( + (moduleKind < ModuleKind.ES2015 || getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.CommonJS) && moduleKind !== ModuleKind.System && + !(node.parent.parent.flags & NodeFlags.Ambient) && hasSyntacticModifier(node.parent.parent, ModifierFlags.Export) + ) { checkESModuleMarker(node.name); } @@ -48742,10 +49337,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const blockScopeFlags = declarationList.flags & NodeFlags.BlockScoped; if ((blockScopeFlags === NodeFlags.Using || blockScopeFlags === NodeFlags.AwaitUsing) && isForInStatement(declarationList.parent)) { - return grammarErrorOnNode(declarationList, + return grammarErrorOnNode( + declarationList, blockScopeFlags === NodeFlags.Using ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : - Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration); + Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration, + ); } if (blockScopeFlags === NodeFlags.AwaitUsing) { @@ -48906,13 +49503,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkAmbientInitializer(node); } - if (isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || - node.flags & NodeFlags.Ambient || isStatic(node) || hasAbstractModifier(node))) { + if ( + isPropertyDeclaration(node) && node.exclamationToken && (!isClassLike(node.parent) || !node.type || node.initializer || + node.flags & NodeFlags.Ambient || isStatic(node) || hasAbstractModifier(node)) + ) { const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type - ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations - : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; + ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations + : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; return grammarErrorOnNode(node.exclamationToken, message); } } @@ -48930,14 +49529,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === SyntaxKind.InterfaceDeclaration || + if ( + node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration || node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.ExportDeclaration || node.kind === SyntaxKind.ExportAssignment || node.kind === SyntaxKind.NamespaceExportDeclaration || - hasSyntacticModifier(node, ModifierFlags.Ambient | ModifierFlags.Export | ModifierFlags.Default)) { + hasSyntacticModifier(node, ModifierFlags.Ambient | ModifierFlags.Export | ModifierFlags.Default) + ) { return false; } @@ -49067,7 +49668,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { specifier, specifier.kind === SyntaxKind.ImportSpecifier ? Diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement - : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement); + : Diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement, + ); } }); } @@ -49242,7 +49844,7 @@ function isNotAccessor(declaration: Declaration): boolean { function isNotOverload(declaration: Declaration): boolean { return (declaration.kind !== SyntaxKind.FunctionDeclaration && declaration.kind !== SyntaxKind.MethodDeclaration) || - !!(declaration as FunctionDeclaration).body; + !!(declaration as FunctionDeclaration).body; } /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ @@ -49271,9 +49873,12 @@ namespace JsxNames { function getIterationTypesKeyFromIterationTypeKind(typeKind: IterationTypeKind) { switch (typeKind) { - case IterationTypeKind.Yield: return "yieldType"; - case IterationTypeKind.Return: return "returnType"; - case IterationTypeKind.Next: return "nextType"; + case IterationTypeKind.Yield: + return "yieldType"; + case IterationTypeKind.Return: + return "returnType"; + case IterationTypeKind.Next: + return "nextType"; } } @@ -49287,7 +49892,7 @@ export function signatureHasLiteralTypes(s: Signature) { return !!(s.flags & SignatureFlags.HasLiteralTypes); } -function createBasicNodeBuilderModuleSpecifierResolutionHost(host: TypeCheckerHost): ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string } { +function createBasicNodeBuilderModuleSpecifierResolutionHost(host: TypeCheckerHost): ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string; } { return { getCommonSourceDirectory: !!(host as Program).getCommonSourceDirectory ? () => (host as Program).getCommonSourceDirectory() : () => "", getCurrentDirectory: () => host.getCurrentDirectory(), @@ -49326,14 +49931,14 @@ interface NodeBuilderContext { } class SymbolTrackerImpl implements SymbolTracker { - moduleResolverHost: ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string } | undefined = undefined; + moduleResolverHost: ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string; } | undefined = undefined; context: NodeBuilderContext; readonly inner: SymbolTracker | undefined = undefined; readonly canTrackSymbol: boolean; disableTrackSymbol = false; - constructor(context: NodeBuilderContext, tracker: SymbolTracker | undefined, moduleResolverHost: ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string } | undefined) { + constructor(context: NodeBuilderContext, tracker: SymbolTracker | undefined, moduleResolverHost: ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string; } | undefined) { while (tracker instanceof SymbolTrackerImpl) { tracker = tracker.inner; } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 4004f0260ee8f..2bde2526ab0c3 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -301,7 +301,7 @@ export const optionsForWatch: CommandLineOption[] = [ name: "excludeDirectory", type: "string", isFilePath: true, - extraValidation: specToDiagnostic + extraValidation: specToDiagnostic, }, category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Remove_a_list_of_directories_from_the_watch_process, @@ -313,7 +313,7 @@ export const optionsForWatch: CommandLineOption[] = [ name: "excludeFile", type: "string", isFilePath: true, - extraValidation: specToDiagnostic + extraValidation: specToDiagnostic, }, category: Diagnostics.Watch_and_Build_Modes, description: Diagnostics.Remove_a_list_of_files_from_the_watch_mode_s_processing, @@ -415,7 +415,7 @@ export const commonOptionsWithBuild: CommandLineOption[] = [ paramType: Diagnostics.FILE_OR_DIRECTORY, category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging, - defaultValueDescription: "profile.cpuprofile" + defaultValueDescription: "profile.cpuprofile", }, { name: "generateTrace", @@ -424,7 +424,7 @@ export const commonOptionsWithBuild: CommandLineOption[] = [ isCommandLineOnly: true, paramType: Diagnostics.DIRECTORY, category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Generates_an_event_trace_and_a_list_of_types + description: Diagnostics.Generates_an_event_trace_and_a_list_of_types, }, { name: "incremental", @@ -433,7 +433,7 @@ export const commonOptionsWithBuild: CommandLineOption[] = [ category: Diagnostics.Projects, description: Diagnostics.Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects, transpileOptionValue: undefined, - defaultValueDescription: Diagnostics.false_unless_composite_is_set + defaultValueDescription: Diagnostics.false_unless_composite_is_set, }, { name: "declaration", @@ -456,7 +456,7 @@ export const commonOptionsWithBuild: CommandLineOption[] = [ category: Diagnostics.Emit, transpileOptionValue: undefined, defaultValueDescription: false, - description: Diagnostics.Create_sourcemaps_for_d_ts_files + description: Diagnostics.Create_sourcemaps_for_d_ts_files, }, { name: "emitDeclarationOnly", @@ -504,7 +504,7 @@ export const commonOptionsWithBuild: CommandLineOption[] = [ category: Diagnostics.Command_line_Options, isCommandLineOnly: true, description: Diagnostics.Set_the_language_of_the_messaging_from_TypeScript_This_does_not_affect_emit, - defaultValueDescription: Diagnostics.Platform_specific + defaultValueDescription: Diagnostics.Platform_specific, }, ]; @@ -644,7 +644,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ showInSimplifiedHelpView: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_a_set_of_bundled_library_declaration_files_that_describe_the_target_runtime_environment, - transpileOptionValue: undefined + transpileOptionValue: undefined, }, { name: "allowJs", @@ -712,7 +712,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ paramType: Diagnostics.LOCATION, category: Diagnostics.Modules, description: Diagnostics.Specify_the_root_folder_within_your_source_files, - defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files + defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files, }, { name: "composite", @@ -826,7 +826,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Enable_error_reporting_for_expressions_and_declarations_with_an_implied_any_type, - defaultValueDescription: Diagnostics.false_unless_strict_is_set + defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: "strictNullChecks", @@ -836,7 +836,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.When_type_checking_take_into_account_null_and_undefined, - defaultValueDescription: Diagnostics.false_unless_strict_is_set + defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: "strictFunctionTypes", @@ -846,7 +846,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.When_assigning_functions_check_to_ensure_parameters_and_the_return_values_are_subtype_compatible, - defaultValueDescription: Diagnostics.false_unless_strict_is_set + defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: "strictBindCallApply", @@ -856,7 +856,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Check_that_the_arguments_for_bind_call_and_apply_methods_match_the_original_function, - defaultValueDescription: Diagnostics.false_unless_strict_is_set + defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: "strictPropertyInitialization", @@ -866,7 +866,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, - defaultValueDescription: Diagnostics.false_unless_strict_is_set + defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: "noImplicitThis", @@ -876,7 +876,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Enable_error_reporting_when_this_is_given_the_type_any, - defaultValueDescription: Diagnostics.false_unless_strict_is_set + defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, { name: "useUnknownInCatchVariables", @@ -897,7 +897,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ strictFlag: true, category: Diagnostics.Type_Checking, description: Diagnostics.Ensure_use_strict_is_always_emitted, - defaultValueDescription: Diagnostics.false_unless_strict_is_set + defaultValueDescription: Diagnostics.false_unless_strict_is_set, }, // Additional Checks @@ -993,7 +993,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ paramType: Diagnostics.STRATEGY, category: Diagnostics.Modules, description: Diagnostics.Specify_how_TypeScript_looks_up_a_file_from_a_given_module_specifier, - defaultValueDescription: Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node + defaultValueDescription: Diagnostics.module_AMD_or_UMD_or_System_or_ES6_then_Classic_Otherwise_Node, }, { name: "baseUrl", @@ -1001,7 +1001,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ affectsModuleResolution: true, isFilePath: true, category: Diagnostics.Modules, - description: Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names + description: Diagnostics.Specify_the_base_directory_to_resolve_non_relative_module_names, }, { // this option can only be specified in tsconfig.json @@ -1012,7 +1012,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ isTSConfigOnly: true, category: Diagnostics.Modules, description: Diagnostics.Specify_a_set_of_entries_that_re_map_imports_to_additional_lookup_locations, - transpileOptionValue: undefined + transpileOptionValue: undefined, }, { // this option can only be specified in tsconfig.json @@ -1023,13 +1023,13 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ element: { name: "rootDirs", type: "string", - isFilePath: true + isFilePath: true, }, affectsModuleResolution: true, category: Diagnostics.Modules, description: Diagnostics.Allow_multiple_folders_to_be_treated_as_one_when_resolving_modules, transpileOptionValue: undefined, - defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files + defaultValueDescription: Diagnostics.Computed_from_the_list_of_input_files, }, { name: "typeRoots", @@ -1037,24 +1037,24 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ element: { name: "typeRoots", type: "string", - isFilePath: true + isFilePath: true, }, affectsModuleResolution: true, category: Diagnostics.Modules, - description: Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types + description: Diagnostics.Specify_multiple_folders_that_act_like_Slashnode_modules_Slash_types, }, { name: "types", type: "list", element: { name: "types", - type: "string" + type: "string", }, affectsProgramStructure: true, showInSimplifiedHelpView: true, category: Diagnostics.Modules, description: Diagnostics.Specify_type_package_names_to_be_included_without_being_referenced_in_a_source_file, - transpileOptionValue: undefined + transpileOptionValue: undefined, }, { name: "allowSyntheticDefaultImports", @@ -1063,7 +1063,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ affectsBuildInfo: true, category: Diagnostics.Interop_Constraints, description: Diagnostics.Allow_import_x_from_y_when_a_module_doesn_t_have_a_default_export, - defaultValueDescription: Diagnostics.module_system_or_esModuleInterop + defaultValueDescription: Diagnostics.module_system_or_esModuleInterop, }, { name: "esModuleInterop", @@ -1199,7 +1199,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ type: "string", category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_the_JSX_factory_function_used_when_targeting_React_JSX_emit_e_g_React_createElement_or_h, - defaultValueDescription: "`React.createElement`" + defaultValueDescription: "`React.createElement`", }, { name: "jsxFragmentFactory", @@ -1217,7 +1217,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ affectsModuleResolution: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Specify_module_specifier_used_to_import_the_JSX_factory_functions_when_using_jsx_Colon_react_jsx_Asterisk, - defaultValueDescription: "react" + defaultValueDescription: "react", }, { name: "resolveJsonModule", @@ -1272,7 +1272,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ type: "string", category: Diagnostics.Backwards_Compatibility, description: Diagnostics.No_longer_supported_In_early_versions_manually_set_the_text_encoding_for_reading_files, - defaultValueDescription: "utf8" + defaultValueDescription: "utf8", }, { name: "emitBOM", @@ -1287,14 +1287,14 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ name: "newLine", type: new Map(Object.entries({ crlf: NewLineKind.CarriageReturnLineFeed, - lf: NewLineKind.LineFeed + lf: NewLineKind.LineFeed, })), affectsEmit: true, affectsBuildInfo: true, paramType: Diagnostics.NEWLINE, category: Diagnostics.Emit, description: Diagnostics.Set_the_newline_character_for_emitting_files, - defaultValueDescription: "lf" + defaultValueDescription: "lf", }, { name: "noErrorTruncation", @@ -1497,7 +1497,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ affectsBuildInfo: true, category: Diagnostics.Language_and_Environment, description: Diagnostics.Emit_ECMAScript_standard_compliant_class_fields, - defaultValueDescription: Diagnostics.true_for_ES2022_and_above_including_ESNext + defaultValueDescription: Diagnostics.true_for_ES2022_and_above_including_ESNext, }, { name: "preserveValueImports", @@ -1523,11 +1523,10 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [ isTSConfigOnly: true, element: { name: "plugin", - type: "object" + type: "object", }, description: Diagnostics.Specify_a_list_of_language_service_plugins_to_include, category: Diagnostics.Editor_Support, - }, { name: "moduleDetection", @@ -1555,32 +1554,25 @@ export const optionDeclarations: CommandLineOption[] = [ ]; /** @internal */ -export const semanticDiagnosticsOptionDeclarations: readonly CommandLineOption[] = - optionDeclarations.filter(option => !!option.affectsSemanticDiagnostics); +export const semanticDiagnosticsOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsSemanticDiagnostics); /** @internal */ -export const affectsEmitOptionDeclarations: readonly CommandLineOption[] = - optionDeclarations.filter(option => !!option.affectsEmit); +export const affectsEmitOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsEmit); /** @internal */ -export const affectsDeclarationPathOptionDeclarations: readonly CommandLineOption[] = - optionDeclarations.filter(option => !!option.affectsDeclarationPath); +export const affectsDeclarationPathOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsDeclarationPath); /** @internal */ -export const moduleResolutionOptionDeclarations: readonly CommandLineOption[] = - optionDeclarations.filter(option => !!option.affectsModuleResolution); +export const moduleResolutionOptionDeclarations: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsModuleResolution); /** @internal */ -export const sourceFileAffectingCompilerOptions: readonly CommandLineOption[] = optionDeclarations.filter(option => - !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics); +export const sourceFileAffectingCompilerOptions: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics); /** @internal */ -export const optionsAffectingProgramStructure: readonly CommandLineOption[] = - optionDeclarations.filter(option => !!option.affectsProgramStructure); +export const optionsAffectingProgramStructure: readonly CommandLineOption[] = optionDeclarations.filter(option => !!option.affectsProgramStructure); /** @internal */ -export const transpileOptionValueCompilerOptions: readonly CommandLineOption[] = optionDeclarations.filter(option => - hasProperty(option, "transpileOptionValue")); +export const transpileOptionValueCompilerOptions: readonly CommandLineOption[] = optionDeclarations.filter(option => hasProperty(option, "transpileOptionValue")); // Build related options /** @internal */ @@ -1615,13 +1607,13 @@ export const optionsForBuild: CommandLineOption[] = [ description: Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean", defaultValueDescription: false, - } + }, ]; /** @internal */ export const buildOpts: CommandLineOption[] = [ ...commonOptionsWithBuild, - ...optionsForBuild + ...optionsForBuild, ]; /** @internal */ @@ -1636,16 +1628,16 @@ export const typeAcquisitionDeclarations: CommandLineOption[] = [ type: "list", element: { name: "include", - type: "string" - } + type: "string", + }, }, { name: "exclude", type: "list", element: { name: "exclude", - type: "string" - } + type: "string", + }, }, { name: "disableFilenameBasedTypeAcquisition", @@ -1683,7 +1675,7 @@ export function getOptionsNameMap(): OptionsNameMap { const compilerOptionsAlternateMode: AlternateModeDiagnostics = { diagnostic: Diagnostics.Compiler_option_0_may_only_be_used_with_build, - getOptionsNameMap: getBuildOptionsNameMap + getOptionsNameMap: getBuildOptionsNameMap, }; /** @internal */ @@ -1693,7 +1685,7 @@ export const defaultInitCompilerOptions: CompilerOptions = { strict: true, esModuleInterop: true, forceConsistentCasingInFileNames: true, - skipLibCheck: true + skipLibCheck: true, }; /** @internal */ @@ -1774,7 +1766,8 @@ function createUnknownOptionError( export function parseCommandLineWorker( diagnostics: ParseCommandLineWorkerDiagnostics, commandLine: readonly string[], - readFile?: (path: string) => string | undefined) { + readFile?: (path: string) => string | undefined, +) { const options = {} as OptionsBase; let watchOptions: WatchOptions | undefined; const fileNames: string[] = []; @@ -1785,7 +1778,7 @@ export function parseCommandLineWorker( options, watchOptions, fileNames, - errors + errors, }; function parseStrings(args: readonly string[]) { @@ -1857,7 +1850,7 @@ function parseOptionValue( diagnostics: ParseCommandLineWorkerDiagnostics, opt: CommandLineOption, options: OptionsBase, - errors: Diagnostic[] + errors: Diagnostic[], ) { if (opt.isTSConfigOnly) { const optValue = args[i]; @@ -1937,7 +1930,7 @@ export const compilerOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnos optionDeclarations, unknownOptionDiagnostic: Diagnostics.Unknown_compiler_option_0, unknownDidYouMeanDiagnostic: Diagnostics.Unknown_compiler_option_0_Did_you_mean_1, - optionTypeMismatchDiagnostic: Diagnostics.Compiler_option_0_expects_an_argument + optionTypeMismatchDiagnostic: Diagnostics.Compiler_option_0_expects_an_argument, }; export function parseCommandLine(commandLine: readonly string[], readFile?: (path: string) => string | undefined): ParsedCommandLine { return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile); @@ -1976,7 +1969,7 @@ function getBuildOptionsNameMap(): OptionsNameMap { const buildOptionsAlternateMode: AlternateModeDiagnostics = { diagnostic: Diagnostics.Compiler_option_0_may_not_be_used_with_build, - getOptionsNameMap + getOptionsNameMap, }; const buildOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { @@ -1985,14 +1978,14 @@ const buildOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { optionDeclarations: buildOpts, unknownOptionDiagnostic: Diagnostics.Unknown_build_option_0, unknownDidYouMeanDiagnostic: Diagnostics.Unknown_build_option_0_Did_you_mean_1, - optionTypeMismatchDiagnostic: Diagnostics.Build_option_0_requires_a_value_of_type_1 + optionTypeMismatchDiagnostic: Diagnostics.Build_option_0_requires_a_value_of_type_1, }; /** @internal */ export function parseBuildCommand(args: readonly string[]): ParsedBuildCommand { const { options, watchOptions, fileNames: projects, errors } = parseCommandLineWorker( buildOptionsDidYouMeanDiagnostics, - args + args, ); const buildOptions = options as BuildOptions; @@ -2072,7 +2065,7 @@ export function getParsedCommandLineOfConfigFile( /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, - watchOptionsToExtend + watchOptionsToExtend, ); } @@ -2080,7 +2073,7 @@ export function getParsedCommandLineOfConfigFile( * Read tsconfig.json file * @param fileName The path to the config file */ -export function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic } { +export function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic; } { const textOrDiagnostic = tryReadFile(fileName, readFile); return isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } @@ -2090,11 +2083,11 @@ export function readConfigFile(fileName: string, readFile: (path: string) => str * @param fileName The path to the config file * @param jsonText The text of the config file */ -export function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic } { +export function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic; } { const jsonSourceFile = parseJsonText(fileName, jsonText); return { config: convertConfigFileToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics, /*jsonConversionNotifier*/ undefined), - error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined, }; } @@ -2138,7 +2131,7 @@ const watchOptionsDidYouMeanDiagnostics: ParseCommandLineWorkerDiagnostics = { optionDeclarations: optionsForWatch, unknownOptionDiagnostic: Diagnostics.Unknown_watch_option_0, unknownDidYouMeanDiagnostic: Diagnostics.Unknown_watch_option_0_Did_you_mean_1, - optionTypeMismatchDiagnostic: Diagnostics.Watch_option_0_requires_a_value_of_type_1 + optionTypeMismatchDiagnostic: Diagnostics.Watch_option_0_requires_a_value_of_type_1, }; let commandLineCompilerOptionsMapCache: Map; @@ -2159,7 +2152,7 @@ const extendsOptionDeclaration: CommandLineOptionOfListType = { type: "listOrElement", element: { name: "extends", - type: "string" + type: "string", }, category: Diagnostics.File_Management, disallowNullOrUndefined: true, @@ -2180,7 +2173,7 @@ const typeAcquisitionDeclaration: TsConfigOnlyOption = { name: "typeAcquisition", type: "object", elementOptions: getCommandLineTypeAcquisitionMap(), - extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics + extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics, }; let _tsconfigRootOptions: TsConfigOnlyOption; function getTsconfigRootOptionsMap() { @@ -2198,7 +2191,7 @@ function getTsconfigRootOptionsMap() { type: "list", element: { name: "references", - type: "object" + type: "object", }, category: Diagnostics.Projects, }, @@ -2207,7 +2200,7 @@ function getTsconfigRootOptionsMap() { type: "list", element: { name: "files", - type: "string" + type: "string", }, category: Diagnostics.File_Management, }, @@ -2216,23 +2209,23 @@ function getTsconfigRootOptionsMap() { type: "list", element: { name: "include", - type: "string" + type: "string", }, category: Diagnostics.File_Management, - defaultValueDescription: Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk + defaultValueDescription: Diagnostics.if_files_is_specified_otherwise_Asterisk_Asterisk_Slash_Asterisk, }, { name: "exclude", type: "list", element: { name: "exclude", - type: "string" + type: "string", }, category: Diagnostics.File_Management, - defaultValueDescription: Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified + defaultValueDescription: Diagnostics.node_modules_bower_components_jspm_packages_plus_the_value_of_outDir_if_one_is_specified, }, - compileOnSaveCommandLineOption - ]) + compileOnSaveCommandLineOption, + ]), }; } return _tsconfigRootOptions; @@ -2261,7 +2254,7 @@ function convertConfigFileToObject( sourceFile, rootExpression, Diagnostics.The_root_value_of_a_0_file_must_be_an_object, - getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json" + getBaseFileName(sourceFile.fileName) === "jsconfig.json" ? "jsconfig.json" : "tsconfig.json", )); // Last-ditch error recovery. Somewhat useful because the JSON parser will recover from some parse errors by // synthesizing a top-level array literal expression. There's a reasonable chance the first element of that @@ -2340,7 +2333,7 @@ export function convertToJson( function convertArrayLiteralExpressionToJson( elements: NodeArray, - elementOption: CommandLineOption | undefined + elementOption: CommandLineOption | undefined, ) { if (!returnValue) { elements.forEach(element => convertPropertyValueToJson(element, elementOption)); @@ -2391,7 +2384,8 @@ export function convertToJson( case SyntaxKind.ArrayLiteralExpression: return convertArrayLiteralExpressionToJson( (valueExpression as ArrayLiteralExpression).elements, - option && (option as CommandLineOptionOfListType).element); + option && (option as CommandLineOptionOfListType).element, + ); } // Not in expected format @@ -2412,8 +2406,8 @@ export function convertToJson( function getCompilerOptionValueTypeString(option: CommandLineOption): string { return (option.type === "listOrElement") ? - `${getCompilerOptionValueTypeString(option.element)} or Array`: - option.type === "list" ? + `${getCompilerOptionValueTypeString(option.element)} or Array` : + option.type === "list" ? "Array" : isString(option.type) ? option.type : "string"; } @@ -2467,9 +2461,9 @@ export function convertToTSConfig(configParseResult: ParsedCommandLine, configFi configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs, configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, host, - ) + ), ), - f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName) + f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName), ); const optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); const watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions); @@ -2492,9 +2486,9 @@ export function convertToTSConfig(configParseResult: ParsedCommandLine, configFi files: length(files) ? files : undefined, ...(configParseResult.options.configFile?.configFileSpecs ? { include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs), - exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs + exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs, } : {}), - compileOnSave: !!configParseResult.compileOnSave ? true : undefined + compileOnSave: !!configParseResult.compileOnSave ? true : undefined, }; return config; } @@ -2559,7 +2553,7 @@ export function getNameOfCompilerOptionValue(value: CompilerOptionsValue, custom /** @internal */ export function serializeCompilerOptions( options: CompilerOptions, - pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean } + pathOptions?: { configFilePath: string; useCaseSensitiveFileNames: boolean; }, ): Map { return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions); } @@ -2571,7 +2565,7 @@ function serializeWatchOptions(options: WatchOptions) { function serializeOptionBaseObject( options: OptionsBase, { optionsNameMap }: OptionsNameMap, - pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean } + pathOptions?: { configFilePath: string; useCaseSensitiveFileNames: boolean; }, ): Map { const result = new Map(); const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); @@ -2698,7 +2692,7 @@ export function generateTSConfig(options: CompilerOptions, fileNames: readonly s // Serialize all options and their descriptions let marginLength = 0; let seenKnownKeys = 0; - const entries: { value: string, description?: string }[] = []; + const entries: { value: string; description?: string; }[] = []; categorizedOptions.forEach((options, category) => { if (entries.length !== 0) { entries.push({ value: "" }); @@ -2714,7 +2708,7 @@ export function generateTSConfig(options: CompilerOptions, fileNames: readonly s } entries.push({ value: optionName, - description: `/* ${option.description && getLocaleSpecificMessage(option.description) || option.name} */` + description: `/* ${option.description && getLocaleSpecificMessage(option.description) || option.name} */`, }); marginLength = Math.max(optionName.length, marginLength); } @@ -2759,7 +2753,7 @@ export function convertToOptionsWithAbsolutePaths(options: CompilerOptions, toAb result[name] = convertToOptionValueWithAbsolutePaths( optionsNameMap.get(name.toLowerCase()), options[name] as CompilerOptionsValue, - toAbsolutePath + toAbsolutePath, ); } } @@ -2849,7 +2843,7 @@ function parseJsonConfigFileContentWorker( configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: readonly FileExtensionInfo[] = [], - extendedConfigCache?: Map + extendedConfigCache?: Map, ): ParsedCommandLine { Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); const errors: Diagnostic[] = []; @@ -2968,7 +2962,7 @@ function parseJsonConfigFileContentWorker( path: getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, - circular: ref.circular + circular: ref.circular, }); } } @@ -3018,7 +3012,8 @@ function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }: ConfigFileSpecs Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), - JSON.stringify(excludeSpecs || [])); + JSON.stringify(excludeSpecs || []), + ); } function shouldReportNoInputFiles(fileNames: string[], canJsonReportNoInutFiles: boolean, resolutionStack?: Path[]) { @@ -3064,7 +3059,7 @@ interface ExtendsResult { exclude?: string[]; files?: string[]; compileOnSave?: boolean; - extendedSourceFiles?: Set + extendedSourceFiles?: Set; } /** * This *just* extracts options/include/exclude/files out of a config file. @@ -3078,7 +3073,7 @@ function parseConfig( configFileName: string | undefined, resolutionStack: string[], errors: Diagnostic[], - extendedConfigCache?: Map + extendedConfigCache?: Map, ): ParsedTsconfig { basePath = normalizeSlashes(basePath); const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath); @@ -3102,7 +3097,7 @@ function parseConfig( if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - const result: ExtendsResult = { options:{} }; + const result: ExtendsResult = { options: {} }; if (isString(ownConfig.extendedConfigPath)) { applyExtendedConfig(result, ownConfig.extendedConfigPath); } @@ -3119,20 +3114,21 @@ function parseConfig( ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assign(result.watchOptions, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions; - } + } return ownConfig; - function applyExtendedConfig(result: ExtendsResult, extendedConfigPath: string){ + function applyExtendedConfig(result: ExtendsResult, extendedConfigPath: string) { const extendedConfig = getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache, result); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { const extendsRaw = extendedConfig.raw; - let relativeDifference: string | undefined ; + let relativeDifference: string | undefined; const setPropertyInResultIfNotUndefined = (propertyName: "include" | "exclude" | "files") => { if (extendsRaw[propertyName]) { - result[propertyName] = map(extendsRaw[propertyName], (path: string) => isRootedDiskPath(path) ? path : combinePaths( - relativeDifference ||= convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames)), - path - )); + result[propertyName] = map(extendsRaw[propertyName], (path: string) => + isRootedDiskPath(path) ? path : combinePaths( + relativeDifference ||= convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames)), + path, + )); } }; setPropertyInResultIfNotUndefined("include"); @@ -3155,7 +3151,7 @@ function parseOwnConfigOfJson( host: ParseConfigHost, basePath: string, configFileName: string | undefined, - errors: Diagnostic[] + errors: Diagnostic[], ): ParsedTsconfig { if (hasProperty(json, "excludes")) { errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); @@ -3198,14 +3194,17 @@ function getExtendsConfigPathOrArray( for (let index = 0; index < (value as unknown[]).length; index++) { const fileName = (value as unknown[])[index]; if (isString(fileName)) { - extendedConfigPath = append(extendedConfigPath, getExtendsConfigPath( - fileName, - host, - newBase, - errors, - (valueExpression as ArrayLiteralExpression | undefined)?.elements[index], - sourceFile, - )); + extendedConfigPath = append( + extendedConfigPath, + getExtendsConfigPath( + fileName, + host, + newBase, + errors, + (valueExpression as ArrayLiteralExpression | undefined)?.elements[index], + sourceFile, + ), + ); } else { convertJsonOption(extendsOptionDeclaration.element, value, basePath, errors, propertyAssignment, (valueExpression as ArrayLiteralExpression | undefined)?.elements[index], sourceFile); @@ -3223,7 +3222,7 @@ function parseOwnConfigOfJsonSourceFile( host: ParseConfigHost, basePath: string, configFileName: string | undefined, - errors: Diagnostic[] + errors: Diagnostic[], ): ParsedTsconfig { const options = getDefaultCompilerOptions(configFileName); let typeAcquisition: TypeAcquisition | undefined; @@ -3289,7 +3288,7 @@ function parseOwnConfigOfJsonSourceFile( if (keyText === "excludes") { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, propertyAssignment.name, Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - if (find(commandOptionsWithoutBuild, (opt) => opt.name === keyText)) { + if (find(commandOptionsWithoutBuild, opt => opt.name === keyText)) { rootCompilerOptions = append(rootCompilerOptions, propertyAssignment.name); } } @@ -3343,7 +3342,7 @@ function getExtendedConfig( resolutionStack: string[], errors: Diagnostic[], extendedConfigCache: Map | undefined, - result: ExtendsResult + result: ExtendsResult, ): ParsedTsconfig | undefined { const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath); let value: ExtendedConfigCacheEntry | undefined; @@ -3355,8 +3354,7 @@ function getExtendedConfig( else { extendedResult = readJsonConfigFile(extendedConfigPath, path => host.readFile(path)); if (!extendedResult.parseDiagnostics.length) { - extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, getDirectoryPath(extendedConfigPath), - getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); + extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, getDirectoryPath(extendedConfigPath), getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache); } if (extendedConfigCache) { extendedConfigCache.set(path, { extendedResult, extendedConfig }); @@ -3385,13 +3383,13 @@ function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, e return typeof result === "boolean" && result; } -export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } { +export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; } { const errors: Diagnostic[] = []; const options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options, errors }; } -export function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypeAcquisition, errors: Diagnostic[] } { +export function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypeAcquisition; errors: Diagnostic[]; } { const errors: Diagnostic[] = []; const options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); return { options, errors }; @@ -3404,9 +3402,7 @@ function getDefaultCompilerOptions(configFileName?: string) { return options; } -function convertCompilerOptionsFromJsonWorker(jsonOptions: any, - basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions { - +function convertCompilerOptionsFromJsonWorker(jsonOptions: any, basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions { const options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, compilerOptionsDidYouMeanDiagnostics, errors); if (configFileName) { @@ -3419,9 +3415,7 @@ function getDefaultTypeAcquisition(configFileName?: string): TypeAcquisition { return { enable: !!configFileName && getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; } -function convertTypeAcquisitionFromJsonWorker(jsonOptions: any, - basePath: string, errors: Diagnostic[], configFileName?: string): TypeAcquisition { - +function convertTypeAcquisitionFromJsonWorker(jsonOptions: any, basePath: string, errors: Diagnostic[], configFileName?: string): TypeAcquisition { const options = getDefaultTypeAcquisition(configFileName); convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), jsonOptions, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors); return options; @@ -3431,13 +3425,9 @@ function convertWatchOptionsFromJsonWorker(jsonOptions: any, basePath: string, e return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors); } -function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, - defaultOptions: undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]): WatchOptions | undefined; -function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, - defaultOptions: CompilerOptions | TypeAcquisition, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]): CompilerOptions | TypeAcquisition; -function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, - defaultOptions: CompilerOptions | TypeAcquisition | WatchOptions | undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]) { - +function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]): WatchOptions | undefined; +function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: CompilerOptions | TypeAcquisition, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]): CompilerOptions | TypeAcquisition; +function convertOptionsFromJson(optionsNameMap: Map, jsonOptions: any, basePath: string, defaultOptions: CompilerOptions | TypeAcquisition | WatchOptions | undefined, diagnostics: DidYouMeanOptionsDiagnostics, errors: Diagnostic[]) { if (!jsonOptions) { return; } @@ -3533,8 +3523,7 @@ function convertJsonOptionOfCustomType( return validateJsonOptionValue(opt, val, errors, valueExpression, sourceFile); } else { - errors.push(createDiagnosticForInvalidCustomType(opt, (message, ...args) => - createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, message, ...args))); + errors.push(createDiagnosticForInvalidCustomType(opt, (message, ...args) => createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, message, ...args))); } } @@ -3593,7 +3582,7 @@ export function getFileNamesFromConfigSpecs( basePath: string, options: CompilerOptions, host: ParseConfigHost, - extraFileExtensions: readonly FileExtensionInfo[] = emptyArray + extraFileExtensions: readonly FileExtensionInfo[] = emptyArray, ): string[] { basePath = normalizePath(basePath); @@ -3683,7 +3672,7 @@ export function isExcludedFile( spec: ConfigFileSpecs, basePath: string, useCaseSensitiveFileNames: boolean, - currentDirectory: string + currentDirectory: string, ): boolean { const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; @@ -3719,13 +3708,13 @@ export function matchesExclude( pathToCheck: string, excludeSpecs: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, - currentDirectory: string + currentDirectory: string, ) { return matchesExcludeWorker( pathToCheck, filter(excludeSpecs, spec => !invalidDotDotAfterRecursiveWildcard(spec)), useCaseSensitiveFileNames, - currentDirectory + currentDirectory, ); } @@ -3734,7 +3723,7 @@ function matchesExcludeWorker( excludeSpecs: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, - basePath?: string + basePath?: string, ) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames); @@ -3824,7 +3813,7 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu return wildcardDirectories; } -function getWildcardDirectoryFromSpec(spec: string, useCaseSensitiveFileNames: boolean): { key: string, flags: WatchDirectoryFlags } | undefined { +function getWildcardDirectoryFromSpec(spec: string, useCaseSensitiveFileNames: boolean): { key: string; flags: WatchDirectoryFlags; } | undefined { const match = wildcardDirectoryPattern.exec(spec); if (match) { // We check this with a few `indexOf` calls because 3 `indexOf`/`lastIndexOf` calls is @@ -3837,14 +3826,14 @@ function getWildcardDirectoryFromSpec(spec: string, useCaseSensitiveFileNames: b return { key: useCaseSensitiveFileNames ? match[0] : toFileNameLowerCase(match[0]), flags: (questionWildcardIndex !== -1 && questionWildcardIndex < lastDirectorySeperatorIndex) - || (starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex) - ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None + || (starWildcardIndex !== -1 && starWildcardIndex < lastDirectorySeperatorIndex) + ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None, }; } if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) { return { key: removeTrailingDirectorySeparator(useCaseSensitiveFileNames ? spec : toFileNameLowerCase(spec)), - flags: WatchDirectoryFlags.Recursive + flags: WatchDirectoryFlags.Recursive, }; } return undefined; @@ -3946,7 +3935,6 @@ function getOptionValueWithEmptyStrings(value: any, option: CommandLineOption): } } - function getDefaultValueForOption(option: CommandLineOption): {} { switch (option.type) { case "number": diff --git a/src/compiler/core.ts b/src/compiler/core.ts index f5d60b0459141..340b49b134aa3 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -13,7 +13,6 @@ import { TextSpan, } from "./_namespaces/ts"; - /** @internal */ export const emptyArray: never[] = [] as never[]; /** @internal */ @@ -352,9 +351,8 @@ export function map(array: readonly T[] | undefined, f: (x: T, i: number) return result; } - /** @internal */ -export function *mapIterator(iter: Iterable, mapFn: (x: T) => U) { +export function* mapIterator(iter: Iterable, mapFn: (x: T) => U) { for (const x of iter) { yield mapFn(x); } @@ -412,7 +410,6 @@ export function flatten(array: T[][] | readonly (T | readonly T[] | undefined return result; } - /** * Maps an array. If the mapped value is an array, it is spread into the result. * @@ -459,7 +456,7 @@ export function flatMapToMutable(array: readonly T[] | undefined, mapfn: ( } /** @internal */ -export function *flatMapIterator(iter: Iterable, mapfn: (x: T) => readonly U[] | Iterable | undefined) { +export function* flatMapIterator(iter: Iterable, mapfn: (x: T) => readonly U[] | Iterable | undefined) { for (const x of iter) { const iter2 = mapfn(x); if (!iter2) continue; @@ -467,7 +464,6 @@ export function *flatMapIterator(iter: Iterable, mapfn: (x: T) => reado } } - /** * Maps an array. If the mapped value is an array, it is spread into the result. * Avoids allocation if all elements map to themselves. @@ -531,7 +527,7 @@ export function mapDefined(array: readonly T[] | undefined, mapFn: (x: T, } /** @internal */ -export function *mapDefinedIterator(iter: Iterable, mapFn: (x: T) => U | undefined) { +export function* mapDefinedIterator(iter: Iterable, mapFn: (x: T) => U | undefined) { for (const x of iter) { const value = mapFn(x); if (value !== undefined) { @@ -584,7 +580,7 @@ export function tryAddToSet(set: Set, value: T) { } /** @internal */ -export function *singleIterator(value: T) { +export function* singleIterator(value: T) { yield value; } @@ -947,13 +943,15 @@ export function compact(array: readonly T[]): readonly T[] { export function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: Comparer): T[] | undefined { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; const result: T[] = []; - loopB: for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + loopB: + for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { if (offsetB > 0) { // Ensure `arrayB` is properly sorted. Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), Comparison.EqualTo); } - loopA: for (const startA = offsetA; offsetA < arrayA.length; offsetA++) { + loopA: + for (const startA = offsetA; offsetA < arrayA.length; offsetA++) { if (offsetA > startA) { // Ensure `arrayA` is properly sorted. We only need to perform this check if // `offsetA` has changed since we entered the loop. @@ -1119,7 +1117,7 @@ export function sort(array: readonly T[], comparer?: Comparer): SortedRead } /** @internal */ -export function *arrayReverseIterator(array: readonly T[]) { +export function* arrayReverseIterator(array: readonly T[]) { for (let i = array.length - 1; i >= 0; i--) { yield array[i]; } @@ -1393,7 +1391,8 @@ export function getAllKeys(obj: object): string[] { for (const name of names) { pushIfUnique(result, name); } - } while (obj = Object.getPrototypeOf(obj)); + } + while (obj = Object.getPrototypeOf(obj)); return result; } @@ -1544,7 +1543,7 @@ export function group(values: readonly T[], getGroupId: (value: T) => K, r } /** @internal */ -export function groupBy(values: readonly T[] | undefined, keySelector: (value: T) => value is U): { true?: U[], false?: Exclude[] }; +export function groupBy(values: readonly T[] | undefined, keySelector: (value: T) => value is U): { true?: U[]; false?: Exclude[]; }; /** @internal */ export function groupBy(values: readonly T[] | undefined, keySelector: (value: T) => K): { [P in K as `${P}`]?: T[]; }; export function groupBy(values: readonly T[] | undefined, keySelector: (value: T) => K): { [P in K as `${P}`]?: T[]; } { @@ -1708,7 +1707,7 @@ export function createSet(getHashCode: (element: TElem const multiMap = new Map(); let size = 0; - function *getElementIterator(): IterableIterator { + function* getElementIterator(): IterableIterator { for (const value of multiMap.values()) { if (isArray(value)) { yield* value; @@ -1746,7 +1745,7 @@ export function createSet(getHashCode: (element: TElem else { const value = values; if (!equals(value, element)) { - multiMap.set(hash, [ value, element ]); + multiMap.set(hash, [value, element]); size++; } } @@ -1879,7 +1878,7 @@ export function cast(value: TIn | undefined, test: * * @internal */ -export function noop(_?: unknown): void { } +export function noop(_?: unknown): void {} /** * Do nothing and return false @@ -2119,8 +2118,8 @@ export function equateValues(a: T, b: T) { export function equateStringsCaseInsensitive(a: string, b: string) { return a === b || a !== undefined - && b !== undefined - && a.toUpperCase() === b.toUpperCase(); + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); } /** @@ -2301,9 +2300,11 @@ const createUIStringComparer = (() => { // If the host does not support Intl, we fall back to localeCompare. // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. - if (typeof String.prototype.localeCompare === "function" && + if ( + typeof String.prototype.localeCompare === "function" && typeof String.prototype.toLocaleUpperCase === "function" && - "a".localeCompare("B") < 0) { + "a".localeCompare("B") < 0 + ) { return createLocaleCompareStringComparer; } @@ -2367,7 +2368,6 @@ export function compareProperties(a: T | un comparer(a[key], b[key]); } - /** * True is greater than false. * @@ -2442,7 +2442,7 @@ function levenshteinWithMax(s1: string, s2: string, max: number): number | undef } for (let j = minJ; j <= maxJ; j++) { // case difference should be significantly cheaper than other differences - const substitutionDistance = s1[i - 1].toLowerCase() === s2[j-1].toLowerCase() + const substitutionDistance = s1[i - 1].toLowerCase() === s2[j - 1].toLowerCase() ? (previous[j - 1] + 0.1) : (previous[j - 1] + 2); const dist = c1 === s2.charCodeAt(j - 1) @@ -2508,7 +2508,8 @@ export function removeMinAndVersionNumbers(fileName: string) { do { --pos; ch = fileName.charCodeAt(pos); - } while (pos > 0 && ch >= CharacterCodes._0 && ch <= CharacterCodes._9); + } + while (pos > 0 && ch >= CharacterCodes._0 && ch <= CharacterCodes._9); } else if (pos > 4 && (ch === CharacterCodes.n || ch === CharacterCodes.N)) { // Looking for "min" or "min" @@ -2704,7 +2705,7 @@ export function not(fn: (...args: T) => boolean): (...args: } /** @internal */ -export function assertType(_: T): void { } +export function assertType(_: T): void {} /** @internal */ export function singleElementArray(t: T | undefined): T[] | undefined { @@ -2776,7 +2777,6 @@ function cartesianProductWorker(arrays: readonly (readonly T[])[], result: (r } } - /** * Returns string left-padded with spaces or zeros until it reaches the given length. * diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index 9ae5e9b94db4f..c026d2c741f79 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -52,7 +52,7 @@ export type Comparer = (a: T, b: T) => Comparison; /** @internal */ export const enum Comparison { - LessThan = -1, - EqualTo = 0, - GreaterThan = 1 + LessThan = -1, + EqualTo = 0, + GreaterThan = 1, } diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index 21d7fa6129bb1..7b5a81d93a89d 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -100,7 +100,7 @@ export enum LogLevel { Error, Warning, Info, - Verbose + Verbose, } /** @internal */ @@ -151,7 +151,7 @@ export namespace Debug { } } - const assertionCache: Partial> = {}; + const assertionCache: Partial> = {}; export function getAssertionLevel() { return currentAssertionLevel; @@ -205,7 +205,8 @@ export namespace Debug { export function failBadSyntaxKind(node: Node, message?: string, stackCrawlMark?: AnyFunction): never { return fail( `${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`, - stackCrawlMark || failBadSyntaxKind); + stackCrawlMark || failBadSyntaxKind, + ); } export function assert(expression: unknown, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): asserts expression { @@ -284,7 +285,8 @@ export namespace Debug { test === undefined || every(nodes, test), message || "Unexpected node.", () => `Node array did not pass test '${getFunctionName(test!)}'.`, - stackCrawlMark || assertEachNode); + stackCrawlMark || assertEachNode, + ); } } @@ -296,7 +298,8 @@ export namespace Debug { node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", () => `Node ${formatSyntaxKind(node?.kind)} did not pass test '${getFunctionName(test!)}'.`, - stackCrawlMark || assertNode); + stackCrawlMark || assertNode, + ); } } @@ -308,7 +311,8 @@ export namespace Debug { node === undefined || test === undefined || !test(node), message || "Unexpected node.", () => `Node ${formatSyntaxKind(node!.kind)} should not have passed test '${getFunctionName(test!)}'.`, - stackCrawlMark || assertNotNode); + stackCrawlMark || assertNotNode, + ); } } @@ -321,12 +325,13 @@ export namespace Debug { test === undefined || node === undefined || test(node), message || "Unexpected node.", () => `Node ${formatSyntaxKind(node?.kind)} did not pass test '${getFunctionName(test!)}'.`, - stackCrawlMark || assertOptionalNode); + stackCrawlMark || assertOptionalNode, + ); } } - export function assertOptionalToken(node: T, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract; - export function assertOptionalToken(node: T | undefined, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract | undefined; + export function assertOptionalToken(node: T, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract; + export function assertOptionalToken(node: T | undefined, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract | undefined; export function assertOptionalToken(node: Node | undefined, kind: SyntaxKind | undefined, message?: string, stackCrawlMark?: AnyFunction): void; export function assertOptionalToken(node: Node | undefined, kind: SyntaxKind | undefined, message?: string, stackCrawlMark?: AnyFunction) { if (shouldAssertFunction(AssertionLevel.Normal, "assertOptionalToken")) { @@ -334,7 +339,8 @@ export namespace Debug { kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node?.kind)} was not a '${formatSyntaxKind(kind)}' token.`, - stackCrawlMark || assertOptionalToken); + stackCrawlMark || assertOptionalToken, + ); } } @@ -345,7 +351,8 @@ export namespace Debug { node === undefined, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node!.kind)} was unexpected'.`, - stackCrawlMark || assertMissingNode); + stackCrawlMark || assertMissingNode, + ); } } @@ -355,7 +362,7 @@ export namespace Debug { * as a result can reduce the number of unnecessary casts. */ export function type(value: unknown): asserts value is T; - export function type(_value: unknown) { } + export function type(_value: unknown) {} export function getFunctionName(func: AnyFunction) { if (typeof func !== "function") { @@ -507,8 +514,7 @@ export namespace Debug { // for use with vscode-js-debug's new customDescriptionGenerator in launch.json __tsDebuggerDisplay: { value(this: FlowNodeBase) { - const flowHeader = - this.flags & FlowFlags.Start ? "FlowStart" : + const flowHeader = this.flags & FlowFlags.Start ? "FlowStart" : this.flags & FlowFlags.BranchLabel ? "FlowBranchLabel" : this.flags & FlowFlags.LoopLabel ? "FlowLoopLabel" : this.flags & FlowFlags.Assignment ? "FlowAssignment" : @@ -521,11 +527,19 @@ export namespace Debug { this.flags & FlowFlags.Unreachable ? "FlowUnreachable" : "UnknownFlow"; const remainingFlags = this.flags & ~(FlowFlags.Referenced - 1); - return `${flowHeader}${remainingFlags ? ` (${formatFlowFlags(remainingFlags)})`: ""}`; - } + return `${flowHeader}${remainingFlags ? ` (${formatFlowFlags(remainingFlags)})` : ""}`; + }, + }, + __debugFlowFlags: { + get(this: FlowNodeBase) { + return formatEnum(this.flags, (ts as any).FlowFlags, /*isFlags*/ true); + }, + }, + __debugToString: { + value(this: FlowNodeBase) { + return formatControlFlowGraph(this); + }, }, - __debugFlowFlags: { get(this: FlowNodeBase) { return formatEnum(this.flags, (ts as any).FlowFlags, /*isFlags*/ true); } }, - __debugToString: { value(this: FlowNodeBase) { return formatControlFlowGraph(this); } } }); } } @@ -563,8 +577,8 @@ export namespace Debug { // we're just taking note of it for anyone checking regex performance in the future. defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]"); return `NodeArray ${defaultValue}`; - } - } + }, + }, }); } } @@ -602,22 +616,24 @@ export namespace Debug { // for use with vscode-js-debug's new customDescriptionGenerator in launch.json __tsDebuggerDisplay: { value(this: Symbol) { - const symbolHeader = - this.flags & SymbolFlags.Transient ? "TransientSymbol" : + const symbolHeader = this.flags & SymbolFlags.Transient ? "TransientSymbol" : "Symbol"; const remainingSymbolFlags = this.flags & ~SymbolFlags.Transient; return `${symbolHeader} '${symbolName(this)}'${remainingSymbolFlags ? ` (${formatSymbolFlags(remainingSymbolFlags)})` : ""}`; - } + }, + }, + __debugFlags: { + get(this: Symbol) { + return formatSymbolFlags(this.flags); + }, }, - __debugFlags: { get(this: Symbol) { return formatSymbolFlags(this.flags); } } }); Object.defineProperties(objectAllocator.getTypeConstructor().prototype, { // for use with vscode-js-debug's new customDescriptionGenerator in launch.json __tsDebuggerDisplay: { value(this: Type) { - const typeHeader = - this.flags & TypeFlags.Nullable ? "NullableType" : + const typeHeader = this.flags & TypeFlags.Nullable ? "NullableType" : this.flags & TypeFlags.StringOrNumberLiteral ? `LiteralType ${JSON.stringify((this as LiteralType).value)}` : this.flags & TypeFlags.BigIntLiteral ? `LiteralType ${(this as BigIntLiteralType).value.negative ? "-" : ""}${(this as BigIntLiteralType).value.base10Value}n` : this.flags & TypeFlags.UniqueESSymbol ? "UniqueESSymbolType" : @@ -631,7 +647,7 @@ export namespace Debug { this.flags & TypeFlags.Substitution ? "SubstitutionType" : this.flags & TypeFlags.TypeParameter ? "TypeParameter" : this.flags & TypeFlags.Object ? - (this as ObjectType).objectFlags & ObjectFlags.ClassOrInterface ? "InterfaceType" : + (this as ObjectType).objectFlags & ObjectFlags.ClassOrInterface ? "InterfaceType" : (this as ObjectType).objectFlags & ObjectFlags.Reference ? "TypeReference" : (this as ObjectType).objectFlags & ObjectFlags.Tuple ? "TupleType" : (this as ObjectType).objectFlags & ObjectFlags.Anonymous ? "AnonymousType" : @@ -642,10 +658,18 @@ export namespace Debug { "Type"; const remainingObjectFlags = this.flags & TypeFlags.Object ? (this as ObjectType).objectFlags & ~ObjectFlags.ObjectTypeKindMask : 0; return `${typeHeader}${this.symbol ? ` '${symbolName(this.symbol)}'` : ""}${remainingObjectFlags ? ` (${formatObjectFlags(remainingObjectFlags)})` : ""}`; - } + }, + }, + __debugFlags: { + get(this: Type) { + return formatTypeFlags(this.flags); + }, + }, + __debugObjectFlags: { + get(this: Type) { + return this.flags & TypeFlags.Object ? formatObjectFlags((this as ObjectType).objectFlags) : ""; + }, }, - __debugFlags: { get(this: Type) { return formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((this as ObjectType).objectFlags) : ""; } }, __debugTypeToString: { value(this: Type) { // avoid recomputing @@ -655,20 +679,28 @@ export namespace Debug { weakTypeTextMap.set(this, text); } return text; - } + }, }, }); Object.defineProperties(objectAllocator.getSignatureConstructor().prototype, { - __debugFlags: { get(this: Signature) { return formatSignatureFlags(this.flags); } }, - __debugSignatureToString: { value(this: Signature) { return this.checker?.signatureToString(this); } } + __debugFlags: { + get(this: Signature) { + return formatSignatureFlags(this.flags); + }, + }, + __debugSignatureToString: { + value(this: Signature) { + return this.checker?.signatureToString(this); + }, + }, }); const nodeConstructors = [ objectAllocator.getNodeConstructor(), objectAllocator.getIdentifierConstructor(), objectAllocator.getTokenConstructor(), - objectAllocator.getSourceFileConstructor() + objectAllocator.getSourceFileConstructor(), ]; for (const ctor of nodeConstructors) { @@ -677,8 +709,7 @@ export namespace Debug { // for use with vscode-js-debug's new customDescriptionGenerator in launch.json __tsDebuggerDisplay: { value(this: Node) { - const nodeHeader = - isGeneratedIdentifier(this) ? "GeneratedIdentifier" : + const nodeHeader = isGeneratedIdentifier(this) ? "GeneratedIdentifier" : isIdentifier(this) ? `Identifier '${idText(this)}'` : isPrivateIdentifier(this) ? `PrivateIdentifier '${idText(this)}'` : isStringLiteral(this) ? `StringLiteral ${JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...")}` : @@ -716,14 +747,38 @@ export namespace Debug { isImportTypeNode(this) ? "ImportTypeNode" : formatSyntaxKind(this.kind); return `${nodeHeader}${this.flags ? ` (${formatNodeFlags(this.flags)})` : ""}`; - } + }, + }, + __debugKind: { + get(this: Node) { + return formatSyntaxKind(this.kind); + }, + }, + __debugNodeFlags: { + get(this: Node) { + return formatNodeFlags(this.flags); + }, + }, + __debugModifierFlags: { + get(this: Node) { + return formatModifierFlags(getEffectiveModifierFlagsNoCache(this)); + }, + }, + __debugTransformFlags: { + get(this: Node) { + return formatTransformFlags(this.transformFlags); + }, + }, + __debugIsParseTreeNode: { + get(this: Node) { + return isParseTreeNode(this); + }, + }, + __debugEmitFlags: { + get(this: Node) { + return formatEmitFlags(getEmitFlags(this)); + }, }, - __debugKind: { get(this: Node) { return formatSyntaxKind(this.kind); } }, - __debugNodeFlags: { get(this: Node) { return formatNodeFlags(this.flags); } }, - __debugModifierFlags: { get(this: Node) { return formatModifierFlags(getEffectiveModifierFlagsNoCache(this)); } }, - __debugTransformFlags: { get(this: Node) { return formatTransformFlags(this.transformFlags); } }, - __debugIsParseTreeNode: { get(this: Node) { return isParseTreeNode(this); } }, - __debugEmitFlags: { get(this: Node) { return formatEmitFlags(getEmitFlags(this)); } }, __debugGetText: { value(this: Node, includeTrivia?: boolean) { if (nodeIsSynthesized(this)) return ""; @@ -736,8 +791,8 @@ export namespace Debug { weakNodeTextMap.set(this, text); } return text; - } - } + }, + }, }); } } @@ -747,8 +802,7 @@ export namespace Debug { export function formatVariance(varianceFlags: VarianceFlags) { const variance = varianceFlags & VarianceFlags.VarianceMask; - let result = - variance === VarianceFlags.Invariant ? "in out" : + let result = variance === VarianceFlags.Invariant ? "in out" : variance === VarianceFlags.Bivariant ? "[bivariant]" : variance === VarianceFlags.Contravariant ? "in" : variance === VarianceFlags.Covariant ? "out" : @@ -762,26 +816,34 @@ export namespace Debug { return result; } - export type DebugType = Type & { __debugTypeToString(): string }; // eslint-disable-line @typescript-eslint/naming-convention + export type DebugType = Type & { __debugTypeToString(): string; }; // eslint-disable-line @typescript-eslint/naming-convention export class DebugTypeMapper { declare kind: TypeMapKind; __debugToString(): string { // eslint-disable-line @typescript-eslint/naming-convention type(this); switch (this.kind) { - case TypeMapKind.Function: return this.debugInfo?.() || "(function mapper)"; - case TypeMapKind.Simple: return `${(this.source as DebugType).__debugTypeToString()} -> ${(this.target as DebugType).__debugTypeToString()}`; - case TypeMapKind.Array: return zipWith( - this.sources as readonly DebugType[], - this.targets as readonly DebugType[] || map(this.sources, () => "any"), - (s, t) => `${s.__debugTypeToString()} -> ${typeof t === "string" ? t : t.__debugTypeToString()}`).join(", "); - case TypeMapKind.Deferred: return zipWith( - this.sources, - this.targets, - (s, t) => `${(s as DebugType).__debugTypeToString()} -> ${(t() as DebugType).__debugTypeToString()}`).join(", "); + case TypeMapKind.Function: + return this.debugInfo?.() || "(function mapper)"; + case TypeMapKind.Simple: + return `${(this.source as DebugType).__debugTypeToString()} -> ${(this.target as DebugType).__debugTypeToString()}`; + case TypeMapKind.Array: + return zipWith( + this.sources as readonly DebugType[], + this.targets as readonly DebugType[] || map(this.sources, () => "any"), + (s, t) => `${s.__debugTypeToString()} -> ${typeof t === "string" ? t : t.__debugTypeToString()}`, + ).join(", "); + case TypeMapKind.Deferred: + return zipWith( + this.sources, + this.targets, + (s, t) => `${(s as DebugType).__debugTypeToString()} -> ${(t() as DebugType).__debugTypeToString()}`, + ).join(", "); case TypeMapKind.Merged: - case TypeMapKind.Composite: return `m1: ${(this.mapper1 as unknown as DebugTypeMapper).__debugToString().split("\n").join("\n ")} + case TypeMapKind.Composite: + return `m1: ${(this.mapper1 as unknown as DebugTypeMapper).__debugToString().split("\n").join("\n ")} m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n").join("\n ")}`; - default: return assertNever(this); + default: + return assertNever(this); } } } @@ -860,16 +922,14 @@ m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n") target: FlowGraphNode; } - const hasAntecedentFlags = - FlowFlags.Assignment | + const hasAntecedentFlags = FlowFlags.Assignment | FlowFlags.Condition | FlowFlags.SwitchClause | FlowFlags.ArrayMutation | FlowFlags.Call | FlowFlags.ReduceLabel; - const hasNodeFlags = - FlowFlags.Start | + const hasNodeFlags = FlowFlags.Start | FlowFlags.Assignment | FlowFlags.Call | FlowFlags.Condition | @@ -893,15 +953,15 @@ m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n") return !!(f.flags & FlowFlags.SwitchClause); } - function hasAntecedents(f: FlowNode): f is FlowLabel & { antecedents: FlowNode[] } { + function hasAntecedents(f: FlowNode): f is FlowLabel & { antecedents: FlowNode[]; } { return !!(f.flags & FlowFlags.Label) && !!(f as FlowLabel).antecedents; } - function hasAntecedent(f: FlowNode): f is Extract { + function hasAntecedent(f: FlowNode): f is Extract { return !!(f.flags & hasAntecedentFlags); } - function hasNode(f: FlowNode): f is Extract { + function hasNode(f: FlowNode): f is Extract { return !!(f.flags & hasNodeFlags); } @@ -938,7 +998,7 @@ m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n") lane: -1, endLane: -1, level: -1, - circular: "circularity" + circular: "circularity", }; nodes.push(graphNode); return graphNode; @@ -1135,17 +1195,28 @@ m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n") function getBoxCharacter(connector: Connection) { switch (connector) { - case Connection.UpDown: return BoxCharacter.ud; - case Connection.LeftRight: return BoxCharacter.lr; - case Connection.UpLeft: return BoxCharacter.ul; - case Connection.UpRight: return BoxCharacter.ur; - case Connection.DownLeft: return BoxCharacter.dl; - case Connection.DownRight: return BoxCharacter.dr; - case Connection.UpDownLeft: return BoxCharacter.udl; - case Connection.UpDownRight: return BoxCharacter.udr; - case Connection.UpLeftRight: return BoxCharacter.ulr; - case Connection.DownLeftRight: return BoxCharacter.dlr; - case Connection.UpDownLeftRight: return BoxCharacter.udlr; + case Connection.UpDown: + return BoxCharacter.ud; + case Connection.LeftRight: + return BoxCharacter.lr; + case Connection.UpLeft: + return BoxCharacter.ul; + case Connection.UpRight: + return BoxCharacter.ur; + case Connection.DownLeft: + return BoxCharacter.dl; + case Connection.DownRight: + return BoxCharacter.dr; + case Connection.UpDownLeft: + return BoxCharacter.udl; + case Connection.UpDownRight: + return BoxCharacter.udr; + case Connection.UpLeftRight: + return BoxCharacter.ulr; + case Connection.DownLeftRight: + return BoxCharacter.dlr; + case Connection.UpDownLeftRight: + return BoxCharacter.udlr; } return " "; } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 228c58bb8a856..d407dadc246ae 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -483,11 +483,13 @@ export function isBuildInfoFile(file: string) { * @internal */ export function forEachEmittedFile( - host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle | undefined) => T, + host: EmitHost, + action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle | undefined) => T, sourceFilesOrTargetSourceFile?: readonly SourceFile[] | SourceFile, forceDtsEmit = false, onlyBuildInfo?: boolean, - includeBuildInfo?: boolean) { + includeBuildInfo?: boolean, +) { const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit); const options = host.getCompilerOptions(); if (outFile(options)) { @@ -575,17 +577,17 @@ function getSourceMapFilePath(jsFilePath: string, options: CompilerOptions) { /** @internal */ export function getOutputExtension(fileName: string, options: CompilerOptions): Extension { return fileExtensionIs(fileName, Extension.Json) ? Extension.Json : - options.jsx === JsxEmit.Preserve && fileExtensionIsOneOf(fileName, [Extension.Jsx, Extension.Tsx]) ? Extension.Jsx : - fileExtensionIsOneOf(fileName, [Extension.Mts, Extension.Mjs]) ? Extension.Mjs : - fileExtensionIsOneOf(fileName, [Extension.Cts, Extension.Cjs]) ? Extension.Cjs : - Extension.Js; + options.jsx === JsxEmit.Preserve && fileExtensionIsOneOf(fileName, [Extension.Jsx, Extension.Tsx]) ? Extension.Jsx : + fileExtensionIsOneOf(fileName, [Extension.Mts, Extension.Mjs]) ? Extension.Mjs : + fileExtensionIsOneOf(fileName, [Extension.Cts, Extension.Cjs]) ? Extension.Cjs : + Extension.Js; } function getOutputPathWithoutChangingExt(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, outputDir: string | undefined, getCommonSourceDirectory?: () => string) { return outputDir ? resolvePath( outputDir, - getRelativePathFromDirectory(getCommonSourceDirectory ? getCommonSourceDirectory() : getCommonSourceDirectoryOfConfig(configFile, ignoreCase), inputFileName, ignoreCase) + getRelativePathFromDirectory(getCommonSourceDirectory ? getCommonSourceDirectory() : getCommonSourceDirectoryOfConfig(configFile, ignoreCase), inputFileName, ignoreCase), ) : inputFileName; } @@ -594,7 +596,7 @@ function getOutputPathWithoutChangingExt(inputFileName: string, configFile: Pars export function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, getCommonSourceDirectory?: () => string) { return changeExtension( getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir, getCommonSourceDirectory), - getDeclarationEmitExtensionForPath(inputFileName) + getDeclarationEmitExtensionForPath(inputFileName), ); } @@ -603,7 +605,7 @@ function getOutputJSFileName(inputFileName: string, configFile: ParsedCommandLin const isJsonFile = fileExtensionIs(inputFileName, Extension.Json); const outputFileName = changeExtension( getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir, getCommonSourceDirectory), - getOutputExtension(inputFileName, configFile.options) + getOutputExtension(inputFileName, configFile.options), ); return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== Comparison.EqualTo ? outputFileName : @@ -655,7 +657,7 @@ export function getCommonSourceDirectory( emittedFiles: () => readonly string[], currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, - checkSourceFilesBelongToPath?: (commonSourceDirectory: string) => void + checkSourceFilesBelongToPath?: (commonSourceDirectory: string) => void, ): string { let commonSourceDirectory; if (options.rootDir) { @@ -687,7 +689,7 @@ export function getCommonSourceDirectoryOfConfig({ options, fileNames }: ParsedC options, () => filter(fileNames, file => !(options.noEmitForJsFiles && fileExtensionIsOneOf(file, supportedJSExtensionsFlat)) && !isDeclarationFileName(file)), getDirectoryPath(normalizeSlashes(Debug.checkDefined(options.configFilePath))), - createGetCanonicalFileName(!ignoreCase) + createGetCanonicalFileName(!ignoreCase), ); } @@ -767,11 +769,10 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, - !targetSourceFile + !targetSourceFile, ); exit(); - return { emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -785,7 +786,7 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); bundleBuildInfo = { commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()), - sourceFiles: sourceFileOrBundle.sourceFiles.map(file => relativeToBuildInfo(getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()))) + sourceFiles: sourceFileOrBundle.sourceFiles.map(file => relativeToBuildInfo(getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()))), }; } tracing?.push(tracing.Phase.Emit, "emitJsFileOrBundle", { jsFilePath }); @@ -843,7 +844,8 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi sourceFileOrBundle: SourceFile | Bundle | undefined, jsFilePath: string | undefined, sourceMapFilePath: string | undefined, - relativeToBuildInfo: (path: string) => string) { + relativeToBuildInfo: (path: string) => string, + ) { if (!sourceFileOrBundle || emitOnly || !jsFilePath) { return; } @@ -867,7 +869,7 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi inlineSources: compilerOptions.inlineSources, extendedDiagnostics: compilerOptions.extendedDiagnostics, writeBundleFileInfo: !!bundleBuildInfo, - relativeToBuildInfo + relativeToBuildInfo, }; // Create a printer to print the nodes @@ -893,7 +895,8 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi sourceFileOrBundle: SourceFile | Bundle | undefined, declarationFilePath: string | undefined, declarationMapPath: string | undefined, - relativeToBuildInfo: (path: string) => string) { + relativeToBuildInfo: (path: string) => string, + ) { if (!sourceFileOrBundle || emitOnly === EmitOnly.Js) return; if (!declarationFilePath) { if (emitOnly || compilerOptions.emitDeclarationOnly) emitSkipped = true; @@ -927,7 +930,7 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi onlyPrintJsDocStyle: true, writeBundleFileInfo: !!bundleBuildInfo, recordInternalSection: !!bundleBuildInfo, - relativeToBuildInfo + relativeToBuildInfo, }; const declarationPrinter = createPrinter(printerOptions, { @@ -954,7 +957,7 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, // Explicitly do not passthru either `inline` option - } + }, ); } declarationTransform.dispose(); @@ -988,7 +991,8 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi getBaseFileName(normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), - mapOptions); + mapOptions, + ); } if (bundle) { @@ -1003,7 +1007,7 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi if (sourceMapDataList) { sourceMapDataList.push({ inputSourceFileNames: sourceMapGenerator.getSources(), - sourceMap: sourceMapGenerator.toJSON() + sourceMap: sourceMapGenerator.toJSON(), }); } @@ -1012,7 +1016,8 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi sourceMapGenerator, jsFilePath, sourceMapFilePath, - sourceFile); + sourceFile, + ); if (sourceMappingURL) { if (!writer.isAtStartOfLine()) writer.rawWrite(newLine); @@ -1106,7 +1111,9 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true)); + /*isAbsolutePathAnUrl*/ true, + ), + ); } else { return encodeURI(combinePaths(sourceMapDir, sourceMapFile)); @@ -1201,7 +1208,7 @@ function createSourceFilesFromBundleBuildInfo(bundle: BundleBuildInfo, buildInfo sourceFile.fileName = getRelativePathFromDirectory( host.getCurrentDirectory(), getNormalizedAbsolutePath(fileName, buildInfoDirectory), - !host.useCaseSensitiveFileNames() + !host.useCaseSensitiveFileNames(), ); sourceFile.text = prologueInfo?.text ?? ""; setTextRangePosWidth(sourceFile, 0, prologueInfo?.text.length ?? 0); @@ -1217,7 +1224,7 @@ export function emitUsingBuildInfo( config: ParsedCommandLine, host: CompilerHost, getCommandLine: (ref: ProjectReference) => ParsedCommandLine | undefined, - customTransformers?: CustomTransformers + customTransformers?: CustomTransformers, ): EmitUsingBuildInfoResult { tracing?.push(tracing.Phase.Emit, "emitUsingBuildInfo", {}, /*separateBeginAndEnd*/ true); performance.mark("beforeEmit"); @@ -1232,7 +1239,7 @@ function emitUsingBuildInfoWorker( config: ParsedCommandLine, host: CompilerHost, getCommandLine: (ref: ProjectReference) => ParsedCommandLine | undefined, - customTransformers?: CustomTransformers + customTransformers?: CustomTransformers, ): EmitUsingBuildInfoResult { const { buildInfoPath, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false); // If host directly provides buildinfo we can get it directly. This allows host to cache the buildinfo @@ -1270,7 +1277,7 @@ function emitUsingBuildInfoWorker( declarationMapText, buildInfoPath, buildInfo, - /*oldFileOfCurrentEmit*/ true + /*oldFileOfCurrentEmit*/ true, ); const outputFiles: OutputFile[] = []; const prependNodes = createPrependNodes(config.projectReferences, getCommandLine, f => host.readFile(f), host); @@ -1342,7 +1349,7 @@ function emitUsingBuildInfoWorker( notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, - getTransformers(config.options, customTransformers) + getTransformers(config.options, customTransformers), ); return outputFiles; } @@ -1381,7 +1388,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri onBeforeEmitNodeArray, onAfterEmitNodeArray, onBeforeEmitToken, - onAfterEmitToken + onAfterEmitToken, } = handlers; var extendedDiagnostics = !!printerOptions.extendedDiagnostics; @@ -1430,7 +1437,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri var containerEnd = -1; var declarationListContainerEnd = -1; var currentLineMap: readonly number[] | undefined; - var detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number }[] | undefined; + var detachedCommentsInfo: { nodePos: number; detachedCommentEndPos: number; }[] | undefined; var hasWrittenComment = false; var commentsDisabled = !!printerOptions.removeComments; var lastSubstitution: Node | undefined; @@ -1438,7 +1445,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri var { enter: enterComment, exit: exitComment } = performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"); var parenthesizer = factory.parenthesizer; var typeArgumentParenthesizerRuleSelector: OrdinalParentheizerRuleSelector = { - select: index => index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : undefined + select: index => index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : undefined, }; var emitBinaryExpression = createEmitBinaryExpression(); /* eslint-enable no-var */ @@ -1456,7 +1463,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri writeList, writeFile, writeBundle, - bundleFileInfo + bundleFileInfo, }; function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string { @@ -1472,9 +1479,12 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri break; } switch (node.kind) { - case SyntaxKind.SourceFile: return printFile(node as SourceFile); - case SyntaxKind.Bundle: return printBundle(node as Bundle); - case SyntaxKind.UnparsedSource: return printUnparsedSource(node as UnparsedSource); + case SyntaxKind.SourceFile: + return printFile(node as SourceFile); + case SyntaxKind.Bundle: + return printBundle(node as Bundle); + case SyntaxKind.UnparsedSource: + return printUnparsedSource(node as UnparsedSource); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -1539,12 +1549,14 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri } function recordBundleFileInternalSectionStart(node: Node) { - if (recordInternalSection && + if ( + recordInternalSection && bundleFileInfo && currentSourceFile && (isDeclaration(node) || isVariableStatement(node)) && isInternalDeclaration(node, currentSourceFile) && - sourceFileTextKind !== BundleFileSectionKind.Internal) { + sourceFileTextKind !== BundleFileSectionKind.Internal + ) { const prevSourceFileTextKind = sourceFileTextKind; recordBundleFileTextLikeSection(writer.getTextPos()); sourceFileTextPos = getTextPosWithWriteLine(); @@ -1596,7 +1608,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri end: writer.getTextPos(), kind: BundleFileSectionKind.Prepend, data: relativeToBuildInfo!((prepend as UnparsedSource).fileName), - texts: newSections as BundleFileTextLike[] + texts: newSections as BundleFileTextLike[], }); } } @@ -2422,8 +2434,10 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri // SyntaxKind.TemplateTail function emitLiteral(node: LiteralLikeNode, jsxAttributeEscape: boolean) { const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape); - if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) - && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) { + if ( + (printerOptions.sourceMap || printerOptions.inlineSourceMap) + && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind)) + ) { writeLiteral(text); } else { @@ -2460,7 +2474,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri writer.getTextPos(), unparsed.kind === SyntaxKind.UnparsedText ? BundleFileSectionKind.Text : - BundleFileSectionKind.Internal + BundleFileSectionKind.Internal, ); } } @@ -2501,10 +2515,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri function emitTabStop(hint: EmitHint, node: Node, snippet: TabStop) { // A tab stop should only be attached to an empty node, i.e. a node that doesn't emit any text. - Debug.assert(node.kind === SyntaxKind.EmptyStatement, - `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.`); - Debug.assert(hint !== EmitHint.EmbeddedStatement, - `A tab stop cannot be attached to an embedded statement.`); + Debug.assert(node.kind === SyntaxKind.EmptyStatement, `A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.`); + Debug.assert(hint !== EmitHint.EmbeddedStatement, `A tab stop cannot be attached to an embedded statement.`); nonEscapingWrite(`$${snippet.order}`); } @@ -2526,7 +2538,6 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri write(getTextOfNode(node, /*includeTrivia*/ false)); } - function emitQualifiedName(node: QualifiedName) { emitEntityName(node.left); writePunctuation("."); @@ -2732,7 +2743,6 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri emit(node.type); } - function emitJSDocNullableType(node: JSDocNullableType) { writePunctuation("?"); emit(node.type); @@ -3025,8 +3035,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false); - const shouldEmitDotDot = - token.kind !== SyntaxKind.QuestionDotToken && + const shouldEmitDotDot = token.kind !== SyntaxKind.QuestionDotToken && mayNeedDotDotForPropertyAccess(node.expression) && !writer.hasTrailingComment() && !writer.hasTrailingWhitespace(); @@ -3301,9 +3310,11 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri lastSubstitution = undefined; } - if (pipelinePhase === pipelineEmitWithComments || + if ( + pipelinePhase === pipelineEmitWithComments || pipelinePhase === pipelineEmitWithSourceMaps || - pipelinePhase === pipelineEmitWithHint) { + pipelinePhase === pipelineEmitWithHint + ) { if (isBinaryExpression(next)) { return next; } @@ -3747,7 +3758,6 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri emitSignatureHead(node); writeTrailingSemicolon(); } - } function emitSignatureHead(node: SignatureDeclaration) { @@ -3777,8 +3787,10 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri return false; } - if (getLeadingLineTerminatorCount(body, firstOrUndefined(body.statements), ListFormat.PreserveLines) - || getClosingLineTerminatorCount(body, lastOrUndefined(body.statements), ListFormat.PreserveLines, body.statements)) { + if ( + getLeadingLineTerminatorCount(body, firstOrUndefined(body.statements), ListFormat.PreserveLines) + || getClosingLineTerminatorCount(body, lastOrUndefined(body.statements), ListFormat.PreserveLines, body.statements) + ) { return false; } @@ -4024,9 +4036,12 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri emitTokenWithComment(SyntaxKind.DefaultKeyword, nextPos, writeKeyword, node); } writeSpace(); - emitExpression(node.expression, node.isExportEquals ? - parenthesizer.getParenthesizeRightSideOfBinaryForOperator(SyntaxKind.EqualsToken) : - parenthesizer.parenthesizeExpressionOfExportDefault); + emitExpression( + node.expression, + node.isExportEquals ? + parenthesizer.getParenthesizeRightSideOfBinaryForOperator(SyntaxKind.EqualsToken) : + parenthesizer.parenthesizeExpressionOfExportDefault, + ); writeTrailingSemicolon(); } @@ -4272,8 +4287,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri } function emitCaseOrDefaultClauseRest(parentNode: Node, statements: NodeArray, colonPos: number) { - const emitAsSingleStatement = - statements.length === 1 && + const emitAsSingleStatement = statements.length === 1 && ( // treat synthesized nodes as located on the same line for emit purposes !currentSourceFile || @@ -4720,8 +4734,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri expression: { pos: statement.expression.pos, end: statement.expression.end, - text: statement.expression.text - } + text: statement.expression.text, + }, }); end = end < statement.end ? statement.end : end; } @@ -4817,7 +4831,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri start, pos - start, /*hasTrailingComma*/ false, - textRange); + textRange, + ); } start = pos; lastMode = mode; @@ -4886,7 +4901,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri } function emitEmbeddedStatement(parent: Node, node: Statement) { - if (isBlock(node) || + if ( + isBlock(node) || getEmitFlags(parent) & EmitFlags.SingleLine || preserveSourceNewlines && !getLeadingLineTerminatorCount(parent, node, ListFormat.None) ) { @@ -4931,16 +4947,16 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri const parameter = singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && isArrowFunction(parentNode) // only arrow functions may have simple arrow head - && !parentNode.type // arrow function may not have return type annotation - && !some(parentNode.modifiers) // parent may not have decorators or modifiers + && isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation + && !some(parentNode.modifiers) // parent may not have decorators or modifiers && !some(parentNode.typeParameters) // parent may not have type parameters - && !some(parameter.modifiers) // parameter may not have decorators or modifiers - && !parameter.dotDotDotToken // parameter may not be rest - && !parameter.questionToken // parameter may not be optional - && !parameter.type // parameter may not have a type annotation - && !parameter.initializer // parameter may not have an initializer - && isIdentifier(parameter.name); // parameter name must be identifier + && !some(parameter.modifiers) // parameter may not have decorators or modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && isIdentifier(parameter.name); // parameter name must be identifier } function emitParametersForArrow(parentNode: FunctionTypeNode | ArrowFunction, parameters: NodeArray) { @@ -4987,7 +5003,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri format | (parentNode && getEmitFlags(parentNode) & EmitFlags.MultiLine ? ListFormat.PreferNewLine : 0), parenthesizerRule, start, - count); + count, + ); } function emitExpressionList>(parentNode: Node | undefined, children: Children | undefined, format: ListFormat, parenthesizerRule?: ParenthesizerRuleOrSelector, start?: number, count?: number) { @@ -5356,18 +5373,22 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri // JsxText will be written with its leading whitespace, so don't add more manually. return 0; } - if (currentSourceFile && parentNode && + if ( + currentSourceFile && parentNode && !positionIsSynthesized(parentNode.pos) && !nodeIsSynthesized(firstChild) && (!firstChild.parent || getOriginalNode(firstChild.parent) === getOriginalNode(parentNode)) ) { if (preserveSourceNewlines) { return getEffectiveLines( - includeComments => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter( - firstChild.pos, - parentNode.pos, - currentSourceFile!, - includeComments)); + includeComments => + getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter( + firstChild.pos, + parentNode.pos, + currentSourceFile!, + includeComments, + ), + ); } return rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile) ? 0 : 1; } @@ -5390,11 +5411,14 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri else if (currentSourceFile && !nodeIsSynthesized(previousNode) && !nodeIsSynthesized(nextNode)) { if (preserveSourceNewlines && siblingNodePositionsAreComparable(previousNode, nextNode)) { return getEffectiveLines( - includeComments => getLinesBetweenRangeEndAndRangeStart( - previousNode, - nextNode, - currentSourceFile!, - includeComments)); + includeComments => + getLinesBetweenRangeEndAndRangeStart( + previousNode, + nextNode, + currentSourceFile!, + includeComments, + ), + ); } // If `preserveSourceNewlines` is `false` we do not intend to preserve the effective lines between the // previous and next node. Instead we naively check whether nodes are on separate lines within the @@ -5431,11 +5455,14 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri if (preserveSourceNewlines) { const end = childrenTextRange && !positionIsSynthesized(childrenTextRange.end) ? childrenTextRange.end : lastChild.end; return getEffectiveLines( - includeComments => getLinesBetweenPositionAndNextNonWhitespaceCharacter( - end, - parentNode.end, - currentSourceFile!, - includeComments)); + includeComments => + getLinesBetweenPositionAndNextNonWhitespaceCharacter( + end, + parentNode.end, + currentSourceFile!, + includeComments, + ), + ); } return rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1; } @@ -5518,11 +5545,14 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri if (currentSourceFile && !nodeIsSynthesized(parent) && !nodeIsSynthesized(node1) && !nodeIsSynthesized(node2)) { if (preserveSourceNewlines) { return getEffectiveLines( - includeComments => getLinesBetweenRangeEndAndRangeStart( - node1, - node2, - currentSourceFile!, - includeComments)); + includeComments => + getLinesBetweenRangeEndAndRangeStart( + node1, + node2, + currentSourceFile!, + includeComments, + ), + ); } return rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1; } @@ -6015,7 +6045,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri !!(flags & GeneratedIdentifierFlags.ReservedInNestedScopes), privateName, prefix, - suffix + suffix, ); case SyntaxKind.ModuleDeclaration: case SyntaxKind.EnumDeclaration: @@ -6072,7 +6102,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri !!(autoGenerate.flags & GeneratedIdentifierFlags.ReservedInNestedScopes), isPrivateIdentifier(name), prefix, - suffix + suffix, ); } @@ -6236,7 +6266,6 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri } } exitComment(); - } function originalNodesHaveSameParent(nodeA: Node, nodeB: Node) { @@ -6377,7 +6406,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri } function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { - if(!currentSourceFile) return; + if (!currentSourceFile) return; // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space emitPos(commentPos); @@ -6488,15 +6517,17 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri parsed, node.parent.sourceMapPath!, node.parent.getLineAndCharacterOfPosition(node.pos), - node.parent.getLineAndCharacterOfPosition(node.end) + node.parent.getLineAndCharacterOfPosition(node.end), ); } } else { const source = sourceMapRange.source || sourceMapSource; - if (node.kind !== SyntaxKind.NotEmittedStatement + if ( + node.kind !== SyntaxKind.NotEmittedStatement && (emitFlags & EmitFlags.NoLeadingSourceMap) === 0 - && sourceMapRange.pos >= 0) { + && sourceMapRange.pos >= 0 + ) { emitSourcePos(sourceMapRange.source || sourceMapSource, skipSourceTrivia(source, sourceMapRange.pos)); } if (emitFlags & EmitFlags.NoNestedSourceMaps) { @@ -6514,9 +6545,11 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri if (emitFlags & EmitFlags.NoNestedSourceMaps) { sourceMapsDisabled = false; } - if (node.kind !== SyntaxKind.NotEmittedStatement + if ( + node.kind !== SyntaxKind.NotEmittedStatement && (emitFlags & EmitFlags.NoTrailingSourceMap) === 0 - && sourceMapRange.end >= 0) { + && sourceMapRange.end >= 0 + ) { emitSourcePos(sourceMapRange.source || sourceMapSource, sourceMapRange.end); } } @@ -6549,7 +6582,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri sourceMapSourceIndex, sourceLine, sourceCharacter, - /*nameIndex*/ undefined); + /*nameIndex*/ undefined, + ); } function emitSourcePos(source: SourceMapSource, pos: number) { @@ -6654,9 +6688,9 @@ function getClosingBracket(format: ListFormat) { // Flags enum to track count of temp variables and a few dedicated names const enum TempFlags { - Auto = 0x00000000, // No preferred name - CountMask = 0x0FFFFFFF, // Temp variable counter - _i = 0x10000000, // Use/preference flag for '_i' + Auto = 0x00000000, // No preferred name + CountMask = 0x0FFFFFFF, // Temp variable counter + _i = 0x10000000, // Use/preference flag for '_i' } interface OrdinalParentheizerRuleSelector { diff --git a/src/compiler/factory/baseNodeFactory.ts b/src/compiler/factory/baseNodeFactory.ts index 5641e25703ebe..9ea81cdf5632b 100644 --- a/src/compiler/factory/baseNodeFactory.ts +++ b/src/compiler/factory/baseNodeFactory.ts @@ -35,7 +35,7 @@ export function createBaseNodeFactory(): BaseNodeFactory { createBaseIdentifierNode, createBasePrivateIdentifierNode, createBaseTokenNode, - createBaseNode + createBaseNode, }; function createBaseSourceFileNode(kind: SyntaxKind.SourceFile): Node { diff --git a/src/compiler/factory/emitHelpers.ts b/src/compiler/factory/emitHelpers.ts index e198c123f302b..f3a49d77cb04f 100644 --- a/src/compiler/factory/emitHelpers.ts +++ b/src/compiler/factory/emitHelpers.ts @@ -41,7 +41,7 @@ import { export const enum PrivateIdentifierKind { Field = "f", Method = "m", - Accessor = "a" + Accessor = "a", } /** @@ -88,15 +88,13 @@ export interface ESDecorateClassElementAccess { /** @internal */ export type ESDecorateName = - | { computed: true, name: Expression } - | { computed: false, name: Identifier | PrivateIdentifier } - ; + | { computed: true; name: Expression; } + | { computed: false; name: Identifier | PrivateIdentifier; }; /** @internal */ export type ESDecorateContext = | ESDecorateClassContext - | ESDecorateClassElementContext - ; + | ESDecorateClassElementContext; /** @internal */ export interface EmitHelperFactory { @@ -220,7 +218,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__decorate"), /*typeArguments*/ undefined, - argumentsArray + argumentsArray, ); } @@ -231,8 +229,8 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel /*typeArguments*/ undefined, [ factory.createStringLiteral(metadataKey), - metadataValue - ] + metadataValue, + ], ); } @@ -244,10 +242,10 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel /*typeArguments*/ undefined, [ factory.createNumericLiteral(parameterOffset + ""), - expression - ] + expression, + ], ), - location + location, ); } @@ -276,12 +274,12 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel [factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - factory.createIdentifier("obj") + factory.createIdentifier("obj"), )], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, - accessor - ) + accessor, + ), ); } @@ -295,33 +293,34 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel factory.createArrowFunction( /*modifiers*/ undefined, /*typeParameters*/ undefined, - [factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - factory.createIdentifier("obj") - ), - factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - factory.createIdentifier("value") - )], + [ + factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + factory.createIdentifier("obj"), + ), + factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + factory.createIdentifier("value"), + ), + ], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, factory.createBlock([ factory.createExpressionStatement( factory.createAssignment( accessor, - factory.createIdentifier("value") - ) - ) - ]) - ) + factory.createIdentifier("value"), + ), + ), + ]), + ), ); } function createESDecorateClassElementAccessHasMethod(elementName: ESDecorateName) { - const propertyName = - elementName.computed ? elementName.name : + const propertyName = elementName.computed ? elementName.name : isIdentifier(elementName.name) ? factory.createStringLiteralFromNode(elementName.name) : elementName.name; @@ -333,16 +332,16 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel [factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - factory.createIdentifier("obj") + factory.createIdentifier("obj"), )], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, factory.createBinaryExpression( propertyName, SyntaxKind.InKeyword, - factory.createIdentifier("obj") - ) - ) + factory.createIdentifier("obj"), + ), + ), ); } @@ -382,8 +381,9 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel decorators, createESDecorateContextObject(contextIn), initializers, - extraInitializers - ]); + extraInitializers, + ], + ); } function createRunInitializersHelper(thisArg: Expression, initializers: Expression, value?: Expression) { @@ -391,22 +391,20 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__runInitializers"), /*typeArguments*/ undefined, - value ? [thisArg, initializers, value] : [thisArg, initializers] + value ? [thisArg, initializers, value] : [thisArg, initializers], ); } // ES2018 Helpers function createAssignHelper(attributesSegments: Expression[]) { if (getEmitScriptTarget(context.getCompilerOptions()) >= ScriptTarget.ES2015) { - return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"), - /*typeArguments*/ undefined, - attributesSegments); + return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments); } context.requestEmitHelper(assignHelper); return factory.createCallExpression( getUnscopedHelperName("__assign"), /*typeArguments*/ undefined, - attributesSegments + attributesSegments, ); } @@ -428,8 +426,8 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel [ hasLexicalThis ? factory.createThis() : factory.createVoidZero(), factory.createIdentifier("arguments"), - generatorFunc - ] + generatorFunc, + ], ); } @@ -439,7 +437,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__asyncDelegator"), /*typeArguments*/ undefined, - [expression] + [expression], ); } @@ -448,7 +446,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__asyncValues"), /*typeArguments*/ undefined, - [expression] + [expression], ); } @@ -475,8 +473,8 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel /*questionToken*/ undefined, temp, /*colonToken*/ undefined, - factory.createAdd(temp, factory.createStringLiteral("")) - ) + factory.createAdd(temp, factory.createStringLiteral("")), + ), ); } else { @@ -491,8 +489,9 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel value, setTextRange( factory.createArrayLiteralExpression(propertyNames), - location - )] + location, + ), + ], ); } @@ -508,7 +507,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, - body + body, ); // Mark this node as originally an async function @@ -521,8 +520,8 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel hasLexicalThis ? factory.createThis() : factory.createVoidZero(), hasLexicalArguments ? factory.createIdentifier("arguments") : factory.createVoidZero(), promiseConstructor ? createExpressionFromEntityName(factory, promiseConstructor) : factory.createVoidZero(), - generatorFunc - ] + generatorFunc, + ], ); } @@ -533,7 +532,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__extends"), /*typeArguments*/ undefined, - [name, factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel)] + [name, factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel)], ); } @@ -542,7 +541,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__makeTemplateObject"), /*typeArguments*/ undefined, - [cooked, raw] + [cooked, raw], ); } @@ -551,7 +550,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__spreadArray"), /*typeArguments*/ undefined, - [to, from, packFrom ? immutableTrue() : immutableFalse()] + [to, from, packFrom ? immutableTrue() : immutableFalse()], ); } @@ -560,7 +559,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__propKey"), /*typeArguments*/ undefined, - [expr] + [expr], ); } @@ -569,7 +568,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return context.factory.createCallExpression( getUnscopedHelperName("__setFunctionName"), /*typeArguments*/ undefined, - prefix ? [f, name, context.factory.createStringLiteral(prefix)] : [f, name] + prefix ? [f, name, context.factory.createStringLiteral(prefix)] : [f, name], ); } @@ -580,7 +579,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__values"), /*typeArguments*/ undefined, - [expression] + [expression], ); } @@ -591,7 +590,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel /*typeArguments*/ undefined, count !== undefined ? [iteratorRecord, factory.createNumericLiteral(count + "")] - : [iteratorRecord] + : [iteratorRecord], ); } @@ -602,7 +601,8 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__generator"), /*typeArguments*/ undefined, - [factory.createThis(), body]); + [factory.createThis(), body], + ); } // ES Module Helpers @@ -612,7 +612,8 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, - [factory.createIdentifier("exports"), module, inputName, ...(outputName ? [outputName] : [])]); + [factory.createIdentifier("exports"), module, inputName, ...(outputName ? [outputName] : [])], + ); } function createImportStarHelper(expression: Expression) { @@ -620,7 +621,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, - [expression] + [expression], ); } @@ -634,7 +635,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__importDefault"), /*typeArguments*/ undefined, - [expression] + [expression], ); } @@ -644,7 +645,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, - [moduleExpression, exportsExpression] + [moduleExpression, exportsExpression], ); } @@ -684,7 +685,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel return factory.createCallExpression( getUnscopedHelperName("__addDisposableResource"), /*typeArguments*/ undefined, - [envBinding, value, async ? factory.createTrue() : factory.createFalse()] + [envBinding, value, async ? factory.createTrue() : factory.createFalse()], ); } @@ -735,7 +736,7 @@ export const decorateHelper: UnscopedEmitHelper = { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; - };` + };`, }; /** @internal */ @@ -747,7 +748,7 @@ export const metadataHelper: UnscopedEmitHelper = { text: ` var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); - };` + };`, }; /** @internal */ @@ -759,7 +760,7 @@ export const paramHelper: UnscopedEmitHelper = { text: ` var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } - };` + };`, }; // ES Decorators Helpers @@ -796,7 +797,7 @@ export const esDecorateHelper: UnscopedEmitHelper = { } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; - };` + };`, }; /** @internal */ @@ -812,7 +813,7 @@ export const runInitializersHelper: UnscopedEmitHelper = { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; - };` + };`, }; // ES2018 Helpers @@ -834,7 +835,7 @@ export const assignHelper: UnscopedEmitHelper = { return t; }; return __assign.apply(this, arguments); - };` + };`, }; /** @internal */ @@ -843,7 +844,7 @@ export const awaitHelper: UnscopedEmitHelper = { importName: "__await", scoped: false, text: ` - var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }` + var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }`, }; /** @internal */ @@ -863,7 +864,7 @@ export const asyncGeneratorHelper: UnscopedEmitHelper = { function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - };` + };`, }; /** @internal */ @@ -877,7 +878,7 @@ export const asyncDelegator: UnscopedEmitHelper = { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } - };` + };`, }; /** @internal */ @@ -892,7 +893,7 @@ export const asyncValues: UnscopedEmitHelper = { return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - };` + };`, }; // ES2018 Destructuring Helpers @@ -913,7 +914,7 @@ export const restHelper: UnscopedEmitHelper = { t[p[i]] = s[p[i]]; } return t; - };` + };`, }; // ES2017 Helpers @@ -933,7 +934,7 @@ export const awaiterHelper: UnscopedEmitHelper = { function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - };` + };`, }; // ES2015 Helpers @@ -960,7 +961,7 @@ export const extendsHelper: UnscopedEmitHelper = { function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - })();` + })();`, }; /** @internal */ @@ -973,7 +974,7 @@ export const templateObjectHelper: UnscopedEmitHelper = { var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; - };` + };`, }; /** @internal */ @@ -997,7 +998,7 @@ export const readHelper: UnscopedEmitHelper = { finally { if (e) throw e.error; } } return ar; - };` + };`, }; /** @internal */ @@ -1014,7 +1015,7 @@ export const spreadArrayHelper: UnscopedEmitHelper = { } } return to.concat(ar || Array.prototype.slice.call(from)); - };` + };`, }; /** @internal */ @@ -1025,7 +1026,7 @@ export const propKeyHelper: UnscopedEmitHelper = { text: ` var __propKey = (this && this.__propKey) || function (x) { return typeof x === "symbol" ? x : "".concat(x); - };` + };`, }; // https://tc39.es/ecma262/#sec-setfunctionname @@ -1038,7 +1039,7 @@ export const setFunctionNameHelper: UnscopedEmitHelper = { var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); - };` + };`, }; // ES2015 Destructuring Helpers @@ -1059,7 +1060,7 @@ export const valuesHelper: UnscopedEmitHelper = { } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - };` + };`, }; // ES2015 Generator Helpers @@ -1158,7 +1159,7 @@ export const generatorHelper: UnscopedEmitHelper = { } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - };` + };`, }; // ES Module Helpers @@ -1180,7 +1181,7 @@ export const createBindingHelper: UnscopedEmitHelper = { }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; - }));` + }));`, }; /** @internal */ @@ -1194,7 +1195,7 @@ export const setModuleDefaultHelper: UnscopedEmitHelper = { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; - });` + });`, }; // emit helper for `import * as Name from "foo"` @@ -1212,7 +1213,7 @@ export const importStarHelper: UnscopedEmitHelper = { if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; - };` + };`, }; // emit helper for `import Name from "foo"` @@ -1224,7 +1225,7 @@ export const importDefaultHelper: UnscopedEmitHelper = { text: ` var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; - };` + };`, }; /** @internal */ @@ -1237,7 +1238,7 @@ export const exportStarHelper: UnscopedEmitHelper = { text: ` var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); - };` + };`, }; /** @@ -1299,7 +1300,7 @@ export const classPrivateFieldGetHelper: UnscopedEmitHelper = { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - };` + };`, }; /** @@ -1365,7 +1366,7 @@ export const classPrivateFieldSetHelper: UnscopedEmitHelper = { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; - };` + };`, }; /** @@ -1390,7 +1391,7 @@ export const classPrivateFieldInHelper: UnscopedEmitHelper = { var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); - };` + };`, }; /** @@ -1420,7 +1421,7 @@ export const addDisposableResourceHelper: UnscopedEmitHelper = { env.stack.push({ async: true }); } return value; - };` + };`, }; /** @@ -1455,7 +1456,7 @@ export const disposeResourcesHelper: UnscopedEmitHelper = { })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; - });` + });`, }; let allUnscopedEmitHelpers: ReadonlyMap | undefined; @@ -1501,7 +1502,7 @@ export const asyncSuperHelper: EmitHelper = { name: "typescript:async-super", scoped: true, text: helperString` - const ${"_superIndex"} = name => super[name];` + const ${"_superIndex"} = name => super[name];`, }; /** @internal */ @@ -1512,7 +1513,7 @@ export const advancedAsyncSuperHelper: EmitHelper = { const ${"_superIndex"} = (function (geti, seti) { const cache = Object.create(null); return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - })(name => super[name], (name, value) => super[name] = value);` + })(name => super[name], (name, value) => super[name] = value);`, }; /** @internal */ diff --git a/src/compiler/factory/nodeConverters.ts b/src/compiler/factory/nodeConverters.ts index bc12cb58cc73a..33ab7b4b598ad 100644 --- a/src/compiler/factory/nodeConverters.ts +++ b/src/compiler/factory/nodeConverters.ts @@ -69,7 +69,7 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { node.typeParameters, node.parameters, node.type, - node.body + node.body, ); setOriginalNode(updated, node); setTextRange(updated, node); @@ -85,7 +85,7 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { node.name, node.typeParameters, node.heritageClauses, - node.members + node.members, ); setOriginalNode(updated, node); setTextRange(updated, node); @@ -106,9 +106,9 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { ? setOriginalNode( setTextRange( factory.createAssignment(expression, element.initializer), - element + element, ), - element + element, ) : expression; } @@ -149,9 +149,9 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { return setOriginalNode( setTextRange( factory.createObjectLiteralExpression(map(node.elements, convertToObjectAssignmentElement)), - node + node, ), - node + node, ); } return cast(node, isObjectLiteralExpression); @@ -162,9 +162,9 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { return setOriginalNode( setTextRange( factory.createArrayLiteralExpression(map(node.elements, convertToArrayAssignmentElement)), - node + node, ), - node + node, ); } return cast(node, isArrayLiteralExpression); diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts index 5a33d53ed4dc9..ededdbd057ab9 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -523,12 +523,16 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const getJSDocPrePostfixUnaryTypeUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, type: T["type"]) => updateJSDocPrePostfixUnaryTypeWorker(kind, node, type)); const getJSDocSimpleTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, comment?: NodeArray) => createJSDocSimpleTagWorker(kind, tagName, comment)); const getJSDocSimpleTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, comment?: NodeArray) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); - const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); - const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); + const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); + const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); const factory: NodeFactory = { - get parenthesizer() { return parenthesizerRules(); }, - get converters() { return converters(); }, + get parenthesizer() { + return parenthesizerRules(); + }, + get converters() { + return converters(); + }, baseFactory, flags, createNodeArray, @@ -807,18 +811,42 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode createExternalModuleReference, updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure - get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(SyntaxKind.JSDocAllType); }, - get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(SyntaxKind.JSDocUnknownType); }, - get createJSDocNonNullableType() { return getJSDocPrePostfixUnaryTypeCreateFunction(SyntaxKind.JSDocNonNullableType); }, - get updateJSDocNonNullableType() { return getJSDocPrePostfixUnaryTypeUpdateFunction(SyntaxKind.JSDocNonNullableType); }, - get createJSDocNullableType() { return getJSDocPrePostfixUnaryTypeCreateFunction(SyntaxKind.JSDocNullableType); }, - get updateJSDocNullableType() { return getJSDocPrePostfixUnaryTypeUpdateFunction(SyntaxKind.JSDocNullableType); }, - get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocOptionalType); }, - get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocOptionalType); }, - get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocVariadicType); }, - get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocVariadicType); }, - get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocNamepathType); }, - get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocNamepathType); }, + get createJSDocAllType() { + return getJSDocPrimaryTypeCreateFunction(SyntaxKind.JSDocAllType); + }, + get createJSDocUnknownType() { + return getJSDocPrimaryTypeCreateFunction(SyntaxKind.JSDocUnknownType); + }, + get createJSDocNonNullableType() { + return getJSDocPrePostfixUnaryTypeCreateFunction(SyntaxKind.JSDocNonNullableType); + }, + get updateJSDocNonNullableType() { + return getJSDocPrePostfixUnaryTypeUpdateFunction(SyntaxKind.JSDocNonNullableType); + }, + get createJSDocNullableType() { + return getJSDocPrePostfixUnaryTypeCreateFunction(SyntaxKind.JSDocNullableType); + }, + get updateJSDocNullableType() { + return getJSDocPrePostfixUnaryTypeUpdateFunction(SyntaxKind.JSDocNullableType); + }, + get createJSDocOptionalType() { + return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocOptionalType); + }, + get updateJSDocOptionalType() { + return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocOptionalType); + }, + get createJSDocVariadicType() { + return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocVariadicType); + }, + get updateJSDocVariadicType() { + return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocVariadicType); + }, + get createJSDocNamepathType() { + return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocNamepathType); + }, + get updateJSDocNamepathType() { + return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocNamepathType); + }, createJSDocFunctionType, updateJSDocFunctionType, createJSDocTypeLiteral, @@ -856,32 +884,84 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode createJSDocLinkPlain, updateJSDocLinkPlain, // lazily load factory members for JSDoc tags with similar structure - get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocTypeTag); }, - get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocTypeTag); }, - get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocReturnTag); }, - get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocReturnTag); }, - get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocThisTag); }, - get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocThisTag); }, - get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocAuthorTag); }, - get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocAuthorTag); }, - get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocClassTag); }, - get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocClassTag); }, - get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocPublicTag); }, - get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocPublicTag); }, - get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocPrivateTag); }, - get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocPrivateTag); }, - get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocProtectedTag); }, - get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocProtectedTag); }, - get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocReadonlyTag); }, - get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocReadonlyTag); }, - get createJSDocOverrideTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocOverrideTag); }, - get updateJSDocOverrideTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocOverrideTag); }, - get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocDeprecatedTag); }, - get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocDeprecatedTag); }, - get createJSDocThrowsTag() { return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocThrowsTag); }, - get updateJSDocThrowsTag() { return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocThrowsTag); }, - get createJSDocSatisfiesTag() { return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocSatisfiesTag); }, - get updateJSDocSatisfiesTag() { return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocSatisfiesTag); }, + get createJSDocTypeTag() { + return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocTypeTag); + }, + get updateJSDocTypeTag() { + return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocTypeTag); + }, + get createJSDocReturnTag() { + return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocReturnTag); + }, + get updateJSDocReturnTag() { + return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocReturnTag); + }, + get createJSDocThisTag() { + return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocThisTag); + }, + get updateJSDocThisTag() { + return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocThisTag); + }, + get createJSDocAuthorTag() { + return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocAuthorTag); + }, + get updateJSDocAuthorTag() { + return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocAuthorTag); + }, + get createJSDocClassTag() { + return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocClassTag); + }, + get updateJSDocClassTag() { + return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocClassTag); + }, + get createJSDocPublicTag() { + return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocPublicTag); + }, + get updateJSDocPublicTag() { + return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocPublicTag); + }, + get createJSDocPrivateTag() { + return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocPrivateTag); + }, + get updateJSDocPrivateTag() { + return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocPrivateTag); + }, + get createJSDocProtectedTag() { + return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocProtectedTag); + }, + get updateJSDocProtectedTag() { + return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocProtectedTag); + }, + get createJSDocReadonlyTag() { + return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocReadonlyTag); + }, + get updateJSDocReadonlyTag() { + return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocReadonlyTag); + }, + get createJSDocOverrideTag() { + return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocOverrideTag); + }, + get updateJSDocOverrideTag() { + return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocOverrideTag); + }, + get createJSDocDeprecatedTag() { + return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocDeprecatedTag); + }, + get updateJSDocDeprecatedTag() { + return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocDeprecatedTag); + }, + get createJSDocThrowsTag() { + return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocThrowsTag); + }, + get updateJSDocThrowsTag() { + return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocThrowsTag); + }, + get createJSDocSatisfiesTag() { + return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocSatisfiesTag); + }, + get updateJSDocSatisfiesTag() { + return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocSatisfiesTag); + }, createJSDocEnumTag, updateJSDocEnumTag, @@ -954,38 +1034,102 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode cloneNode, // Lazily load factory methods for common operator factories and utilities - get createComma() { return getBinaryCreateFunction(SyntaxKind.CommaToken); }, - get createAssignment() { return getBinaryCreateFunction(SyntaxKind.EqualsToken) as NodeFactory["createAssignment"]; }, - get createLogicalOr() { return getBinaryCreateFunction(SyntaxKind.BarBarToken); }, - get createLogicalAnd() { return getBinaryCreateFunction(SyntaxKind.AmpersandAmpersandToken); }, - get createBitwiseOr() { return getBinaryCreateFunction(SyntaxKind.BarToken); }, - get createBitwiseXor() { return getBinaryCreateFunction(SyntaxKind.CaretToken); }, - get createBitwiseAnd() { return getBinaryCreateFunction(SyntaxKind.AmpersandToken); }, - get createStrictEquality() { return getBinaryCreateFunction(SyntaxKind.EqualsEqualsEqualsToken); }, - get createStrictInequality() { return getBinaryCreateFunction(SyntaxKind.ExclamationEqualsEqualsToken); }, - get createEquality() { return getBinaryCreateFunction(SyntaxKind.EqualsEqualsToken); }, - get createInequality() { return getBinaryCreateFunction(SyntaxKind.ExclamationEqualsToken); }, - get createLessThan() { return getBinaryCreateFunction(SyntaxKind.LessThanToken); }, - get createLessThanEquals() { return getBinaryCreateFunction(SyntaxKind.LessThanEqualsToken); }, - get createGreaterThan() { return getBinaryCreateFunction(SyntaxKind.GreaterThanToken); }, - get createGreaterThanEquals() { return getBinaryCreateFunction(SyntaxKind.GreaterThanEqualsToken); }, - get createLeftShift() { return getBinaryCreateFunction(SyntaxKind.LessThanLessThanToken); }, - get createRightShift() { return getBinaryCreateFunction(SyntaxKind.GreaterThanGreaterThanToken); }, - get createUnsignedRightShift() { return getBinaryCreateFunction(SyntaxKind.GreaterThanGreaterThanGreaterThanToken); }, - get createAdd() { return getBinaryCreateFunction(SyntaxKind.PlusToken); }, - get createSubtract() { return getBinaryCreateFunction(SyntaxKind.MinusToken); }, - get createMultiply() { return getBinaryCreateFunction(SyntaxKind.AsteriskToken); }, - get createDivide() { return getBinaryCreateFunction(SyntaxKind.SlashToken); }, - get createModulo() { return getBinaryCreateFunction(SyntaxKind.PercentToken); }, - get createExponent() { return getBinaryCreateFunction(SyntaxKind.AsteriskAsteriskToken); }, - get createPrefixPlus() { return getPrefixUnaryCreateFunction(SyntaxKind.PlusToken); }, - get createPrefixMinus() { return getPrefixUnaryCreateFunction(SyntaxKind.MinusToken); }, - get createPrefixIncrement() { return getPrefixUnaryCreateFunction(SyntaxKind.PlusPlusToken); }, - get createPrefixDecrement() { return getPrefixUnaryCreateFunction(SyntaxKind.MinusMinusToken); }, - get createBitwiseNot() { return getPrefixUnaryCreateFunction(SyntaxKind.TildeToken); }, - get createLogicalNot() { return getPrefixUnaryCreateFunction(SyntaxKind.ExclamationToken); }, - get createPostfixIncrement() { return getPostfixUnaryCreateFunction(SyntaxKind.PlusPlusToken); }, - get createPostfixDecrement() { return getPostfixUnaryCreateFunction(SyntaxKind.MinusMinusToken); }, + get createComma() { + return getBinaryCreateFunction(SyntaxKind.CommaToken); + }, + get createAssignment() { + return getBinaryCreateFunction(SyntaxKind.EqualsToken) as NodeFactory["createAssignment"]; + }, + get createLogicalOr() { + return getBinaryCreateFunction(SyntaxKind.BarBarToken); + }, + get createLogicalAnd() { + return getBinaryCreateFunction(SyntaxKind.AmpersandAmpersandToken); + }, + get createBitwiseOr() { + return getBinaryCreateFunction(SyntaxKind.BarToken); + }, + get createBitwiseXor() { + return getBinaryCreateFunction(SyntaxKind.CaretToken); + }, + get createBitwiseAnd() { + return getBinaryCreateFunction(SyntaxKind.AmpersandToken); + }, + get createStrictEquality() { + return getBinaryCreateFunction(SyntaxKind.EqualsEqualsEqualsToken); + }, + get createStrictInequality() { + return getBinaryCreateFunction(SyntaxKind.ExclamationEqualsEqualsToken); + }, + get createEquality() { + return getBinaryCreateFunction(SyntaxKind.EqualsEqualsToken); + }, + get createInequality() { + return getBinaryCreateFunction(SyntaxKind.ExclamationEqualsToken); + }, + get createLessThan() { + return getBinaryCreateFunction(SyntaxKind.LessThanToken); + }, + get createLessThanEquals() { + return getBinaryCreateFunction(SyntaxKind.LessThanEqualsToken); + }, + get createGreaterThan() { + return getBinaryCreateFunction(SyntaxKind.GreaterThanToken); + }, + get createGreaterThanEquals() { + return getBinaryCreateFunction(SyntaxKind.GreaterThanEqualsToken); + }, + get createLeftShift() { + return getBinaryCreateFunction(SyntaxKind.LessThanLessThanToken); + }, + get createRightShift() { + return getBinaryCreateFunction(SyntaxKind.GreaterThanGreaterThanToken); + }, + get createUnsignedRightShift() { + return getBinaryCreateFunction(SyntaxKind.GreaterThanGreaterThanGreaterThanToken); + }, + get createAdd() { + return getBinaryCreateFunction(SyntaxKind.PlusToken); + }, + get createSubtract() { + return getBinaryCreateFunction(SyntaxKind.MinusToken); + }, + get createMultiply() { + return getBinaryCreateFunction(SyntaxKind.AsteriskToken); + }, + get createDivide() { + return getBinaryCreateFunction(SyntaxKind.SlashToken); + }, + get createModulo() { + return getBinaryCreateFunction(SyntaxKind.PercentToken); + }, + get createExponent() { + return getBinaryCreateFunction(SyntaxKind.AsteriskAsteriskToken); + }, + get createPrefixPlus() { + return getPrefixUnaryCreateFunction(SyntaxKind.PlusToken); + }, + get createPrefixMinus() { + return getPrefixUnaryCreateFunction(SyntaxKind.MinusToken); + }, + get createPrefixIncrement() { + return getPrefixUnaryCreateFunction(SyntaxKind.PlusPlusToken); + }, + get createPrefixDecrement() { + return getPrefixUnaryCreateFunction(SyntaxKind.MinusMinusToken); + }, + get createBitwiseNot() { + return getPrefixUnaryCreateFunction(SyntaxKind.TildeToken); + }, + get createLogicalNot() { + return getPrefixUnaryCreateFunction(SyntaxKind.ExclamationToken); + }, + get createPostfixIncrement() { + return getPostfixUnaryCreateFunction(SyntaxKind.PlusPlusToken); + }, + get createPostfixDecrement() { + return getPostfixUnaryCreateFunction(SyntaxKind.MinusMinusToken); + }, // Compound nodes createImmediatelyInvokedFunctionExpression, @@ -1150,13 +1294,20 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createLiteralLikeNode(kind: LiteralToken["kind"] | SyntaxKind.JsxTextAllWhiteSpaces, text: string): LiteralToken { switch (kind) { - case SyntaxKind.NumericLiteral: return createNumericLiteral(text, /*numericLiteralFlags*/ 0); - case SyntaxKind.BigIntLiteral: return createBigIntLiteral(text); - case SyntaxKind.StringLiteral: return createStringLiteral(text, /*isSingleQuote*/ undefined); - case SyntaxKind.JsxText: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false); - case SyntaxKind.JsxTextAllWhiteSpaces: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true); - case SyntaxKind.RegularExpressionLiteral: return createRegularExpressionLiteral(text); - case SyntaxKind.NoSubstitutionTemplateLiteral: return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0) as NoSubstitutionTemplateLiteral; + case SyntaxKind.NumericLiteral: + return createNumericLiteral(text, /*numericLiteralFlags*/ 0); + case SyntaxKind.BigIntLiteral: + return createBigIntLiteral(text); + case SyntaxKind.StringLiteral: + return createStringLiteral(text, /*isSingleQuote*/ undefined); + case SyntaxKind.JsxText: + return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false); + case SyntaxKind.JsxTextAllWhiteSpaces: + return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true); + case SyntaxKind.RegularExpressionLiteral: + return createRegularExpressionLiteral(text); + case SyntaxKind.NoSubstitutionTemplateLiteral: + return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0) as NoSubstitutionTemplateLiteral; } } @@ -1179,7 +1330,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode flags: autoGenerateFlags, id: nextAutoGenerateId, prefix, - suffix + suffix, }); nextAutoGenerateId++; return node; @@ -1323,8 +1474,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode switch (token) { case SyntaxKind.AsyncKeyword: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) - transformFlags = - TransformFlags.ContainsES2017 | + transformFlags = TransformFlags.ContainsES2017 | TransformFlags.ContainsES2018; break; @@ -1445,8 +1595,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.QualifiedName); node.left = left; node.right = asName(right); - node.transformFlags |= - propagateChildFlags(node.left) | + node.transformFlags |= propagateChildFlags(node.left) | propagateIdentifierNameFlags(node.right); node.flowNode = undefined; // initialized by binder (FlowContainer) @@ -1456,7 +1605,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier) { return node.left !== left - || node.right !== right + || node.right !== right ? update(createQualifiedName(left, right), node) : node; } @@ -1465,8 +1614,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createComputedPropertyName(expression: Expression) { const node = createBaseNode(SyntaxKind.ComputedPropertyName); node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2015 | TransformFlags.ContainsComputedPropertyName; return node; @@ -1500,9 +1648,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration { return node.modifiers !== modifiers - || node.name !== name - || node.constraint !== constraint - || node.default !== defaultType + || node.name !== name + || node.constraint !== constraint + || node.default !== defaultType ? update(createTypeParameterDeclaration(modifiers, name, constraint, defaultType), node) : node; } @@ -1514,7 +1662,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, - initializer?: Expression + initializer?: Expression, ) { const node = createBaseDeclaration(SyntaxKind.Parameter); node.modifiers = asNodeArray(modifiers); @@ -1528,8 +1676,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.transformFlags = TransformFlags.ContainsTypeScript; } else { - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | @@ -1551,14 +1698,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, - initializer: Expression | undefined + initializer: Expression | undefined, ) { return node.modifiers !== modifiers - || node.dotDotDotToken !== dotDotDotToken - || node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type + || node.initializer !== initializer ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } @@ -1567,8 +1714,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createDecorator(expression: Expression) { const node = createBaseNode(SyntaxKind.Decorator); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsTypeScript | TransformFlags.ContainsTypeScriptClassSyntax | TransformFlags.ContainsDecorators; @@ -1591,7 +1737,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, - type: TypeNode | undefined + type: TypeNode | undefined, ): PropertySignature { const node = createBaseDeclaration(SyntaxKind.PropertySignature); node.modifiers = asNodeArray(modifiers); @@ -1611,12 +1757,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, - type: TypeNode | undefined + type: TypeNode | undefined, ) { return node.modifiers !== modifiers - || node.name !== name - || node.questionToken !== questionToken - || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) : node; } @@ -1635,7 +1781,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, - initializer: Expression | undefined + initializer: Expression | undefined, ) { const node = createBaseDeclaration(SyntaxKind.PropertyDeclaration); node.modifiers = asNodeArray(modifiers); @@ -1647,8 +1793,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const isAmbient = node.flags & NodeFlags.Ambient || modifiersToFlags(node.modifiers) & ModifierFlags.Ambient; - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (isAmbient || node.questionToken || node.exclamationToken || node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None) | @@ -1666,14 +1811,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, - initializer: Expression | undefined + initializer: Expression | undefined, ) { return node.modifiers !== modifiers - || node.name !== name - || node.questionToken !== (questionOrExclamationToken !== undefined && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) - || node.exclamationToken !== (questionOrExclamationToken !== undefined && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) - || node.type !== type - || node.initializer !== initializer + || node.name !== name + || node.questionToken !== (questionOrExclamationToken !== undefined && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) + || node.exclamationToken !== (questionOrExclamationToken !== undefined && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) + || node.type !== type + || node.initializer !== initializer ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) : node; } @@ -1685,7 +1830,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], - type: TypeNode | undefined + type: TypeNode | undefined, ) { const node = createBaseDeclaration(SyntaxKind.MethodSignature); node.modifiers = asNodeArray(modifiers); @@ -1711,14 +1856,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode questionToken: QuestionToken | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, - type: TypeNode | undefined + type: TypeNode | undefined, ) { return node.modifiers !== modifiers - || node.name !== name - || node.questionToken !== questionToken - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) : node; } @@ -1732,7 +1877,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, - body: Block | undefined + body: Block | undefined, ) { const node = createBaseDeclaration(SyntaxKind.MethodDeclaration); node.modifiers = asNodeArray(modifiers); @@ -1753,8 +1898,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const isGenerator = !!node.asteriskToken; const isAsyncGenerator = isAsync && isGenerator; - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | @@ -1790,16 +1934,16 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, - body: Block | undefined + body: Block | undefined, ) { return node.modifiers !== modifiers - || node.asteriskToken !== asteriskToken - || node.name !== name - || node.questionToken !== questionToken - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.body !== body + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.questionToken !== questionToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) : node; } @@ -1814,7 +1958,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createClassStaticBlockDeclaration( - body: Block + body: Block, ): ClassStaticBlockDeclaration { const node = createBaseDeclaration(SyntaxKind.ClassStaticBlockDeclaration); node.body = body; @@ -1832,7 +1976,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateClassStaticBlockDeclaration( node: ClassStaticBlockDeclaration, - body: Block + body: Block, ): ClassStaticBlockDeclaration { return node.body !== body ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) @@ -1851,15 +1995,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createConstructorDeclaration( modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], - body: Block | undefined + body: Block | undefined, ) { const node = createBaseDeclaration(SyntaxKind.Constructor); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); node.body = body; - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.parameters) | (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | TransformFlags.ContainsES2015; @@ -1880,11 +2023,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: ConstructorDeclaration, modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], - body: Block | undefined + body: Block | undefined, ) { return node.modifiers !== modifiers - || node.parameters !== parameters - || node.body !== body + || node.parameters !== parameters + || node.body !== body ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) : node; } @@ -1903,7 +2046,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, - body: Block | undefined + body: Block | undefined, ) { const node = createBaseDeclaration(SyntaxKind.GetAccessor); node.modifiers = asNodeArray(modifiers); @@ -1916,8 +2059,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.transformFlags = TransformFlags.ContainsTypeScript; } else { - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | @@ -1943,13 +2085,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, - body: Block | undefined + body: Block | undefined, ) { return node.modifiers !== modifiers - || node.name !== name - || node.parameters !== parameters - || node.type !== type - || node.body !== body + || node.name !== name + || node.parameters !== parameters + || node.type !== type + || node.body !== body ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) : node; } @@ -1967,7 +2109,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], - body: Block | undefined + body: Block | undefined, ) { const node = createBaseDeclaration(SyntaxKind.SetAccessor); node.modifiers = asNodeArray(modifiers); @@ -1979,8 +2121,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.transformFlags = TransformFlags.ContainsTypeScript; } else { - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | @@ -2005,12 +2146,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], - body: Block | undefined + body: Block | undefined, ) { return node.modifiers !== modifiers - || node.name !== name - || node.parameters !== parameters - || node.body !== body + || node.name !== name + || node.parameters !== parameters + || node.body !== body ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) : node; } @@ -2028,7 +2169,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createCallSignature( typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], - type: TypeNode | undefined + type: TypeNode | undefined, ): CallSignatureDeclaration { const node = createBaseDeclaration(SyntaxKind.CallSignature); node.typeParameters = asNodeArray(typeParameters); @@ -2048,11 +2189,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, - type: TypeNode | undefined + type: TypeNode | undefined, ) { return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type + || node.parameters !== parameters + || node.type !== type ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) : node; } @@ -2061,7 +2202,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createConstructSignature( typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], - type: TypeNode | undefined + type: TypeNode | undefined, ): ConstructSignatureDeclaration { const node = createBaseDeclaration(SyntaxKind.ConstructSignature); node.typeParameters = asNodeArray(typeParameters); @@ -2081,11 +2222,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, - type: TypeNode | undefined + type: TypeNode | undefined, ) { return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type + || node.parameters !== parameters + || node.type !== type ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) : node; } @@ -2094,7 +2235,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createIndexSignature( modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], - type: TypeNode | undefined + type: TypeNode | undefined, ): IndexSignatureDeclaration { const node = createBaseDeclaration(SyntaxKind.IndexSignature); node.modifiers = asNodeArray(modifiers); @@ -2114,11 +2255,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: IndexSignatureDeclaration, modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], - type: TypeNode + type: TypeNode, ) { return node.parameters !== parameters - || node.type !== type - || node.modifiers !== modifiers + || node.type !== type + || node.modifiers !== modifiers ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) : node; } @@ -2135,7 +2276,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddle | TemplateTail) { return node.type !== type - || node.literal !== literal + || node.literal !== literal ? update(createTemplateLiteralTypeSpan(type, literal), node) : node; } @@ -2162,8 +2303,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined) { return node.assertsModifier !== assertsModifier - || node.parameterName !== parameterName - || node.type !== type + || node.parameterName !== parameterName + || node.type !== type ? update(createTypePredicateNode(assertsModifier, parameterName, type), node) : node; } @@ -2180,7 +2321,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined) { return node.typeName !== typeName - || node.typeArguments !== typeArguments + || node.typeArguments !== typeArguments ? update(createTypeReferenceNode(typeName, typeArguments), node) : node; } @@ -2189,7 +2330,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createFunctionTypeNode( typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], - type: TypeNode + type: TypeNode, ): FunctionTypeNode { const node = createBaseDeclaration(SyntaxKind.FunctionType); node.typeParameters = asNodeArray(typeParameters); @@ -2210,11 +2351,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, - type: TypeNode + type: TypeNode, ) { return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type + || node.parameters !== parameters + || node.type !== type ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) : node; } @@ -2238,7 +2379,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], - type: TypeNode + type: TypeNode, ): ConstructorTypeNode { const node = createBaseDeclaration(SyntaxKind.ConstructorType); node.modifiers = asNodeArray(modifiers); @@ -2258,7 +2399,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createConstructorTypeNode2( typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], - type: TypeNode + type: TypeNode, ): ConstructorTypeNode { return createConstructorTypeNode1(/*modifiers*/ undefined, typeParameters, parameters, type); } @@ -2275,12 +2416,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly Modifier[] | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, - type: TypeNode + type: TypeNode, ) { return node.modifiers !== modifiers - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) : node; } @@ -2290,7 +2431,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, - type: TypeNode + type: TypeNode, ) { return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type); } @@ -2307,7 +2448,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]) { return node.exprName !== exprName - || node.typeArguments !== typeArguments + || node.typeArguments !== typeArguments ? update(createTypeQueryNode(exprName, typeArguments), node) : node; } @@ -2373,9 +2514,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateNamedTupleMember(node: NamedTupleMember, dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode) { return node.dotDotDotToken !== dotDotDotToken - || node.name !== name - || node.questionToken !== questionToken - || node.type !== type + || node.name !== name + || node.questionToken !== questionToken + || node.type !== type ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node) : node; } @@ -2460,9 +2601,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode) { return node.checkType !== checkType - || node.extendsType !== extendsType - || node.trueType !== trueType - || node.falseType !== falseType + || node.extendsType !== extendsType + || node.trueType !== trueType + || node.falseType !== falseType ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) : node; } @@ -2494,7 +2635,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTemplateLiteralType(node: TemplateLiteralTypeNode, head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]) { return node.head !== head - || node.templateSpans !== templateSpans + || node.templateSpans !== templateSpans ? update(createTemplateLiteralType(head, templateSpans), node) : node; } @@ -2505,7 +2646,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode assertions?: ImportTypeAssertionContainer, qualifier?: EntityName, typeArguments?: readonly TypeNode[], - isTypeOf = false + isTypeOf = false, ): ImportTypeNode { const node = createBaseNode(SyntaxKind.ImportType); node.argument = argument; @@ -2524,13 +2665,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode assertions: ImportTypeAssertionContainer | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, - isTypeOf: boolean = node.isTypeOf + isTypeOf: boolean = node.isTypeOf, ): ImportTypeNode { return node.argument !== argument - || node.assertions !== assertions - || node.qualifier !== qualifier - || node.typeArguments !== typeArguments - || node.isTypeOf !== isTypeOf + || node.assertions !== assertions + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf ? update(createImportTypeNode(argument, assertions, qualifier, typeArguments, isTypeOf), node) : node; } @@ -2587,7 +2728,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) { return node.objectType !== objectType - || node.indexType !== indexType + || node.indexType !== indexType ? update(createIndexedAccessTypeNode(objectType, indexType), node) : node; } @@ -2611,11 +2752,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: readonly TypeElement[] | undefined): MappedTypeNode { return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.nameType !== nameType - || node.questionToken !== questionToken - || node.type !== type - || node.members !== members + || node.typeParameter !== typeParameter + || node.nameType !== nameType + || node.questionToken !== questionToken + || node.type !== type + || node.members !== members ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) : node; } @@ -2643,13 +2784,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createObjectBindingPattern(elements: readonly BindingElement[]) { const node = createBaseNode(SyntaxKind.ObjectBindingPattern); node.elements = createNodeArray(elements); - node.transformFlags |= - propagateChildrenFlags(node.elements) | + node.transformFlags |= propagateChildrenFlags(node.elements) | TransformFlags.ContainsES2015 | TransformFlags.ContainsBindingPattern; if (node.transformFlags & TransformFlags.ContainsRestOrSpread) { - node.transformFlags |= - TransformFlags.ContainsES2018 | + node.transformFlags |= TransformFlags.ContainsES2018 | TransformFlags.ContainsObjectRestOrSpread; } return node; @@ -2666,8 +2805,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createArrayBindingPattern(elements: readonly ArrayBindingElement[]) { const node = createBaseNode(SyntaxKind.ArrayBindingPattern); node.elements = createNodeArray(elements); - node.transformFlags |= - propagateChildrenFlags(node.elements) | + node.transformFlags |= propagateChildrenFlags(node.elements) | TransformFlags.ContainsES2015 | TransformFlags.ContainsBindingPattern; return node; @@ -2687,8 +2825,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.propertyName = asName(propertyName); node.name = asName(name); node.initializer = asInitializer(initializer); - node.transformFlags |= - propagateChildFlags(node.dotDotDotToken) | + node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | propagateNameFlags(node.propertyName) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | @@ -2702,9 +2839,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined) { return node.propertyName !== propertyName - || node.dotDotDotToken !== dotDotDotToken - || node.name !== name - || node.initializer !== initializer + || node.dotDotDotToken !== dotDotDotToken + || node.name !== name + || node.initializer !== initializer ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) : node; } @@ -2757,8 +2894,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.expression = expression; node.questionDotToken = questionDotToken; node.name = name; - node.transformFlags = - propagateChildFlags(node.expression) | + node.transformFlags = propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (isIdentifier(node.name) ? propagateIdentifierNameFlags(node.name) : @@ -2774,13 +2910,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBasePropertyAccessExpression( parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false), /*questionDotToken*/ undefined, - asName(name) + asName(name), ); if (isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators - node.transformFlags |= - TransformFlags.ContainsES2017 | + node.transformFlags |= TransformFlags.ContainsES2017 | TransformFlags.ContainsES2018; } return node; @@ -2792,7 +2927,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return updatePropertyAccessChain(node, expression, node.questionDotToken, cast(name, isIdentifier)); } return node.expression !== expression - || node.name !== name + || node.name !== name ? update(createPropertyAccessExpression(expression, name), node) : node; } @@ -2802,7 +2937,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBasePropertyAccessExpression( parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), questionDotToken, - asName(name) + asName(name), ) as Mutable; node.flags |= NodeFlags.OptionalChain; node.transformFlags |= TransformFlags.ContainsES2020; @@ -2815,8 +2950,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression - || node.questionDotToken !== questionDotToken - || node.name !== name + || node.questionDotToken !== questionDotToken + || node.name !== name ? update(createPropertyAccessChain(expression, questionDotToken, name), node) : node; } @@ -2826,8 +2961,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.expression = expression; node.questionDotToken = questionDotToken; node.argumentExpression = argumentExpression; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression); @@ -2841,13 +2975,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseElementAccessExpression( parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false), /*questionDotToken*/ undefined, - asExpression(index) + asExpression(index), ); if (isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators - node.transformFlags |= - TransformFlags.ContainsES2017 | + node.transformFlags |= TransformFlags.ContainsES2017 | TransformFlags.ContainsES2018; } return node; @@ -2859,7 +2992,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); } return node.expression !== expression - || node.argumentExpression !== argumentExpression + || node.argumentExpression !== argumentExpression ? update(createElementAccessExpression(expression, argumentExpression), node) : node; } @@ -2869,7 +3002,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseElementAccessExpression( parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), questionDotToken, - asExpression(index) + asExpression(index), ) as Mutable; node.flags |= NodeFlags.OptionalChain; node.transformFlags |= TransformFlags.ContainsES2020; @@ -2882,8 +3015,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // Because we are updating an existing ElementAccessChain we want to inherit its emitFlags // instead of using the default from createElementAccess return node.expression !== expression - || node.questionDotToken !== questionDotToken - || node.argumentExpression !== argumentExpression + || node.questionDotToken !== questionDotToken + || node.argumentExpression !== argumentExpression ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node) : node; } @@ -2894,8 +3027,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.questionDotToken = questionDotToken; node.typeArguments = typeArguments; node.arguments = argumentsArray; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments); @@ -2928,8 +3060,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); } return node.expression !== expression - || node.typeArguments !== typeArguments - || node.arguments !== argumentsArray + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? update(createCallExpression(expression, typeArguments, argumentsArray), node) : node; } @@ -2940,7 +3072,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), questionDotToken, asNodeArray(typeArguments), - parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)) + parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)), ) as Mutable; node.flags |= NodeFlags.OptionalChain; node.transformFlags |= TransformFlags.ContainsES2020; @@ -2951,9 +3083,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function updateCallChain(node: CallChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]) { Debug.assert(!!(node.flags & NodeFlags.OptionalChain), "Cannot update a CallExpression using updateCallChain. Use updateCall instead."); return node.expression !== expression - || node.questionDotToken !== questionDotToken - || node.typeArguments !== typeArguments - || node.arguments !== argumentsArray + || node.questionDotToken !== questionDotToken + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node) : node; } @@ -2964,8 +3096,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | TransformFlags.ContainsES2020; @@ -2978,8 +3109,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateNewExpression(node: NewExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined) { return node.expression !== expression - || node.typeArguments !== typeArguments - || node.arguments !== argumentsArray + || node.typeArguments !== typeArguments + || node.arguments !== argumentsArray ? update(createNewExpression(expression, typeArguments, argumentsArray), node) : node; } @@ -2990,8 +3121,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); node.typeArguments = asNodeArray(typeArguments); node.template = template; - node.transformFlags |= - propagateChildFlags(node.tag) | + node.transformFlags |= propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | TransformFlags.ContainsES2015; @@ -3007,8 +3137,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral) { return node.tag !== tag - || node.typeArguments !== typeArguments - || node.template !== template + || node.typeArguments !== typeArguments + || node.template !== template ? update(createTaggedTemplateExpression(tag, typeArguments, template), node) : node; } @@ -3018,8 +3148,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.TypeAssertionExpression); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | TransformFlags.ContainsTypeScript; return node; @@ -3028,7 +3157,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression) { return node.type !== type - || node.expression !== expression + || node.expression !== expression ? update(createTypeAssertion(type, expression), node) : node; } @@ -3058,7 +3187,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[] | undefined, type: TypeNode | undefined, - body: Block + body: Block, ) { const node = createBaseDeclaration(SyntaxKind.FunctionExpression); node.modifiers = asNodeArray(modifiers); @@ -3073,8 +3202,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const isGenerator = !!node.asteriskToken; const isAsyncGenerator = isAsync && isGenerator; - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | @@ -3107,15 +3235,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, - body: Block + body: Block, ) { return node.name !== name - || node.modifiers !== modifiers - || node.asteriskToken !== asteriskToken - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.body !== body + || node.modifiers !== modifiers + || node.asteriskToken !== asteriskToken + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } @@ -3127,7 +3255,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, - body: ConciseBody + body: ConciseBody, ) { const node = createBaseDeclaration(SyntaxKind.ArrowFunction); node.modifiers = asNodeArray(modifiers); @@ -3139,8 +3267,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const isAsync = modifiersToFlags(node.modifiers) & ModifierFlags.Async; - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | @@ -3168,14 +3295,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken, - body: ConciseBody + body: ConciseBody, ): ArrowFunction { return node.modifiers !== modifiers - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.equalsGreaterThanToken !== equalsGreaterThanToken - || node.body !== body + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken + || node.body !== body ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } @@ -3229,8 +3356,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createAwaitExpression(expression: Expression) { const node = createBaseNode(SyntaxKind.AwaitExpression); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2017 | TransformFlags.ContainsES2018 | TransformFlags.ContainsAwait; @@ -3252,10 +3378,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.transformFlags |= propagateChildFlags(node.operand); // Only set this flag for non-generated identifiers and non-"local" names. See the // comment in `visitPreOrPostfixUnaryExpression` in module.ts - if ((operator === SyntaxKind.PlusPlusToken || operator === SyntaxKind.MinusMinusToken) && + if ( + (operator === SyntaxKind.PlusPlusToken || operator === SyntaxKind.MinusMinusToken) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && - !isLocalName(node.operand)) { + !isLocalName(node.operand) + ) { node.transformFlags |= TransformFlags.ContainsUpdateExpressionForIdentifier; } return node; @@ -3276,9 +3404,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.transformFlags |= propagateChildFlags(node.operand); // Only set this flag for non-generated identifiers and non-"local" names. See the // comment in `visitPreOrPostfixUnaryExpression` in module.ts - if (isIdentifier(node.operand) && + if ( + isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && - !isLocalName(node.operand)) { + !isLocalName(node.operand) + ) { node.transformFlags |= TransformFlags.ContainsUpdateExpressionForIdentifier; } return node; @@ -3299,8 +3429,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); node.operatorToken = operatorToken; node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right); - node.transformFlags |= - propagateChildFlags(node.left) | + node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === SyntaxKind.QuestionQuestionToken) { @@ -3308,15 +3437,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } else if (operatorKind === SyntaxKind.EqualsToken) { if (isObjectLiteralExpression(node.left)) { - node.transformFlags |= - TransformFlags.ContainsES2015 | + node.transformFlags |= TransformFlags.ContainsES2015 | TransformFlags.ContainsES2018 | TransformFlags.ContainsDestructuringAssignment | propagateAssignmentPatternFlags(node.left); } else if (isArrayLiteralExpression(node.left)) { - node.transformFlags |= - TransformFlags.ContainsES2015 | + node.transformFlags |= TransformFlags.ContainsES2015 | TransformFlags.ContainsDestructuringAssignment | propagateAssignmentPatternFlags(node.left); } @@ -3342,8 +3469,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateBinaryExpression(node: BinaryExpression, left: Expression, operator: BinaryOperatorToken, right: Expression) { return node.left !== left - || node.operatorToken !== operator - || node.right !== right + || node.operatorToken !== operator + || node.right !== right ? update(createBinaryExpression(left, operator, right), node) : node; } @@ -3356,8 +3483,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); node.colonToken = colonToken ?? createToken(SyntaxKind.ColonToken); node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse); - node.transformFlags |= - propagateChildFlags(node.condition) | + node.transformFlags |= propagateChildFlags(node.condition) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.whenTrue) | propagateChildFlags(node.colonToken) | @@ -3372,13 +3498,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode questionToken: Token, whenTrue: Expression, colonToken: Token, - whenFalse: Expression + whenFalse: Expression, ): ConditionalExpression { return node.condition !== condition - || node.questionToken !== questionToken - || node.whenTrue !== whenTrue - || node.colonToken !== colonToken - || node.whenFalse !== whenFalse + || node.questionToken !== questionToken + || node.whenTrue !== whenTrue + || node.colonToken !== colonToken + || node.whenFalse !== whenFalse ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; } @@ -3388,8 +3514,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.TemplateExpression); node.head = head; node.templateSpans = createNodeArray(templateSpans); - node.transformFlags |= - propagateChildFlags(node.head) | + node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | TransformFlags.ContainsES2015; return node; @@ -3398,7 +3523,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: readonly TemplateSpan[]) { return node.head !== head - || node.templateSpans !== templateSpans + || node.templateSpans !== templateSpans ? update(createTemplateExpression(head, templateSpans), node) : node; } @@ -3493,8 +3618,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.YieldExpression); node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.asteriskToken = asteriskToken; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | TransformFlags.ContainsES2015 | TransformFlags.ContainsES2018 | @@ -3505,7 +3629,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateYieldExpression(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression) { return node.expression !== expression - || node.asteriskToken !== asteriskToken + || node.asteriskToken !== asteriskToken ? update(createYieldExpression(asteriskToken, expression), node) : node; } @@ -3514,8 +3638,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createSpreadElement(expression: Expression) { const node = createBaseNode(SyntaxKind.SpreadElement); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2015 | TransformFlags.ContainsRestOrSpread; return node; @@ -3534,7 +3657,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, - members: readonly ClassElement[] + members: readonly ClassElement[], ) { const node = createBaseDeclaration(SyntaxKind.ClassExpression); node.modifiers = asNodeArray(modifiers); @@ -3542,8 +3665,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.typeParameters = asNodeArray(typeParameters); node.heritageClauses = asNodeArray(heritageClauses); node.members = createNodeArray(members); - node.transformFlags |= - propagateChildrenFlags(node.modifiers) | + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | @@ -3562,13 +3684,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, - members: readonly ClassElement[] + members: readonly ClassElement[], ) { return node.modifiers !== modifiers - || node.name !== name - || node.typeParameters !== typeParameters - || node.heritageClauses !== heritageClauses - || node.members !== members + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) : node; } @@ -3583,8 +3705,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.ExpressionWithTypeArguments); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | TransformFlags.ContainsES2015; return node; @@ -3593,7 +3714,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments: readonly TypeNode[] | undefined) { return node.expression !== expression - || node.typeArguments !== typeArguments + || node.typeArguments !== typeArguments ? update(createExpressionWithTypeArguments(expression, typeArguments), node) : node; } @@ -3603,8 +3724,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.AsExpression); node.expression = expression; node.type = type; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | TransformFlags.ContainsTypeScript; return node; @@ -3613,7 +3733,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode) { return node.expression !== expression - || node.type !== type + || node.type !== type ? update(createAsExpression(expression, type), node) : node; } @@ -3622,8 +3742,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createNonNullExpression(expression: Expression) { const node = createBaseNode(SyntaxKind.NonNullExpression); node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsTypeScript; return node; } @@ -3643,8 +3762,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.SatisfiesExpression); node.expression = expression; node.type = type; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.type) | TransformFlags.ContainsTypeScript; return node; @@ -3653,7 +3771,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode) { return node.expression !== expression - || node.type !== type + || node.type !== type ? update(createSatisfiesExpression(expression, type), node) : node; } @@ -3663,8 +3781,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.NonNullExpression); node.flags |= NodeFlags.OptionalChain; node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsTypeScript; return node; } @@ -3714,8 +3831,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.TemplateSpan); node.expression = expression; node.literal = literal; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | TransformFlags.ContainsES2015; return node; @@ -3724,7 +3840,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail) { return node.expression !== expression - || node.literal !== literal + || node.literal !== literal ? update(createTemplateSpan(expression, literal), node) : node; } @@ -3765,8 +3881,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.VariableStatement); node.modifiers = asNodeArray(modifiers); node.declarationList = isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; - node.transformFlags |= - propagateChildrenFlags(node.modifiers) | + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.declarationList); if (modifiersToFlags(node.modifiers) & ModifierFlags.Ambient) { node.transformFlags = TransformFlags.ContainsTypeScript; @@ -3780,7 +3895,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateVariableStatement(node: VariableStatement, modifiers: readonly ModifierLike[] | undefined, declarationList: VariableDeclarationList) { return node.modifiers !== modifiers - || node.declarationList !== declarationList + || node.declarationList !== declarationList ? update(createVariableStatement(modifiers, declarationList), node) : node; } @@ -3816,8 +3931,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); node.elseStatement = asEmbeddedStatement(elseStatement); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thenStatement) | propagateChildFlags(node.elseStatement); @@ -3829,8 +3943,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateIfStatement(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined) { return node.expression !== expression - || node.thenStatement !== thenStatement - || node.elseStatement !== elseStatement + || node.thenStatement !== thenStatement + || node.elseStatement !== elseStatement ? update(createIfStatement(expression, thenStatement, elseStatement), node) : node; } @@ -3840,8 +3954,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.DoStatement); node.statement = asEmbeddedStatement(statement); node.expression = expression; - node.transformFlags |= - propagateChildFlags(node.statement) | + node.transformFlags |= propagateChildFlags(node.statement) | propagateChildFlags(node.expression); node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -3852,7 +3965,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateDoStatement(node: DoStatement, statement: Statement, expression: Expression) { return node.statement !== statement - || node.expression !== expression + || node.expression !== expression ? update(createDoStatement(statement, expression), node) : node; } @@ -3862,8 +3975,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.WhileStatement); node.expression = expression; node.statement = asEmbeddedStatement(statement); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.statement); node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -3874,7 +3986,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateWhileStatement(node: WhileStatement, expression: Expression, statement: Statement) { return node.expression !== expression - || node.statement !== statement + || node.statement !== statement ? update(createWhileStatement(expression, statement), node) : node; } @@ -3886,8 +3998,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.condition = condition; node.incrementor = incrementor; node.statement = asEmbeddedStatement(statement); - node.transformFlags |= - propagateChildFlags(node.initializer) | + node.transformFlags |= propagateChildFlags(node.initializer) | propagateChildFlags(node.condition) | propagateChildFlags(node.incrementor) | propagateChildFlags(node.statement); @@ -3902,9 +4013,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateForStatement(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement) { return node.initializer !== initializer - || node.condition !== condition - || node.incrementor !== incrementor - || node.statement !== statement + || node.condition !== condition + || node.incrementor !== incrementor + || node.statement !== statement ? update(createForStatement(initializer, condition, incrementor, statement), node) : node; } @@ -3915,8 +4026,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.initializer = initializer; node.expression = expression; node.statement = asEmbeddedStatement(statement); - node.transformFlags |= - propagateChildFlags(node.initializer) | + node.transformFlags |= propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement); @@ -3930,8 +4040,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateForInStatement(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement) { return node.initializer !== initializer - || node.expression !== expression - || node.statement !== statement + || node.expression !== expression + || node.statement !== statement ? update(createForInStatement(initializer, expression, statement), node) : node; } @@ -3943,8 +4053,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.initializer = initializer; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statement = asEmbeddedStatement(statement); - node.transformFlags |= - propagateChildFlags(node.awaitModifier) | + node.transformFlags |= propagateChildFlags(node.awaitModifier) | propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | @@ -3961,9 +4070,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateForOfStatement(node: ForOfStatement, awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement) { return node.awaitModifier !== awaitModifier - || node.initializer !== initializer - || node.expression !== expression - || node.statement !== statement + || node.initializer !== initializer + || node.expression !== expression + || node.statement !== statement ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node) : node; } @@ -3972,8 +4081,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createContinueStatement(label?: string | Identifier): ContinueStatement { const node = createBaseNode(SyntaxKind.ContinueStatement); node.label = asName(label); - node.transformFlags |= - propagateChildFlags(node.label) | + node.transformFlags |= propagateChildFlags(node.label) | TransformFlags.ContainsHoistedDeclarationOrCompletion; node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -3992,8 +4100,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createBreakStatement(label?: string | Identifier): BreakStatement { const node = createBaseNode(SyntaxKind.BreakStatement); node.label = asName(label); - node.transformFlags |= - propagateChildFlags(node.label) | + node.transformFlags |= propagateChildFlags(node.label) | TransformFlags.ContainsHoistedDeclarationOrCompletion; node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -4013,8 +4120,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.ReturnStatement); node.expression = expression; // return in an ES2018 async generator must be awaited - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2018 | TransformFlags.ContainsHoistedDeclarationOrCompletion; @@ -4035,8 +4141,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.WithStatement); node.expression = expression; node.statement = asEmbeddedStatement(statement); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.statement); node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -4047,7 +4152,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateWithStatement(node: WithStatement, expression: Expression, statement: Statement) { return node.expression !== expression - || node.statement !== statement + || node.statement !== statement ? update(createWithStatement(expression, statement), node) : node; } @@ -4057,8 +4162,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.SwitchStatement); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.caseBlock = caseBlock; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.caseBlock); node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -4070,7 +4174,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateSwitchStatement(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock) { return node.expression !== expression - || node.caseBlock !== caseBlock + || node.caseBlock !== caseBlock ? update(createSwitchStatement(expression, caseBlock), node) : node; } @@ -4080,8 +4184,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.LabeledStatement); node.label = asName(label); node.statement = asEmbeddedStatement(statement); - node.transformFlags |= - propagateChildFlags(node.label) | + node.transformFlags |= propagateChildFlags(node.label) | propagateChildFlags(node.statement); node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -4092,7 +4195,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateLabeledStatement(node: LabeledStatement, label: Identifier, statement: Statement) { return node.label !== label - || node.statement !== statement + || node.statement !== statement ? update(createLabeledStatement(label, statement), node) : node; } @@ -4121,8 +4224,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; - node.transformFlags |= - propagateChildFlags(node.tryBlock) | + node.transformFlags |= propagateChildFlags(node.tryBlock) | propagateChildFlags(node.catchClause) | propagateChildFlags(node.finallyBlock); @@ -4134,8 +4236,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateTryStatement(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined) { return node.tryBlock !== tryBlock - || node.catchClause !== catchClause - || node.finallyBlock !== finallyBlock + || node.catchClause !== catchClause + || node.finallyBlock !== finallyBlock ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node) : node; } @@ -4156,8 +4258,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.exclamationToken = exclamationToken; node.type = type; node.initializer = asInitializer(initializer); - node.transformFlags |= - propagateNameFlags(node.name) | + node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | (node.exclamationToken ?? node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None); @@ -4168,9 +4269,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { return node.name !== name - || node.type !== type - || node.exclamationToken !== exclamationToken - || node.initializer !== initializer + || node.type !== type + || node.exclamationToken !== exclamationToken + || node.initializer !== initializer ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node) : node; } @@ -4180,12 +4281,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.VariableDeclarationList); node.flags |= flags & NodeFlags.BlockScoped; node.declarations = createNodeArray(declarations); - node.transformFlags |= - propagateChildrenFlags(node.declarations) | + node.transformFlags |= propagateChildrenFlags(node.declarations) | TransformFlags.ContainsHoistedDeclarationOrCompletion; if (flags & NodeFlags.BlockScoped) { - node.transformFlags |= - TransformFlags.ContainsES2015 | + node.transformFlags |= TransformFlags.ContainsES2015 | TransformFlags.ContainsBlockScopedBinding; } if (flags & NodeFlags.Using) { @@ -4209,7 +4308,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, - body: Block | undefined + body: Block | undefined, ) { const node = createBaseDeclaration(SyntaxKind.FunctionDeclaration); node.modifiers = asNodeArray(modifiers); @@ -4228,8 +4327,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const isGenerator = !!node.asteriskToken; const isAsyncGenerator = isAsync && isGenerator; - node.transformFlags = - propagateChildrenFlags(node.modifiers) | + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.asteriskToken) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | @@ -4262,15 +4360,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, - body: Block | undefined + body: Block | undefined, ) { return node.modifiers !== modifiers - || node.asteriskToken !== asteriskToken - || node.name !== name - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.body !== body + || node.asteriskToken !== asteriskToken + || node.name !== name + || node.typeParameters !== typeParameters + || node.parameters !== parameters + || node.type !== type + || node.body !== body ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) : node; } @@ -4279,7 +4377,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode if (updated !== original) { // copy children used only for error reporting if (updated.modifiers === original.modifiers) { - updated.modifiers = original.modifiers; + updated.modifiers = original.modifiers; } } return finishUpdateBaseSignatureDeclaration(updated, original); @@ -4291,7 +4389,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, - members: readonly ClassElement[] + members: readonly ClassElement[], ) { const node = createBaseDeclaration(SyntaxKind.ClassDeclaration); node.modifiers = asNodeArray(modifiers); @@ -4304,8 +4402,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.transformFlags = TransformFlags.ContainsTypeScript; } else { - node.transformFlags |= - propagateChildrenFlags(node.modifiers) | + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | @@ -4328,13 +4425,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, - members: readonly ClassElement[] + members: readonly ClassElement[], ) { return node.modifiers !== modifiers - || node.name !== name - || node.typeParameters !== typeParameters - || node.heritageClauses !== heritageClauses - || node.members !== members + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } @@ -4345,7 +4442,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, - members: readonly TypeElement[] + members: readonly TypeElement[], ) { const node = createBaseDeclaration(SyntaxKind.InterfaceDeclaration); node.modifiers = asNodeArray(modifiers); @@ -4366,13 +4463,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, - members: readonly TypeElement[] + members: readonly TypeElement[], ) { return node.modifiers !== modifiers - || node.name !== name - || node.typeParameters !== typeParameters - || node.heritageClauses !== heritageClauses - || node.members !== members + || node.name !== name + || node.typeParameters !== typeParameters + || node.heritageClauses !== heritageClauses + || node.members !== members ? update(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) : node; } @@ -4382,7 +4479,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, - type: TypeNode + type: TypeNode, ) { const node = createBaseDeclaration(SyntaxKind.TypeAliasDeclaration); node.modifiers = asNodeArray(modifiers); @@ -4403,12 +4500,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, - type: TypeNode + type: TypeNode, ) { return node.modifiers !== modifiers - || node.name !== name - || node.typeParameters !== typeParameters - || node.type !== type + || node.name !== name + || node.typeParameters !== typeParameters + || node.type !== type ? update(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) : node; } @@ -4417,14 +4514,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createEnumDeclaration( modifiers: readonly ModifierLike[] | undefined, name: string | Identifier, - members: readonly EnumMember[] + members: readonly EnumMember[], ) { const node = createBaseDeclaration(SyntaxKind.EnumDeclaration); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.members = createNodeArray(members); - node.transformFlags |= - propagateChildrenFlags(node.modifiers) | + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.name) | propagateChildrenFlags(node.members) | TransformFlags.ContainsTypeScript; @@ -4439,10 +4535,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: EnumDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, - members: readonly EnumMember[]) { + members: readonly EnumMember[], + ) { return node.modifiers !== modifiers - || node.name !== name - || node.members !== members + || node.name !== name + || node.members !== members ? update(createEnumDeclaration(modifiers, name, members), node) : node; } @@ -4452,7 +4549,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, name: ModuleName, body: ModuleBody | undefined, - flags = NodeFlags.None + flags = NodeFlags.None, ) { const node = createBaseDeclaration(SyntaxKind.ModuleDeclaration); node.modifiers = asNodeArray(modifiers); @@ -4463,8 +4560,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.transformFlags = TransformFlags.ContainsTypeScript; } else { - node.transformFlags |= - propagateChildrenFlags(node.modifiers) | + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.name) | propagateChildFlags(node.body) | TransformFlags.ContainsTypeScript; @@ -4482,11 +4578,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: ModuleDeclaration, modifiers: readonly ModifierLike[] | undefined, name: ModuleName, - body: ModuleBody | undefined + body: ModuleBody | undefined, ) { return node.modifiers !== modifiers - || node.name !== name - || node.body !== body + || node.name !== name + || node.body !== body ? update(createModuleDeclaration(modifiers, name, body, node.flags), node) : node; } @@ -4530,8 +4626,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createNamespaceExportDeclaration(name: string | Identifier) { const node = createBaseDeclaration(SyntaxKind.NamespaceExportDeclaration); node.name = asName(name); - node.transformFlags |= - propagateIdentifierNameFlags(node.name) | + node.transformFlags |= propagateIdentifierNameFlags(node.name) | TransformFlags.ContainsTypeScript; node.modifiers = undefined; // initialized by parser to report grammar errors @@ -4559,15 +4654,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: string | Identifier, - moduleReference: ModuleReference + moduleReference: ModuleReference, ) { const node = createBaseDeclaration(SyntaxKind.ImportEqualsDeclaration); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.isTypeOnly = isTypeOnly; node.moduleReference = moduleReference; - node.transformFlags |= - propagateChildrenFlags(node.modifiers) | + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateIdentifierNameFlags(node.name) | propagateChildFlags(node.moduleReference); @@ -4587,12 +4681,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: Identifier, - moduleReference: ModuleReference + moduleReference: ModuleReference, ) { return node.modifiers !== modifiers - || node.isTypeOnly !== isTypeOnly - || node.name !== name - || node.moduleReference !== moduleReference + || node.isTypeOnly !== isTypeOnly + || node.name !== name + || node.moduleReference !== moduleReference ? update(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) : node; } @@ -4602,15 +4696,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, - assertClause: AssertClause | undefined + assertClause: AssertClause | undefined, ): ImportDeclaration { const node = createBaseNode(SyntaxKind.ImportDeclaration); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; - node.transformFlags |= - propagateChildFlags(node.importClause) | + node.transformFlags |= propagateChildFlags(node.importClause) | propagateChildFlags(node.moduleSpecifier); node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context @@ -4624,12 +4717,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, - assertClause: AssertClause | undefined + assertClause: AssertClause | undefined, ) { return node.modifiers !== modifiers - || node.importClause !== importClause - || node.moduleSpecifier !== moduleSpecifier - || node.assertClause !== assertClause + || node.importClause !== importClause + || node.moduleSpecifier !== moduleSpecifier + || node.assertClause !== assertClause ? update(createImportDeclaration(modifiers, importClause, moduleSpecifier, assertClause), node) : node; } @@ -4640,8 +4733,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; - node.transformFlags |= - propagateChildFlags(node.name) | + node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.namedBindings); if (isTypeOnly) { node.transformFlags |= TransformFlags.ContainsTypeScript; @@ -4653,8 +4745,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined) { return node.isTypeOnly !== isTypeOnly - || node.name !== name - || node.namedBindings !== namedBindings + || node.name !== name + || node.namedBindings !== namedBindings ? update(createImportClause(isTypeOnly, name, namedBindings), node) : node; } @@ -4671,7 +4763,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateAssertClause(node: AssertClause, elements: readonly AssertEntry[], multiLine?: boolean): AssertClause { return node.elements !== elements - || node.multiLine !== multiLine + || node.multiLine !== multiLine ? update(createAssertClause(elements, multiLine), node) : node; } @@ -4688,7 +4780,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry { return node.name !== name - || node.value !== value + || node.value !== value ? update(createAssertEntry(name, value), node) : node; } @@ -4704,7 +4796,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateImportTypeAssertionContainer(node: ImportTypeAssertionContainer, clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer { return node.assertClause !== clause - || node.multiLine !== multiLine + || node.multiLine !== multiLine ? update(createImportTypeAssertionContainer(clause, multiLine), node) : node; } @@ -4729,8 +4821,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createNamespaceExport(name: Identifier): NamespaceExport { const node = createBaseDeclaration(SyntaxKind.NamespaceExport); node.name = name; - node.transformFlags |= - propagateChildFlags(node.name) | + node.transformFlags |= propagateChildFlags(node.name) | TransformFlags.ContainsES2020; node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context return node; @@ -4765,8 +4856,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.isTypeOnly = isTypeOnly; node.propertyName = propertyName; node.name = name; - node.transformFlags |= - propagateChildFlags(node.propertyName) | + node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context return node; @@ -4775,8 +4865,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) { return node.isTypeOnly !== isTypeOnly - || node.propertyName !== propertyName - || node.name !== name + || node.propertyName !== propertyName + || node.name !== name ? update(createImportSpecifier(isTypeOnly, propertyName, name), node) : node; } @@ -4785,7 +4875,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createExportAssignment( modifiers: readonly ModifierLike[] | undefined, isExportEquals: boolean | undefined, - expression: Expression + expression: Expression, ) { const node = createBaseDeclaration(SyntaxKind.ExportAssignment); node.modifiers = asNodeArray(modifiers); @@ -4804,10 +4894,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function updateExportAssignment( node: ExportAssignment, modifiers: readonly ModifierLike[] | undefined, - expression: Expression + expression: Expression, ) { return node.modifiers !== modifiers - || node.expression !== expression + || node.expression !== expression ? update(createExportAssignment(modifiers, node.isExportEquals, expression), node) : node; } @@ -4818,7 +4908,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, - assertClause?: AssertClause + assertClause?: AssertClause, ) { const node = createBaseDeclaration(SyntaxKind.ExportDeclaration); node.modifiers = asNodeArray(modifiers); @@ -4826,8 +4916,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.exportClause = exportClause; node.moduleSpecifier = moduleSpecifier; node.assertClause = assertClause; - node.transformFlags |= - propagateChildrenFlags(node.modifiers) | + node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.exportClause) | propagateChildFlags(node.moduleSpecifier); node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context @@ -4843,13 +4932,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, - assertClause: AssertClause | undefined + assertClause: AssertClause | undefined, ) { return node.modifiers !== modifiers - || node.isTypeOnly !== isTypeOnly - || node.exportClause !== exportClause - || node.moduleSpecifier !== moduleSpecifier - || node.assertClause !== assertClause + || node.isTypeOnly !== isTypeOnly + || node.exportClause !== exportClause + || node.moduleSpecifier !== moduleSpecifier + || node.assertClause !== assertClause ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node) : node; } @@ -4886,8 +4975,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.isTypeOnly = isTypeOnly; node.propertyName = asName(propertyName); node.name = asName(name); - node.transformFlags |= - propagateChildFlags(node.propertyName) | + node.transformFlags |= propagateChildFlags(node.propertyName) | propagateChildFlags(node.name); node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context @@ -4898,8 +4986,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) { return node.isTypeOnly !== isTypeOnly - || node.propertyName !== propertyName - || node.name !== name + || node.propertyName !== propertyName + || node.name !== name ? update(createExportSpecifier(isTypeOnly, propertyName, name), node) : node; } @@ -4946,10 +5034,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api // createJSDocNullableType // createJSDocNonNullableType - function createJSDocPrePostfixUnaryTypeWorker(kind: T["kind"], type: T["type"], postfix = false): T { + function createJSDocPrePostfixUnaryTypeWorker(kind: T["kind"], type: T["type"], postfix = false): T { const node = createJSDocUnaryTypeWorker( kind, - postfix ? type && parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(type) : type + postfix ? type && parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(type) : type, ) as Mutable; node.postfix = postfix; return node; @@ -4970,8 +5058,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // updateJSDocNullableType function updateJSDocPrePostfixUnaryTypeWorker(kind: T["kind"], node: T, type: T["type"]): T { return node.type !== type - ? update(createJSDocPrePostfixUnaryTypeWorker(kind, type, node.postfix), node) - : node; + ? update(createJSDocPrePostfixUnaryTypeWorker(kind, type, node.postfix), node) + : node; } // @api @@ -4989,8 +5077,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseDeclaration(SyntaxKind.JSDocFunctionType); node.parameters = asNodeArray(parameters); node.type = type; - node.transformFlags = - propagateChildrenFlags(node.parameters) | + node.transformFlags = propagateChildrenFlags(node.parameters) | (node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None); node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -5003,7 +5090,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocFunctionType(node: JSDocFunctionType, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType { return node.parameters !== parameters - || node.type !== type + || node.type !== type ? update(createJSDocFunctionType(parameters, type), node) : node; } @@ -5019,7 +5106,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocTypeLiteral(node: JSDocTypeLiteral, propertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean): JSDocTypeLiteral { return node.jsDocPropertyTags !== propertyTags - || node.isArrayType !== isArrayType + || node.isArrayType !== isArrayType ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node) : node; } @@ -5054,8 +5141,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature { return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type + || node.parameters !== parameters + || node.type !== type ? update(createJSDocSignature(typeParameters, parameters, type), node) : node; } @@ -5093,9 +5180,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier = getDefaultTagName(node), constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag { return node.tagName !== tagName - || node.constraint !== constraint - || node.typeParameters !== typeParameters - || node.comment !== comment + || node.constraint !== constraint + || node.typeParameters !== typeParameters + || node.comment !== comment ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node) : node; } @@ -5115,9 +5202,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag { return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.fullName !== fullName - || node.comment !== comment + || node.typeExpression !== typeExpression + || node.fullName !== fullName + || node.comment !== comment ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node) : node; } @@ -5135,11 +5222,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag { return node.tagName !== tagName - || node.name !== name - || node.isBracketed !== isBracketed - || node.typeExpression !== typeExpression - || node.isNameFirst !== isNameFirst - || node.comment !== comment + || node.name !== name + || node.isBracketed !== isBracketed + || node.typeExpression !== typeExpression + || node.isNameFirst !== isNameFirst + || node.comment !== comment ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node; } @@ -5157,11 +5244,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag { return node.tagName !== tagName - || node.name !== name - || node.isBracketed !== isBracketed - || node.typeExpression !== typeExpression - || node.isNameFirst !== isNameFirst - || node.comment !== comment + || node.name !== name + || node.isBracketed !== isBracketed + || node.typeExpression !== typeExpression + || node.isNameFirst !== isNameFirst + || node.comment !== comment ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) : node; } @@ -5181,9 +5268,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag { return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.fullName !== fullName - || node.comment !== comment + || node.typeExpression !== typeExpression + || node.fullName !== fullName + || node.comment !== comment ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node) : node; } @@ -5198,8 +5285,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocOverloadTag(node: JSDocOverloadTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, comment: string | NodeArray | undefined): JSDocOverloadTag { return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.comment !== comment + || node.typeExpression !== typeExpression + || node.comment !== comment ? update(createJSDocOverloadTag(tagName, typeExpression, comment), node) : node; } @@ -5214,8 +5301,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag { return node.tagName !== tagName - || node.class !== className - || node.comment !== comment + || node.class !== className + || node.comment !== comment ? update(createJSDocAugmentsTag(tagName, className, comment), node) : node; } @@ -5237,8 +5324,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { return node.tagName !== tagName - || node.name !== name - || node.comment !== comment + || node.name !== name + || node.comment !== comment ? update(createJSDocSeeTag(tagName, name, comment), node) : node; } @@ -5262,8 +5349,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.JSDocMemberName); node.left = left; node.right = right; - node.transformFlags |= - propagateChildFlags(node.left) | + node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.right); return node; } @@ -5271,7 +5357,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocMemberName(node: JSDocMemberName, left: EntityName | JSDocMemberName, right: Identifier) { return node.left !== left - || node.right !== right + || node.right !== right ? update(createJSDocMemberName(left, right), node) : node; } @@ -5324,8 +5410,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag { return node.tagName !== tagName - || node.class !== className - || node.comment !== comment + || node.class !== className + || node.comment !== comment ? update(createJSDocImplementsTag(tagName, className, comment), node) : node; } @@ -5353,7 +5439,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // updateJSDocDeprecatedTag function updateJSDocSimpleTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), comment: string | NodeArray | undefined) { return node.tagName !== tagName - || node.comment !== comment + || node.comment !== comment ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) : node; } @@ -5364,7 +5450,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // createJSDocThisTag // createJSDocEnumTag // createJSDocSatisfiesTag - function createJSDocTypeLikeTagWorker(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray) { + function createJSDocTypeLikeTagWorker(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray) { const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); node.typeExpression = typeExpression; return node; @@ -5376,10 +5462,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // updateJSDocThisTag // updateJSDocEnumTag // updateJSDocSatisfiesTag - function updateJSDocTypeLikeTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined) { + function updateJSDocTypeLikeTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined) { return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.comment !== comment + || node.typeExpression !== typeExpression + || node.comment !== comment ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node) : node; } @@ -5393,7 +5479,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag { return node.tagName !== tagName - || node.comment !== comment + || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) : node; } @@ -5411,8 +5497,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined) { return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.comment !== comment + || node.typeExpression !== typeExpression + || node.comment !== comment ? update(createJSDocEnumTag(tagName, typeExpression, comment), node) : node; } @@ -5442,7 +5528,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined) { return node.comment !== comment - || node.tags !== tags + || node.tags !== tags ? update(createJSDocComment(comment, tags), node) : node; } @@ -5457,8 +5543,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; - node.transformFlags |= - propagateChildFlags(node.openingElement) | + node.transformFlags |= propagateChildFlags(node.openingElement) | propagateChildrenFlags(node.children) | propagateChildFlags(node.closingElement) | TransformFlags.ContainsJsx; @@ -5468,8 +5553,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) { return node.openingElement !== openingElement - || node.children !== children - || node.closingElement !== closingElement + || node.children !== children + || node.closingElement !== closingElement ? update(createJsxElement(openingElement, children, closingElement), node) : node; } @@ -5480,8 +5565,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; - node.transformFlags |= - propagateChildFlags(node.tagName) | + node.transformFlags |= propagateChildFlags(node.tagName) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.attributes) | TransformFlags.ContainsJsx; @@ -5494,8 +5578,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { return node.tagName !== tagName - || node.typeArguments !== typeArguments - || node.attributes !== attributes + || node.typeArguments !== typeArguments + || node.attributes !== attributes ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } @@ -5506,8 +5590,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; - node.transformFlags |= - propagateChildFlags(node.tagName) | + node.transformFlags |= propagateChildFlags(node.tagName) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.attributes) | TransformFlags.ContainsJsx; @@ -5520,8 +5603,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { return node.tagName !== tagName - || node.typeArguments !== typeArguments - || node.attributes !== attributes + || node.typeArguments !== typeArguments + || node.attributes !== attributes ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } @@ -5530,8 +5613,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createJsxClosingElement(tagName: JsxTagNameExpression) { const node = createBaseNode(SyntaxKind.JsxClosingElement); node.tagName = tagName; - node.transformFlags |= - propagateChildFlags(node.tagName) | + node.transformFlags |= propagateChildFlags(node.tagName) | TransformFlags.ContainsJsx; return node; } @@ -5549,8 +5631,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; - node.transformFlags |= - propagateChildFlags(node.openingFragment) | + node.transformFlags |= propagateChildFlags(node.openingFragment) | propagateChildrenFlags(node.children) | propagateChildFlags(node.closingFragment) | TransformFlags.ContainsJsx; @@ -5560,8 +5641,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) { return node.openingFragment !== openingFragment - || node.children !== children - || node.closingFragment !== closingFragment + || node.children !== children + || node.closingFragment !== closingFragment ? update(createJsxFragment(openingFragment, children, closingFragment), node) : node; } @@ -5578,7 +5659,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean) { return node.text !== text - || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces + || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node) : node; } @@ -5602,8 +5683,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseDeclaration(SyntaxKind.JsxAttribute); node.name = name; node.initializer = initializer; - node.transformFlags |= - propagateChildFlags(node.name) | + node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | TransformFlags.ContainsJsx; return node; @@ -5612,7 +5692,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJsxAttribute(node: JsxAttribute, name: JsxAttributeName, initializer: JsxAttributeValue | undefined) { return node.name !== name - || node.initializer !== initializer + || node.initializer !== initializer ? update(createJsxAttribute(name, initializer), node) : node; } @@ -5621,8 +5701,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createJsxAttributes(properties: readonly JsxAttributeLike[]) { const node = createBaseDeclaration(SyntaxKind.JsxAttributes); node.properties = createNodeArray(properties); - node.transformFlags |= - propagateChildrenFlags(node.properties) | + node.transformFlags |= propagateChildrenFlags(node.properties) | TransformFlags.ContainsJsx; return node; } @@ -5638,8 +5717,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createJsxSpreadAttribute(expression: Expression) { const node = createBaseNode(SyntaxKind.JsxSpreadAttribute); node.expression = expression; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsJsx; return node; } @@ -5656,8 +5734,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.JsxExpression); node.dotDotDotToken = dotDotDotToken; node.expression = expression; - node.transformFlags |= - propagateChildFlags(node.dotDotDotToken) | + node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | propagateChildFlags(node.expression) | TransformFlags.ContainsJsx; return node; @@ -5675,8 +5752,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.JsxNamespacedName); node.namespace = namespace; node.name = name; - node.transformFlags |= - propagateChildFlags(node.namespace) | + node.transformFlags |= propagateChildFlags(node.namespace) | propagateChildFlags(node.name) | TransformFlags.ContainsJsx; return node; @@ -5685,7 +5761,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJsxNamespacedName(node: JsxNamespacedName, namespace: Identifier, name: Identifier) { return node.namespace !== namespace - || node.name !== name + || node.name !== name ? update(createJsxNamespacedName(namespace, name), node) : node; } @@ -5699,8 +5775,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.CaseClause); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statements = createNodeArray(statements); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.statements); node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -5710,7 +5785,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateCaseClause(node: CaseClause, expression: Expression, statements: readonly Statement[]) { return node.expression !== expression - || node.statements !== statements + || node.statements !== statements ? update(createCaseClause(expression, statements), node) : node; } @@ -5762,8 +5837,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.variableDeclaration = asVariableDeclaration(variableDeclaration); node.block = block; - node.transformFlags |= - propagateChildFlags(node.variableDeclaration) | + node.transformFlags |= propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block) | (!variableDeclaration ? TransformFlags.ContainsES2019 : TransformFlags.None); @@ -5775,7 +5849,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block) { return node.variableDeclaration !== variableDeclaration - || node.block !== block + || node.block !== block ? update(createCatchClause(variableDeclaration, block), node) : node; } @@ -5789,8 +5863,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseDeclaration(SyntaxKind.PropertyAssignment); node.name = asName(name); node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); - node.transformFlags |= - propagateNameFlags(node.name) | + node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer); node.modifiers = undefined; // initialized by parser to report grammar errors @@ -5803,7 +5876,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression) { return node.name !== name - || node.initializer !== initializer + || node.initializer !== initializer ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) : node; } @@ -5824,8 +5897,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseDeclaration(SyntaxKind.ShorthandPropertyAssignment); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); - node.transformFlags |= - propagateIdentifierNameFlags(node.name) | + node.transformFlags |= propagateIdentifierNameFlags(node.name) | propagateChildFlags(node.objectAssignmentInitializer) | TransformFlags.ContainsES2015; @@ -5840,7 +5912,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined) { return node.name !== name - || node.objectAssignmentInitializer !== objectAssignmentInitializer + || node.objectAssignmentInitializer !== objectAssignmentInitializer ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) : node; } @@ -5860,8 +5932,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createSpreadAssignment(expression: Expression) { const node = createBaseDeclaration(SyntaxKind.SpreadAssignment); node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2018 | TransformFlags.ContainsObjectRestOrSpread; @@ -5885,8 +5956,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseDeclaration(SyntaxKind.EnumMember); node.name = asName(name); node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); - node.transformFlags |= - propagateChildFlags(node.name) | + node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | TransformFlags.ContainsTypeScript; @@ -5897,7 +5967,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined) { return node.name !== name - || node.initializer !== initializer + || node.initializer !== initializer ? update(createEnumMember(name, initializer), node) : node; } @@ -5910,7 +5980,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createSourceFile( statements: readonly Statement[], endOfFileToken: EndOfFileToken, - flags: NodeFlags + flags: NodeFlags, ) { const node = baseFactory.createBaseSourceFileNode(SyntaxKind.SourceFile) as Mutable; node.statements = createNodeArray(statements); @@ -5927,8 +5997,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.isDeclarationFile = false; node.hasNoDefaultLib = false; - node.transformFlags |= - propagateChildrenFlags(node.statements) | + node.transformFlags |= propagateChildrenFlags(node.statements) | propagateChildFlags(node.endOfFileToken); node.locals = undefined; // initialized by binder (LocalsContainer) @@ -5967,12 +6036,20 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node: SourceFile = Object.create(redirectInfo.redirectTarget); Object.defineProperties(node, { id: { - get(this: SourceFile) { return this.redirectInfo!.redirectTarget.id; }, - set(this: SourceFile, value: SourceFile["id"]) { this.redirectInfo!.redirectTarget.id = value; }, + get(this: SourceFile) { + return this.redirectInfo!.redirectTarget.id; + }, + set(this: SourceFile, value: SourceFile["id"]) { + this.redirectInfo!.redirectTarget.id = value; + }, }, symbol: { - get(this: SourceFile) { return this.redirectInfo!.redirectTarget.symbol; }, - set(this: SourceFile, value: SourceFile["symbol"]) { this.redirectInfo!.redirectTarget.symbol = value; }, + get(this: SourceFile) { + return this.redirectInfo!.redirectTarget.symbol; + }, + set(this: SourceFile, value: SourceFile["symbol"]) { + this.redirectInfo!.redirectTarget.symbol = value; + }, }, }); node.redirectInfo = redirectInfo; @@ -6023,7 +6100,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode referencedFiles: readonly FileReference[], typeReferences: readonly FileReference[], hasNoDefaultLib: boolean, - libReferences: readonly FileReference[] + libReferences: readonly FileReference[], ) { const node = cloneSourceFile(source); node.statements = createNodeArray(statements); @@ -6032,8 +6109,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.typeReferenceDirectives = typeReferences; node.hasNoDefaultLib = hasNoDefaultLib; node.libReferenceDirectives = libReferences; - node.transformFlags = - propagateChildrenFlags(node.statements) | + node.transformFlags = propagateChildrenFlags(node.statements) | propagateChildFlags(node.endOfFileToken); return node; } @@ -6046,14 +6122,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode referencedFiles = node.referencedFiles, typeReferenceDirectives = node.typeReferenceDirectives, hasNoDefaultLib = node.hasNoDefaultLib, - libReferenceDirectives = node.libReferenceDirectives + libReferenceDirectives = node.libReferenceDirectives, ) { return node.statements !== statements - || node.isDeclarationFile !== isDeclarationFile - || node.referencedFiles !== referencedFiles - || node.typeReferenceDirectives !== typeReferenceDirectives - || node.hasNoDefaultLib !== hasNoDefaultLib - || node.libReferenceDirectives !== libReferenceDirectives + || node.isDeclarationFile !== isDeclarationFile + || node.referencedFiles !== referencedFiles + || node.typeReferenceDirectives !== typeReferenceDirectives + || node.hasNoDefaultLib !== hasNoDefaultLib + || node.libReferenceDirectives !== libReferenceDirectives ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node) : node; } @@ -6073,7 +6149,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateBundle(node: Bundle, sourceFiles: readonly SourceFile[], prepends: readonly (UnparsedSource | InputFiles)[] = emptyArray) { return node.sourceFiles !== sourceFiles - || node.prepends !== prepends + || node.prepends !== prepends ? update(createBundle(sourceFiles, prepends), node) : node; } @@ -6181,8 +6257,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.PartiallyEmittedExpression); node.expression = expression; node.original = original; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsTypeScript; setTextRange(node, original); return node; @@ -6227,8 +6302,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.SyntheticReferenceExpression); node.expression = expression; node.thisArg = thisArg; - node.transformFlags |= - propagateChildFlags(node.expression) | + node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); return node; } @@ -6236,7 +6310,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateSyntheticReferenceExpression(node: SyntheticReferenceExpression, expression: Expression, thisArg: Expression) { return node.expression !== expression - || node.thisArg !== thisArg + || node.thisArg !== thisArg ? update(createSyntheticReferenceExpression(expression, thisArg), node) : node; } @@ -6307,11 +6381,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return clonePrivateIdentifier(node) as T & PrivateIdentifier; } - const clone = - !isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) as T : + const clone = !isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) as T : baseFactory.createBaseNode(node.kind) as T; - (clone as Mutable).flags |= (node.flags & ~NodeFlags.Synthesized); + (clone as Mutable).flags |= node.flags & ~NodeFlags.Synthesized; (clone as Mutable).transformFlags = node.transformFlags; setOriginalNode(clone, node); @@ -6338,10 +6411,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode /*typeParameters*/ undefined, /*parameters*/ param ? [param] : [], /*type*/ undefined, - createBlock(statements, /*multiLine*/ true) + createBlock(statements, /*multiLine*/ true), ), /*typeArguments*/ undefined, - /*argumentsArray*/ paramValue ? [paramValue] : [] + /*argumentsArray*/ paramValue ? [paramValue] : [], ); } @@ -6355,10 +6428,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode /*parameters*/ param ? [param] : [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, - createBlock(statements, /*multiLine*/ true) + createBlock(statements, /*multiLine*/ true), ), /*typeArguments*/ undefined, - /*argumentsArray*/ paramValue ? [paramValue] : [] + /*argumentsArray*/ paramValue ? [paramValue] : [], ); } @@ -6370,7 +6443,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return createExportAssignment( /*modifiers*/ undefined, /*isExportEquals*/ false, - expression); + expression, + ); } function createExternalModuleExport(exportName: Identifier) { @@ -6378,8 +6452,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode /*modifiers*/ undefined, /*isTypeOnly*/ false, createNamedExports([ - createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName) - ]) + createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName), + ]), ); } @@ -6406,13 +6480,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode createPropertyAccessChain(object, /*questionDotToken*/ undefined, methodName), /*questionDotToken*/ undefined, /*typeArguments*/ undefined, - argumentsList + argumentsList, ); } return createCallExpression( createPropertyAccessExpression(object, methodName), /*typeArguments*/ undefined, - argumentsList + argumentsList, ); } @@ -6481,12 +6555,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function updateOuterExpression(outerExpression: OuterExpression, expression: Expression) { switch (outerExpression.kind) { - case SyntaxKind.ParenthesizedExpression: return updateParenthesizedExpression(outerExpression, expression); - case SyntaxKind.TypeAssertionExpression: return updateTypeAssertion(outerExpression, outerExpression.type, expression); - case SyntaxKind.AsExpression: return updateAsExpression(outerExpression, expression, outerExpression.type); - case SyntaxKind.SatisfiesExpression: return updateSatisfiesExpression(outerExpression, expression, outerExpression.type); - case SyntaxKind.NonNullExpression: return updateNonNullExpression(outerExpression, expression); - case SyntaxKind.PartiallyEmittedExpression: return updatePartiallyEmittedExpression(outerExpression, expression); + case SyntaxKind.ParenthesizedExpression: + return updateParenthesizedExpression(outerExpression, expression); + case SyntaxKind.TypeAssertionExpression: + return updateTypeAssertion(outerExpression, outerExpression.type, expression); + case SyntaxKind.AsExpression: + return updateAsExpression(outerExpression, expression, outerExpression.type); + case SyntaxKind.SatisfiesExpression: + return updateSatisfiesExpression(outerExpression, expression, outerExpression.type); + case SyntaxKind.NonNullExpression: + return updateNonNullExpression(outerExpression, expression); + case SyntaxKind.PartiallyEmittedExpression: + return updatePartiallyEmittedExpression(outerExpression, expression); } } @@ -6517,7 +6597,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression( outerExpression, - restoreOuterExpressions(outerExpression.expression, innerExpression) + restoreOuterExpressions(outerExpression.expression, innerExpression), ); } return innerExpression; @@ -6532,7 +6612,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode outermostLabeledStatement.label, isLabeledStatement(outermostLabeledStatement.statement) ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) - : node + : node, ); if (afterRestoreLabelCallback) { afterRestoreLabelCallback(outermostLabeledStatement); @@ -6589,11 +6669,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode setTextRange( factory.createAssignment( thisArg, - callee.expression + callee.expression, ), - callee.expression + callee.expression, ), - callee.name + callee.name, ); setTextRange(target, callee); } @@ -6610,11 +6690,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode setTextRange( factory.createAssignment( thisArg, - callee.expression + callee.expression, ), - callee.expression + callee.expression, ), - callee.argumentExpression + callee.argumentExpression, ); setTextRange(target, callee); } @@ -6646,15 +6726,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode paramName, /*questionToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined + /*initializer*/ undefined, )], createBlock([ - createExpressionStatement(expression) - ]) - ) - ]) + createExpressionStatement(expression), + ]), + ), + ]), ), - "value" + "value", ); } @@ -7060,7 +7140,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode variableDeclaration, /*exclamationToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined + /*initializer*/ undefined, ); } return variableDeclaration; @@ -7084,32 +7164,51 @@ function updateWithOriginal(updated: Mutable, original: T): T function getDefaultTagNameForKind(kind: JSDocTag["kind"]): string { switch (kind) { - case SyntaxKind.JSDocTypeTag: return "type"; - case SyntaxKind.JSDocReturnTag: return "returns"; - case SyntaxKind.JSDocThisTag: return "this"; - case SyntaxKind.JSDocEnumTag: return "enum"; - case SyntaxKind.JSDocAuthorTag: return "author"; - case SyntaxKind.JSDocClassTag: return "class"; - case SyntaxKind.JSDocPublicTag: return "public"; - case SyntaxKind.JSDocPrivateTag: return "private"; - case SyntaxKind.JSDocProtectedTag: return "protected"; - case SyntaxKind.JSDocReadonlyTag: return "readonly"; - case SyntaxKind.JSDocOverrideTag: return "override"; - case SyntaxKind.JSDocTemplateTag: return "template"; - case SyntaxKind.JSDocTypedefTag: return "typedef"; - case SyntaxKind.JSDocParameterTag: return "param"; - case SyntaxKind.JSDocPropertyTag: return "prop"; - case SyntaxKind.JSDocCallbackTag: return "callback"; - case SyntaxKind.JSDocOverloadTag: return "overload"; - case SyntaxKind.JSDocAugmentsTag: return "augments"; - case SyntaxKind.JSDocImplementsTag: return "implements"; + case SyntaxKind.JSDocTypeTag: + return "type"; + case SyntaxKind.JSDocReturnTag: + return "returns"; + case SyntaxKind.JSDocThisTag: + return "this"; + case SyntaxKind.JSDocEnumTag: + return "enum"; + case SyntaxKind.JSDocAuthorTag: + return "author"; + case SyntaxKind.JSDocClassTag: + return "class"; + case SyntaxKind.JSDocPublicTag: + return "public"; + case SyntaxKind.JSDocPrivateTag: + return "private"; + case SyntaxKind.JSDocProtectedTag: + return "protected"; + case SyntaxKind.JSDocReadonlyTag: + return "readonly"; + case SyntaxKind.JSDocOverrideTag: + return "override"; + case SyntaxKind.JSDocTemplateTag: + return "template"; + case SyntaxKind.JSDocTypedefTag: + return "typedef"; + case SyntaxKind.JSDocParameterTag: + return "param"; + case SyntaxKind.JSDocPropertyTag: + return "prop"; + case SyntaxKind.JSDocCallbackTag: + return "callback"; + case SyntaxKind.JSDocOverloadTag: + return "overload"; + case SyntaxKind.JSDocAugmentsTag: + return "augments"; + case SyntaxKind.JSDocImplementsTag: + return "implements"; default: return Debug.fail(`Unsupported kind: ${Debug.formatSyntaxKind(kind)}`); } } let rawTextScanner: Scanner | undefined; -const invalidValueSentinel: object = { }; +const invalidValueSentinel: object = {}; function getCookedText(kind: TemplateLiteralToken["kind"], rawText: string) { if (!rawTextScanner) { @@ -7462,7 +7561,7 @@ function parseOldFileOfCurrentEmit(bundleFileInfo: BundleFileInfo) { /** @deprecated */ export function createInputFiles( javascriptText: string, - declarationText: string + declarationText: string, ): InputFiles; /** @deprecated */ export function createInputFiles( @@ -7471,7 +7570,7 @@ export function createInputFiles( javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, - declarationMapText: string | undefined + declarationMapText: string | undefined, ): InputFiles; /** @deprecated */ export function createInputFiles( @@ -7480,7 +7579,7 @@ export function createInputFiles( javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, - buildInfoPath: string | undefined + buildInfoPath: string | undefined, ): InputFiles; export function createInputFiles( javascriptTextOrReadFileText: string | ((path: string) => string | undefined), diff --git a/src/compiler/factory/parenthesizerRules.ts b/src/compiler/factory/parenthesizerRules.ts index 5a1386d567b3f..b90cc220fb616 100644 --- a/src/compiler/factory/parenthesizerRules.ts +++ b/src/compiler/factory/parenthesizerRules.ts @@ -151,9 +151,11 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul case Comparison.LessThan: // If the operand is the right side of a right-associative binary operation // and is a yield expression, then we do not need parentheses. - if (!isLeftSideOfBinary + if ( + !isLeftSideOfBinary && binaryOperatorAssociativity === Associativity.Right - && operand.kind === SyntaxKind.YieldExpression) { + && operand.kind === SyntaxKind.YieldExpression + ) { return false; } @@ -176,8 +178,10 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul return binaryOperatorAssociativity === Associativity.Right; } else { - if (isBinaryExpression(emittedOperand) - && emittedOperand.operatorToken.kind === binaryOperator) { + if ( + isBinaryExpression(emittedOperand) + && emittedOperand.operatorToken.kind === binaryOperator + ) { // No need to parenthesize the right operand when the binary operator and // operand are the same and one of the following: // x*(a*b) => x*a*b @@ -259,9 +263,9 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul const leftKind = getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).left); const literalKind = isLiteralKind(leftKind) - && leftKind === getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).right) - ? leftKind - : SyntaxKind.Unknown; + && leftKind === getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).right) + ? leftKind + : SyntaxKind.Unknown; (node as BinaryPlusExpression).cachedLiteralKind = literalKind; return literalKind; @@ -292,7 +296,6 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul : operand; } - function parenthesizeLeftSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression): Expression { return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true); } @@ -380,9 +383,11 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // new C.x -> not the same as (new C).x // const emittedExpression = skipPartiallyEmittedExpressions(expression); - if (isLeftHandSideExpression(emittedExpression) + if ( + isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== SyntaxKind.NewExpression || (emittedExpression as NewExpression).arguments) - && (optionalChain || !isOptionalChain(emittedExpression))) { + && (optionalChain || !isOptionalChain(emittedExpression)) + ) { // TODO(rbuckton): Verify whether this assertion holds. return expression as LeftHandSideExpression; } @@ -425,7 +430,7 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul emittedExpression, setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, - emittedExpression.arguments + emittedExpression.arguments, ); return factory.restoreOuterExpressions(expression, updated, OuterExpressionKinds.PartiallyEmittedExpressions); } diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts index 221d4874d5226..23f8014586d5f 100644 --- a/src/compiler/factory/utilities.ts +++ b/src/compiler/factory/utilities.ts @@ -178,7 +178,7 @@ import { Token, TransformFlags, TypeNode, - WrappedExpression + WrappedExpression, } from "../_namespaces/ts"; // Compound nodes @@ -191,14 +191,14 @@ export function createEmptyExports(factory: NodeFactory) { /** @internal */ export function createMemberAccessForPropertyName(factory: NodeFactory, target: Expression, memberName: PropertyName, location?: TextRange): MemberExpression { if (isComputedPropertyName(memberName)) { - return setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); + return setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); } else { const expression = setTextRange( isMemberName(memberName) ? factory.createPropertyAccessExpression(target, memberName) : factory.createElementAccessExpression(target, memberName), - memberName + memberName, ); addEmitFlags(expression, EmitFlags.NoNestedSourceMaps); return expression; @@ -234,7 +234,7 @@ export function createJsxFactoryExpression(factory: NodeFactory, jsxFactoryEntit createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) : factory.createPropertyAccessExpression( createReactNamespace(reactNamespace, parent), - "createElement" + "createElement", ); } @@ -243,7 +243,7 @@ function createJsxFragmentFactoryExpression(factory: NodeFactory, jsxFragmentFac createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) : factory.createPropertyAccessExpression( createReactNamespace(reactNamespace, parent), - "Fragment" + "Fragment", ); } @@ -274,9 +274,9 @@ export function createExpressionForJsxElement(factory: NodeFactory, callee: Expr factory.createCallExpression( callee, /*typeArguments*/ undefined, - argumentsList + argumentsList, ), - location + location, ); } @@ -301,9 +301,9 @@ export function createExpressionForJsxFragment(factory: NodeFactory, jsxFactoryE factory.createCallExpression( createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement), /*typeArguments*/ undefined, - argumentsList + argumentsList, ), - location + location, ); } @@ -318,14 +318,14 @@ export function createForOfBindingStatement(factory: NodeFactory, node: ForIniti firstDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, - boundValue + boundValue, ); return setTextRange( factory.createVariableStatement( /*modifiers*/ undefined, - factory.updateVariableDeclarationList(node, [updatedDeclaration]) + factory.updateVariableDeclarationList(node, [updatedDeclaration]), ), - /*location*/ node + /*location*/ node, ); } else { @@ -392,11 +392,11 @@ function createExpressionForAccessorDeclaration(factory: NodeFactory, properties /*typeParameters*/ undefined, getAccessor.parameters, /*type*/ undefined, - getAccessor.body! // TODO: GH#18217 + getAccessor.body!, // TODO: GH#18217 ), - getAccessor + getAccessor, ), - getAccessor + getAccessor, ), set: setAccessor && setTextRange( setOriginalNode( @@ -407,15 +407,15 @@ function createExpressionForAccessorDeclaration(factory: NodeFactory, properties /*typeParameters*/ undefined, setAccessor.parameters, /*type*/ undefined, - setAccessor.body! // TODO: GH#18217 + setAccessor.body!, // TODO: GH#18217 ), - setAccessor + setAccessor, ), - setAccessor - ) - }, !multiLine) + setAccessor, + ), + }, !multiLine), ), - firstAccessor + firstAccessor, ); } @@ -427,11 +427,11 @@ function createExpressionForPropertyAssignment(factory: NodeFactory, property: P setTextRange( factory.createAssignment( createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), - property.initializer + property.initializer, ), - property + property, ), - property + property, ); } @@ -440,11 +440,11 @@ function createExpressionForShorthandPropertyAssignment(factory: NodeFactory, pr setTextRange( factory.createAssignment( createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), - factory.cloneNode(property.name) + factory.cloneNode(property.name), ), - /*location*/ property + /*location*/ property, ), - /*original*/ property + /*original*/ property, ); } @@ -462,16 +462,16 @@ function createExpressionForMethodDeclaration(factory: NodeFactory, method: Meth /*typeParameters*/ undefined, method.parameters, /*type*/ undefined, - method.body! // TODO: GH#18217 + method.body!, // TODO: GH#18217 ), - /*location*/ method + /*location*/ method, ), - /*original*/ method - ) + /*original*/ method, + ), ), - /*location*/ method + /*location*/ method, ), - /*original*/ method + /*original*/ method, ); } @@ -483,7 +483,7 @@ export function createExpressionForObjectLiteralElementLike(factory: NodeFactory switch (property.kind) { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return createExpressionForAccessorDeclaration(factory, node.properties, property as typeof property & { readonly name: Exclude }, receiver, !!node.multiLine); + return createExpressionForAccessorDeclaration(factory, node.properties, property as typeof property & { readonly name: Exclude; }, receiver, !!node.multiLine); case SyntaxKind.PropertyAssignment: return createExpressionForPropertyAssignment(factory, property, receiver); case SyntaxKind.ShorthandPropertyAssignment: @@ -612,12 +612,12 @@ export function startsWithUseStrict(statements: readonly Statement[]) { } /** @internal */ -export function isCommaExpression(node: Expression): node is BinaryExpression & { operatorToken: Token } { +export function isCommaExpression(node: Expression): node is BinaryExpression & { operatorToken: Token; } { return node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken; } /** @internal */ -export function isCommaSequence(node: Expression): node is BinaryExpression & {operatorToken: Token} | CommaListExpression { +export function isCommaSequence(node: Expression): node is BinaryExpression & { operatorToken: Token; } | CommaListExpression { return isCommaExpression(node) || isCommaListExpression(node); } @@ -731,10 +731,10 @@ export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: Node // Alias the imports if the names are used somewhere in the file. // NOTE: We don't need to care about global import collisions as this is a module. namedBindings = nodeFactory.createNamedImports( - map(helperNames, name => isFileLevelUniqueName(sourceFile, name) - ? nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, nodeFactory.createIdentifier(name)) - : nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)) - ) + map(helperNames, name => + isFileLevelUniqueName(sourceFile, name) + ? nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, nodeFactory.createIdentifier(name)) + : nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name))), ); const parseNode = getOriginalNode(sourceFile, isSourceFile); const emitNode = getOrCreateEmitNode(parseNode); @@ -754,7 +754,7 @@ export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: Node /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(externalHelpersModuleNameText), - /*assertClause*/ undefined + /*assertClause*/ undefined, ); addInternalEmitFlags(externalHelpersImportDeclaration, InternalEmitFlags.NeverApplyImportHelper); return externalHelpersImportDeclaration; @@ -1291,7 +1291,7 @@ export function isBinaryOperatorToken(node: Node): node is BinaryOperatorToken { return isBinaryOperator(node.kind); } -type BinaryExpressionState = (machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], resultHolder: { value: TResult }, outerState: TOuterState) => number; +type BinaryExpressionState = (machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], resultHolder: { value: TResult; }, outerState: TOuterState) => number; namespace BinaryExpressionState { /** @@ -1300,7 +1300,7 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function enter(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult }, outerState: TOuterState): number { + export function enter(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult; }, outerState: TOuterState): number { const prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; Debug.assertEqual(stateStack[stackIndex], enter); userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); @@ -1314,7 +1314,7 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function left(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult }, _outerState: TOuterState): number { + export function left(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult; }, _outerState: TOuterState): number { Debug.assertEqual(stateStack[stackIndex], left); Debug.assertIsDefined(machine.onLeft); stateStack[stackIndex] = nextState(machine, left); @@ -1332,7 +1332,7 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function operator(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult }, _outerState: TOuterState): number { + export function operator(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult; }, _outerState: TOuterState): number { Debug.assertEqual(stateStack[stackIndex], operator); Debug.assertIsDefined(machine.onOperator); stateStack[stackIndex] = nextState(machine, operator); @@ -1346,7 +1346,7 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function right(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult }, _outerState: TOuterState): number { + export function right(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult; }, _outerState: TOuterState): number { Debug.assertEqual(stateStack[stackIndex], right); Debug.assertIsDefined(machine.onRight); stateStack[stackIndex] = nextState(machine, right); @@ -1364,7 +1364,7 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function exit(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], resultHolder: { value: TResult }, _outerState: TOuterState): number { + export function exit(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], resultHolder: { value: TResult; }, _outerState: TOuterState): number { Debug.assertEqual(stateStack[stackIndex], exit); stateStack[stackIndex] = nextState(machine, exit); const result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); @@ -1385,7 +1385,7 @@ namespace BinaryExpressionState { * Handles a frame that is already done. * @returns The `done` state. */ - export function done(_machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], _nodeStack: BinaryExpression[], _userStateStack: TState[], _resultHolder: { value: TResult }, _outerState: TOuterState): number { + export function done(_machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], _nodeStack: BinaryExpression[], _userStateStack: TState[], _resultHolder: { value: TResult; }, _outerState: TOuterState): number { Debug.assertEqual(stateStack[stackIndex], done); return stackIndex; } @@ -1401,10 +1401,14 @@ namespace BinaryExpressionState { case operator: if (machine.onRight) return right; // falls through - case right: return exit; - case exit: return done; - case done: return done; - default: Debug.fail("Invalid state"); + case right: + return exit; + case exit: + return done; + case done: + return done; + default: + Debug.fail("Invalid state"); } } @@ -1452,7 +1456,7 @@ class BinaryExpressionStateMachine { * * @internal */ - export function createBinaryExpressionTrampoline( +export function createBinaryExpressionTrampoline( onEnter: (node: BinaryExpression, prev: TState | undefined) => TState, onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, @@ -1492,7 +1496,7 @@ export function createBinaryExpressionTrampoline( return trampoline; function trampoline(node: BinaryExpression, outerState: TOuterState) { - const resultHolder: { value: TResult } = { value: undefined! }; + const resultHolder: { value: TResult; } = { value: undefined! }; const stateStack: BinaryExpressionState[] = [BinaryExpressionState.enter]; const nodeStack: BinaryExpression[] = [node]; const userStateStack: TState[] = [undefined!]; @@ -1550,10 +1554,13 @@ export function getNodeForGeneratedName(name: GeneratedIdentifier | GeneratedPri node = original; const autoGenerate = node.emitNode?.autoGenerate; // if "node" is a different generated name (having a different "autoGenerateId"), use it and stop traversing. - if (isMemberName(node) && ( - autoGenerate === undefined || - !!(autoGenerate.flags & GeneratedIdentifierFlags.Node) && - autoGenerate.id !== autoGenerateId)) { + if ( + isMemberName(node) && ( + autoGenerate === undefined || + !!(autoGenerate.flags & GeneratedIdentifierFlags.Node) && + autoGenerate.id !== autoGenerateId + ) + ) { break; } @@ -1637,7 +1644,7 @@ export function createAccessorPropertyBackingField(factory: NodeFactory, node: P factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage"), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - initializer + initializer, ); } @@ -1656,10 +1663,10 @@ export function createAccessorPropertyGetRedirector(factory: NodeFactory, node: factory.createReturnStatement( factory.createPropertyAccessExpression( receiver, - factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage") - ) - ) - ]) + factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage"), + ), + ), + ]), ); } @@ -1675,19 +1682,19 @@ export function createAccessorPropertySetRedirector(factory: NodeFactory, node: [factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - "value" + "value", )], factory.createBlock([ factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression( receiver, - factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage") + factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage"), ), - factory.createIdentifier("value") - ) - ) - ]) + factory.createIdentifier("value"), + ), + ), + ]), ); } @@ -1707,7 +1714,7 @@ export function findComputedPropertyNameCacheAssignment(name: ComputedPropertyNa } if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && isGeneratedIdentifier(node.left)) { - return node as AssignmentExpression & { readonly left: GeneratedIdentifier }; + return node as AssignmentExpression & { readonly left: GeneratedIdentifier; }; } break; diff --git a/src/compiler/factory/utilitiesPublic.ts b/src/compiler/factory/utilitiesPublic.ts index 8afd72574c0fb..5380a4a1604e0 100644 --- a/src/compiler/factory/utilitiesPublic.ts +++ b/src/compiler/factory/utilitiesPublic.ts @@ -49,4 +49,4 @@ export function canHaveDecorators(node: Node): node is HasDecorators { || kind === SyntaxKind.SetAccessor || kind === SyntaxKind.ClassExpression || kind === SyntaxKind.ClassDeclaration; -} \ No newline at end of file +} diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index c229d42be1b36..4aedc4a4aa5d0 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -132,7 +132,7 @@ function withPackageId(packageInfo: PackageJsonInfo | undefined, r: PathAndExten packageId = { name: packageJsonContent.name, subModuleName: r.path.slice(packageInfo.packageDirectory.length + directorySeparator.length), - version: packageJsonContent.version + version: packageJsonContent.version, }; } } @@ -176,6 +176,7 @@ interface PathAndExtension { resolvedUsingTsExtension: boolean | undefined; } +// dprint-ignore /** * Kinds of file that we are currently looking for. */ @@ -230,7 +231,8 @@ function createResolvedModuleWithFailedLookupLocationsHandlingSymlink( legacyResult?: string, ): ResolvedModuleWithFailedLookupLocations { // If this is from node_modules for non relative name, always respect preserveSymlinks - if (!state.resultFromCache && + if ( + !state.resultFromCache && !state.compilerOptions.preserveSymlinks && resolved && isExternalLibraryImport && @@ -532,7 +534,6 @@ export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string return result; } - const typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -654,8 +655,8 @@ export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string } } return resolvedTypeScriptOnly( - loadNodeModuleFromDirectory(Extensions.Declaration, candidate, - !directoryExists, moduleResolutionState)); + loadNodeModuleFromDirectory(Extensions.Declaration, candidate, !directoryExists, moduleResolutionState), + ); }); } else { @@ -1080,7 +1081,7 @@ export function createModeAwareCache(): ModeAwareCache { }, size() { return underlying.size; - } + }, }; return cache; @@ -1519,9 +1520,7 @@ type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ -function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - state: ModuleResolutionState): Resolved | undefined { - +function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); if (resolved) return resolved.value; @@ -1548,9 +1547,7 @@ function tryLoadModuleUsingPathsIfEligible(extensions: Extensions, moduleName: s } } -function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - state: ModuleResolutionState): Resolved | undefined { - +function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -1571,8 +1568,7 @@ function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, if (!endsWith(normalizedRoot, directorySeparator)) { normalizedRoot += directorySeparator; } - const isLongestMatchingPrefix = - startsWith(candidate, normalizedRoot) && + const isLongestMatchingPrefix = startsWith(candidate, normalizedRoot) && (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); if (state.traceEnabled) { @@ -1678,9 +1674,7 @@ export enum NodeResolutionFeatures { EsmMode = 1 << 5, } -function node16ModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, - host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, - resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations { +function node16ModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations { return nodeNextModuleNameResolverWorker( NodeResolutionFeatures.Node16Default, moduleName, @@ -1689,13 +1683,11 @@ function node16ModuleNameResolver(moduleName: string, containingFile: string, co host, cache, redirectedReference, - resolutionMode + resolutionMode, ); } -function nodeNextModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, - host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, - resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations { +function nodeNextModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations { return nodeNextModuleNameResolverWorker( NodeResolutionFeatures.NodeNextDefault, moduleName, @@ -1704,7 +1696,7 @@ function nodeNextModuleNameResolver(moduleName: string, containingFile: string, host, cache, redirectedReference, - resolutionMode + resolutionMode, ); } @@ -1730,7 +1722,8 @@ function tryResolveJSModuleWorker(moduleName: string, initialDir: string, host: /*cache*/ undefined, Extensions.JavaScript, /*isConfigLookup*/ false, - /*redirectedReference*/ undefined); + /*redirectedReference*/ undefined, + ); } export function bundlerModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations { @@ -1797,8 +1790,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node10) { const priorityExtensions = extensions & (Extensions.TypeScript | Extensions.Declaration); const secondaryExtensions = extensions & ~(Extensions.TypeScript | Extensions.Declaration); - result = - priorityExtensions && tryResolve(priorityExtensions, state) || + result = priorityExtensions && tryResolve(priorityExtensions, state) || secondaryExtensions && tryResolve(secondaryExtensions, state) || undefined; } @@ -1809,7 +1801,8 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa // For non-relative names that resolved to JS but no types in modes that look up an "import" condition in package.json "exports", // try again with "exports" disabled to try to detect if this is likely a configuration error in a dependency's package.json. let legacyResult; - if (result?.value?.isExternalLibraryImport + if ( + result?.value?.isExternalLibraryImport && !isConfigLookup && extensions & (Extensions.TypeScript | Extensions.Declaration) && features & NodeResolutionFeatures.Exports @@ -1840,7 +1833,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa legacyResult, ); - function tryResolve(extensions: Extensions, state: ModuleResolutionState): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> { + function tryResolve(extensions: Extensions, state: ModuleResolutionState): SearchResult<{ resolved: Resolved; isExternalLibraryImport: boolean; }> { const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { @@ -1880,7 +1873,6 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa return resolved && toSearchResult({ resolved, isExternalLibraryImport: contains(parts, "node_modules") }); } } - } // If you import from "." inside a containing directory "/foo", the result of `normalizePath` @@ -2037,7 +2029,8 @@ function loadModuleFromFileNoImplicitExtensions(extensions: Extensions, candidat * candidate to end with a TS extension (but will also try substituting a JS extension for a TS extension). */ function loadFileNameFromPackageJsonField(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { - if (extensions & Extensions.TypeScript && fileExtensionIsOneOf(candidate, supportedTSImplementationExtensions) || + if ( + extensions & Extensions.TypeScript && fileExtensionIsOneOf(candidate, supportedTSImplementationExtensions) || extensions & Extensions.Declaration && fileExtensionIsOneOf(candidate, supportedDeclarationExtensions) ) { const result = tryFile(candidate, onlyRecordFailures, state); @@ -2102,7 +2095,6 @@ function tryAddingExtensions(candidate: string, extensions: Extensions, original default: return extensions & Extensions.Declaration && !isDeclarationFileName(candidate + originalExtension) && tryExtension(`.d${originalExtension}.ts`) || undefined; - } function tryExtension(ext: string, resolvedUsingTsExtension?: boolean): PathAndExtension | undefined { @@ -2178,13 +2170,14 @@ export function getEntrypointsFromPackageJsonInfo( /*onlyRecordFailures*/ false, loadPackageJsonMainState, packageJsonInfo.contents.packageJsonContent, - getVersionPathsOfPackageJsonInfo(packageJsonInfo, loadPackageJsonMainState)); + getVersionPathsOfPackageJsonInfo(packageJsonInfo, loadPackageJsonMainState), + ); entrypoints = append(entrypoints, mainResolution?.path); if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) { const conditionSets = deduplicate( [getConditions(options, /*esmMode*/ true), getConditions(options, /*esmMode*/ false)], - arrayIsEqualTo + arrayIsEqualTo, ); for (const conditions of conditionSets) { const loadPackageJsonExportsState = { ...loadPackageJsonMainState, failedLookupLocations: [], conditions, host }; @@ -2192,7 +2185,8 @@ export function getEntrypointsFromPackageJsonInfo( packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, loadPackageJsonExportsState, - extensions); + extensions, + ); if (exportResolutions) { for (const resolution of exportResolutions) { entrypoints = appendIfUnique(entrypoints, resolution.path); @@ -2207,7 +2201,7 @@ export function getEntrypointsFromPackageJsonInfo( function loadEntrypointsFromExportMap( scope: PackageJsonInfo, exports: object, - state: ModuleResolutionState & { host: GetPackageJsonEntrypointsHost }, + state: ModuleResolutionState & { host: GetPackageJsonEntrypointsHost; }, extensions: Extensions, ): PathAndExtension[] | undefined { let entrypoints: PathAndExtension[] | undefined; @@ -2238,12 +2232,12 @@ function loadEntrypointsFromExportMap( scope.packageDirectory, extensionsToExtensionsArray(extensions), /*excludes*/ undefined, - [changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target))] + [changeAnyExtension(target.replace("*", "**/*"), getDeclarationEmitExtensionForPath(target))], ).forEach(entry => { entrypoints = appendIfUnique(entrypoints, { path: entry, ext: getAnyExtensionFromPath(entry), - resolvedUsingTsExtension: undefined + resolvedUsingTsExtension: undefined, }); }); } @@ -2390,8 +2384,7 @@ function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: st packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); } else { - packageFile = - extensions & Extensions.Declaration && readPackageJsonTypesFields(jsonContent, candidate, state) || + packageFile = extensions & Extensions.Declaration && readPackageJsonTypesFields(jsonContent, candidate, state) || extensions & (Extensions.ImplementationFiles | Extensions.Declaration) && readPackageJsonMainField(jsonContent, candidate, state) || undefined; } @@ -2469,7 +2462,7 @@ function extensionIsOk(extensions: Extensions, extension: string): boolean { } /** @internal */ -export function parsePackageName(moduleName: string): { packageName: string, rest: string } { +export function parsePackageName(moduleName: string): { packageName: string; rest: string; } { let idx = moduleName.indexOf(directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(directorySeparator, idx + 1); @@ -2617,24 +2610,24 @@ function loadModuleFromImportsOrExports(extensions: Extensions, state: ModuleRes const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!endsWith(moduleName, directorySeparator) && moduleName.indexOf("*") === -1 && hasProperty(lookupTable, moduleName)) { - const target = (lookupTable as { [idx: string]: unknown })[moduleName]; + const target = (lookupTable as { [idx: string]: unknown; })[moduleName]; return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike), k => k.indexOf("*") !== -1 || endsWith(k, "/")), comparePatternKeys); for (const potentialTarget of expandingKeys) { if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { - const target = (lookupTable as { [idx: string]: unknown })[potentialTarget]; + const target = (lookupTable as { [idx: string]: unknown; })[potentialTarget]; const starPos = potentialTarget.indexOf("*"); const subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (endsWith(potentialTarget, "*") && startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { - const target = (lookupTable as { [idx: string]: unknown })[potentialTarget]; + const target = (lookupTable as { [idx: string]: unknown; })[potentialTarget]; const subpath = moduleName.substring(potentialTarget.length - 1); return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (startsWith(moduleName, potentialTarget)) { - const target = (lookupTable as { [idx: string]: unknown })[potentialTarget]; + const target = (lookupTable as { [idx: string]: unknown; })[potentialTarget]; const subpath = moduleName.substring(potentialTarget.length); return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget); } @@ -2667,13 +2660,15 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo traceIfEnabled(state, Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); traceIfEnabled(state, Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); const result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, extensions, /*isConfigLookup*/ false, redirectedReference); - return toSearchResult(result.resolvedModule ? { - path: result.resolvedModule.resolvedFileName, - extension: result.resolvedModule.extension, - packageId: result.resolvedModule.packageId, - originalPath: result.resolvedModule.originalPath, - resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension - } : undefined); + return toSearchResult( + result.resolvedModule ? { + path: result.resolvedModule.resolvedFileName, + extension: result.resolvedModule.extension, + packageId: result.resolvedModule.packageId, + originalPath: result.resolvedModule.originalPath, + resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension, + } : undefined, + ); } if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); @@ -2700,11 +2695,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo } if (state.traceEnabled) { - trace(state.host, - Diagnostics.Using_0_subpath_1_with_target_2, - isImports ? "imports" : "exports", - key, - pattern ? target.replace(/\*/g, subpath) : target + subpath); + trace(state.host, Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); } const finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); const inputLink = tryLoadInputFileForPath(finalPath, subpath, combinePaths(scope.packageDirectory, "package.json"), isImports); @@ -2778,7 +2769,8 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo // we reproduce into the output directory is based on the set of input files, which we're still in the process of traversing and resolving! // _Given that_, we have to guess what the base of the output directory is (obviously the user wrote the export map, so has some idea what it is!). // We are going to probe _so many_ possible paths. We limit where we'll do this to try to reduce the possibilities of false positive lookups. - if (!state.isConfigLookup + if ( + !state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) && finalPath.indexOf("/node_modules/") === -1 && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true) @@ -2836,7 +2828,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo ? Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_import_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate : Diagnostics.The_project_root_is_ambiguous_but_is_required_to_resolve_export_map_entry_0_in_file_1_Supply_the_rootDir_compiler_option_to_disambiguate, entry === "" ? "." : entry, // replace empty string with `.` - the reverse of the operation done when entries are built - so main entrypoint errors don't look weird - packagePath + packagePath, )); } for (const commonSourceDirGuess of commonSourceDirGuesses) { @@ -2971,10 +2963,12 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, modu // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state); // But only if we're not respecting export maps (if we are, we might redirect around this location) - if (rest !== "" && packageInfo && ( - !(state.features & NodeResolutionFeatures.Exports) || - !hasProperty((rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state))?.contents.packageJsonContent ?? emptyArray, "exports") - )) { + if ( + rest !== "" && packageInfo && ( + !(state.features & NodeResolutionFeatures.Exports) || + !hasProperty((rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state))?.contents.packageJsonContent ?? emptyArray, "exports") + ) + ) { const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); if (fromFile) { return noPackageId(fromFile); @@ -2992,8 +2986,7 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, modu } const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => { - let pathAndExtension = - (rest || !(state.features & NodeResolutionFeatures.EsmMode)) && loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + let pathAndExtension = (rest || !(state.features & NodeResolutionFeatures.EsmMode)) && loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || loadNodeModuleFromDirectoryWorker( extensions, candidate, @@ -3124,8 +3117,8 @@ function tryFindNonRelativeModuleNameInCache(cache: NonRelativeModuleNameResolut originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, - resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension - } + resolvedUsingTsExtension: result.resolvedModule.resolvedUsingTsExtension, + }, }; } } @@ -3141,7 +3134,8 @@ export function classicNameResolver(moduleName: string, containingFile: string, host, traceEnabled, failedLookupLocations, - affectingLocations, packageJsonInfoCache: cache, + affectingLocations, + packageJsonInfoCache: cache, features: NodeResolutionFeatures.None, conditions: [], requestContainingDirectory: containingDirectory, @@ -3150,8 +3144,7 @@ export function classicNameResolver(moduleName: string, containingFile: string, candidateIsFromPackageJsonField: false, }; - const resolved = - tryResolve(Extensions.TypeScript | Extensions.Declaration) || + const resolved = tryResolve(Extensions.TypeScript | Extensions.Declaration) || tryResolve(Extensions.JavaScript | (compilerOptions.resolveJsonModule ? Extensions.Json : 0)); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocationsHandlingSymlink( @@ -3256,7 +3249,7 @@ export function loadModuleFromGlobalCache(moduleName: string, projectName: strin failedLookupLocations, affectingLocations, diagnostics, - state.resultFromCache + state.resultFromCache, ); } @@ -3269,7 +3262,7 @@ export function loadModuleFromGlobalCache(moduleName: string, projectName: strin * - { value: undefined } - not found - stop searching * - { value: } - found - stop searching */ -type SearchResult = { value: T | undefined } | undefined; +type SearchResult = { value: T | undefined; } | undefined; /** * Wraps value to SearchResult. diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index eeeeb75615994..cec0585ca3650 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -114,7 +114,12 @@ import { // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. -const enum RelativePreference { Relative, NonRelative, Shortest, ExternalNonRelative } +const enum RelativePreference { + Relative, + NonRelative, + Shortest, + ExternalNonRelative, +} // Processed preferences interface Preferences { @@ -133,10 +138,9 @@ function getPreferences( ): Preferences { const preferredEnding = getPreferredEnding(); return { - relativePreference: - oldImportSpecifier !== undefined ? (isExternalModuleNameRelative(oldImportSpecifier) ? - RelativePreference.Relative : - RelativePreference.NonRelative) : + relativePreference: oldImportSpecifier !== undefined ? (isExternalModuleNameRelative(oldImportSpecifier) ? + RelativePreference.Relative : + RelativePreference.NonRelative) : importModuleSpecifierPreference === "relative" ? RelativePreference.Relative : importModuleSpecifierPreference === "non-relative" ? RelativePreference.NonRelative : importModuleSpecifierPreference === "project-relative" ? RelativePreference.ExternalNonRelative : @@ -155,17 +159,22 @@ function getPreferences( } const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName); switch (preferredEnding) { - case ModuleSpecifierEnding.JsExtension: return allowImportingTsExtension - ? [ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index] - : [ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index]; - case ModuleSpecifierEnding.TsExtension: return [ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.Index]; - case ModuleSpecifierEnding.Index: return allowImportingTsExtension - ? [ModuleSpecifierEnding.Index, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.JsExtension] - : [ModuleSpecifierEnding.Index, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.JsExtension]; - case ModuleSpecifierEnding.Minimal: return allowImportingTsExtension - ? [ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.JsExtension] - : [ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index, ModuleSpecifierEnding.JsExtension]; - default: Debug.assertNever(preferredEnding); + case ModuleSpecifierEnding.JsExtension: + return allowImportingTsExtension + ? [ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index] + : [ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index]; + case ModuleSpecifierEnding.TsExtension: + return [ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.Index]; + case ModuleSpecifierEnding.Index: + return allowImportingTsExtension + ? [ModuleSpecifierEnding.Index, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.JsExtension] + : [ModuleSpecifierEnding.Index, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.JsExtension]; + case ModuleSpecifierEnding.Minimal: + return allowImportingTsExtension + ? [ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.JsExtension] + : [ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index, ModuleSpecifierEnding.JsExtension]; + default: + Debug.assertNever(preferredEnding); } }, }; @@ -179,7 +188,8 @@ function getPreferences( importModuleSpecifierEnding, importingSourceFile.impliedNodeFormat, compilerOptions, - importingSourceFile); + importingSourceFile, + ); } } @@ -231,8 +241,7 @@ export function getNodeModulesPackageName( ): string | undefined { const info = getInfo(importingSourceFile.path, host); const modulePaths = getAllModulePaths(importingSourceFile.path, nodeModulesFileName, host, preferences, options); - return firstDefined(modulePaths, - modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, preferences, /*packageNameOnly*/ true, options.overrideImportMode)); + return firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, preferences, /*packageNameOnly*/ true, options.overrideImportMode)); } function getModuleSpecifierWorker( @@ -243,7 +252,7 @@ function getModuleSpecifierWorker( host: ModuleSpecifierResolutionHost, preferences: Preferences, userPreferences: UserPreferences, - options: ModuleSpecifierOptions = {} + options: ModuleSpecifierOptions = {}, ): string { const info = getInfo(importingSourceFileName, host); const modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options); @@ -264,7 +273,8 @@ export function tryGetModuleSpecifiersFromCache( importingSourceFile, host, userPreferences, - options)[0]; + options, + )[0]; } function tryGetModuleSpecifiersFromCacheWorker( @@ -305,7 +315,7 @@ export function getModuleSpecifiers( importingSourceFile, host, userPreferences, - options + options, ).moduleSpecifiers; } @@ -318,7 +328,7 @@ export function getModuleSpecifiersWithCacheInfo( host: ModuleSpecifierResolutionHost, userPreferences: UserPreferences, options: ModuleSpecifierOptions = {}, -): { moduleSpecifiers: readonly string[], computedWithoutCache: boolean } { +): { moduleSpecifiers: readonly string[]; computedWithoutCache: boolean; } { let computedWithoutCache = false; const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker); if (ambient) return { moduleSpecifiers: [ambient], computedWithoutCache }; @@ -329,7 +339,7 @@ export function getModuleSpecifiersWithCacheInfo( importingSourceFile, host, userPreferences, - options + options, ); if (specifiers) return { moduleSpecifiers: specifiers, computedWithoutCache }; if (!moduleSourceFile) return { moduleSpecifiers: emptyArray, computedWithoutCache }; @@ -351,20 +361,21 @@ function computeModuleSpecifiers( ): readonly string[] { const info = getInfo(importingSourceFile.path, host); const preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); - const existingSpecifier = forEach(modulePaths, modulePath => forEach( - host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), - reason => { - if (reason.kind !== FileIncludeKind.Import || reason.file !== importingSourceFile.path) return undefined; - // If the candidate import mode doesn't match the mode we're generating for, don't consider it - // TODO: maybe useful to keep around as an alternative option for certain contexts where the mode is overridable - if (importingSourceFile.impliedNodeFormat && importingSourceFile.impliedNodeFormat !== getModeForResolutionAtIndex(importingSourceFile, reason.index)) return undefined; - const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text; - // If the preference is for non relative and the module specifier is relative, ignore it - return preferences.relativePreference !== RelativePreference.NonRelative || !pathIsRelative(specifier) ? - specifier : - undefined; - } - )); + const existingSpecifier = forEach(modulePaths, modulePath => + forEach( + host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), + reason => { + if (reason.kind !== FileIncludeKind.Import || reason.file !== importingSourceFile.path) return undefined; + // If the candidate import mode doesn't match the mode we're generating for, don't consider it + // TODO: maybe useful to keep around as an alternative option for certain contexts where the mode is overridable + if (importingSourceFile.impliedNodeFormat && importingSourceFile.impliedNodeFormat !== getModeForResolutionAtIndex(importingSourceFile, reason.index)) return undefined; + const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text; + // If the preference is for non relative and the module specifier is relative, ignore it + return preferences.relativePreference !== RelativePreference.NonRelative || !pathIsRelative(specifier) ? + specifier : + undefined; + }, + )); if (existingSpecifier) { const moduleSpecifiers = [existingSpecifier]; return moduleSpecifiers; @@ -434,7 +445,7 @@ function computeModuleSpecifiers( interface Info { readonly getCanonicalFileName: GetCanonicalFileName; - readonly importingSourceFileName: Path + readonly importingSourceFileName: Path; readonly sourceDirectory: Path; } // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path @@ -549,7 +560,7 @@ export function forEachFileNameOfModule( importedFileName: string, host: ModuleSpecifierResolutionHost, preferSymlinks: boolean, - cb: (fileName: string, isRedirect: boolean) => T | undefined + cb: (fileName: string, isRedirect: boolean) => T | undefined, ): T | undefined { const getCanonicalFileName = hostGetCanonicalFileName(host); const cwd = host.getCurrentDirectory(); @@ -623,7 +634,7 @@ function getAllModulePaths( function getAllModulePathsWorker(importingFileName: Path, importedFileName: string, host: ModuleSpecifierResolutionHost): readonly ModulePath[] { const getCanonicalFileName = hostGetCanonicalFileName(host); - const allFileNames = new Map(); + const allFileNames = new Map(); let importedFileFromNodeModules = false; forEachFileNameOfModule( importingFileName, @@ -635,7 +646,7 @@ function getAllModulePathsWorker(importingFileName: Path, importedFileName: stri allFileNames.set(path, { path: getCanonicalFileName(path), isRedirect, isInNodeModules }); importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules; // don't return value, so we collect everything - } + }, ); // Sort by paths closest to importing file Name directory @@ -673,8 +684,8 @@ function getAllModulePathsWorker(importingFileName: Path, importedFileName: stri function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol, checker: TypeChecker): string | undefined { const decl = moduleSymbol.declarations?.find( - d => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name))) - ) as (ModuleDeclaration & { name: StringLiteral }) | undefined; + d => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name))), + ) as (ModuleDeclaration & { name: StringLiteral; }) | undefined; if (decl) { return decl.name.text; } @@ -689,28 +700,30 @@ function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol, checker: TypeCh * } */ // `import {c} from "m";` is valid, in which case, `moduleSymbol` is "ns", but the module name should be "m" - const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, - d => { - if (!isModuleDeclaration(d)) return; - const topNamespace = getTopNamespace(d); - if (!(topNamespace?.parent?.parent - && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) return; - const exportAssignment = ((topNamespace.parent.parent.symbol.exports?.get("export=" as __String)?.valueDeclaration as ExportAssignment)?.expression as PropertyAccessExpression | Identifier); - if (!exportAssignment) return; - const exportSymbol = checker.getSymbolAtLocation(exportAssignment); - if (!exportSymbol) return; - const originalExportSymbol = exportSymbol?.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(exportSymbol) : exportSymbol; - if (originalExportSymbol === d.symbol) return topNamespace.parent.parent; - - function getTopNamespace(namespaceDeclaration: ModuleDeclaration) { - while (namespaceDeclaration.flags & NodeFlags.NestedNamespace) { - namespaceDeclaration = namespaceDeclaration.parent as ModuleDeclaration; - } - return namespaceDeclaration; + const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, d => { + if (!isModuleDeclaration(d)) return; + const topNamespace = getTopNamespace(d); + if ( + !(topNamespace?.parent?.parent + && isModuleBlock(topNamespace.parent) + && isAmbientModule(topNamespace.parent.parent) + && isSourceFile(topNamespace.parent.parent.parent)) + ) return; + const exportAssignment = (topNamespace.parent.parent.symbol.exports?.get("export=" as __String)?.valueDeclaration as ExportAssignment)?.expression as PropertyAccessExpression | Identifier; + if (!exportAssignment) return; + const exportSymbol = checker.getSymbolAtLocation(exportAssignment); + if (!exportSymbol) return; + const originalExportSymbol = exportSymbol?.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(exportSymbol) : exportSymbol; + if (originalExportSymbol === d.symbol) return topNamespace.parent.parent; + + function getTopNamespace(namespaceDeclaration: ModuleDeclaration) { + while (namespaceDeclaration.flags & NodeFlags.NestedNamespace) { + namespaceDeclaration = namespaceDeclaration.parent as ModuleDeclaration; } + return namespaceDeclaration; } - ); - const ambientModuleDeclare = ambientModuleDeclareCandidates[0] as (AmbientModuleDeclaration & { name: StringLiteral }) | undefined; + }); + const ambientModuleDeclare = ambientModuleDeclareCandidates[0] as (AmbientModuleDeclaration & { name: StringLiteral; }) | undefined; if (ambientModuleDeclare) { return ambientModuleDeclare.name.text; } @@ -757,9 +770,9 @@ function tryGetModuleNameFromPaths(relativeToBaseUrl: string, paths: MapLike ({ + const candidates: { ending: ModuleSpecifierEnding | undefined; value: string; }[] = allowedEndings.map(ending => ({ ending, - value: processEnding(relativeToBaseUrl, [ending], compilerOptions) + value: processEnding(relativeToBaseUrl, [ending], compilerOptions), })); if (tryGetExtensionFromPath(pattern)) { candidates.push({ ending: undefined, value: relativeToBaseUrl }); @@ -769,7 +782,8 @@ function tryGetModuleNameFromPaths(relativeToBaseUrl: string, paths: MapLike= prefix.length + suffix.length && + if ( + value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value }) @@ -790,7 +804,7 @@ function tryGetModuleNameFromPaths(relativeToBaseUrl: string, paths: MapLike Node; @@ -471,10 +471,10 @@ export function isFileProbablyExternalModule(sourceFile: SourceFile) { function isAnExternalModuleIndicatorNode(node: Node) { return canHaveModifiers(node) && hasModifierOfKind(node, SyntaxKind.ExportKeyword) - || isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference) - || isImportDeclaration(node) - || isExportAssignment(node) - || isExportDeclaration(node) ? node : undefined; + || isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference) + || isImportDeclaration(node) + || isExportAssignment(node) + || isExportDeclaration(node) ? node : undefined; } function getImportMetaIfNecessary(sourceFile: SourceFile) { @@ -497,7 +497,7 @@ function isImportMeta(node: Node): boolean { } type ForEachChildFunction = (node: TNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined) => T | undefined; -type ForEachChildTable = { [TNode in ForEachChildNodes as TNode["kind"]]: ForEachChildFunction }; +type ForEachChildTable = { [TNode in ForEachChildNodes as TNode["kind"]]: ForEachChildFunction; }; const forEachChildTable: ForEachChildTable = { [SyntaxKind.QualifiedName]: function forEachChildInQualifiedName(node: QualifiedName, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { return visitNode(cbNode, node.left) || @@ -1087,13 +1087,13 @@ const forEachChildTable: ForEachChildTable = { [SyntaxKind.JSDocTypedefTag]: function forEachChildInJSDocTypedefTag(node: JSDocTypedefTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { return visitNode(cbNode, node.tagName) || (node.typeExpression && - node.typeExpression.kind === SyntaxKind.JSDocTypeExpression + node.typeExpression.kind === SyntaxKind.JSDocTypeExpression ? visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + visitNode(cbNode, node.fullName) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.typeExpression) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))); + visitNode(cbNode, node.typeExpression) || + (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))); }, [SyntaxKind.JSDocCallbackTag]: function forEachChildInJSDocCallbackTag(node: JSDocCallbackTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { return visitNode(cbNode, node.tagName) || @@ -1336,7 +1336,7 @@ export function createSourceFile(fileName: string, sourceText: string, languageV const { languageVersion, setExternalModuleIndicator: overrideSetExternalModuleIndicator, - impliedNodeFormat: format + impliedNodeFormat: format, } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : ({ languageVersion: languageVersionOrOptions } as CreateSourceFileOptions); if (languageVersion === ScriptTarget.JSON) { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, ScriptKind.JSON, noop); @@ -1387,7 +1387,7 @@ export function updateSourceFile(sourceFile: SourceFile, newText: string, textCh const newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. // We will manually port the flag to the new source file. - (newSourceFile as Mutable).flags |= (sourceFile.flags & NodeFlags.PermanentlySetIncrementalFlags); + (newSourceFile as Mutable).flags |= sourceFile.flags & NodeFlags.PermanentlySetIncrementalFlags; return newSourceFile; } @@ -1442,7 +1442,7 @@ namespace Parser { createBaseIdentifierNode: kind => countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)), createBasePrivateIdentifierNode: kind => countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)), createBaseTokenNode: kind => countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)), - createBaseNode: kind => countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)) + createBaseNode: kind => countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)), }; var factory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules | NodeFactoryFlags.NoNodeConverters | NodeFactoryFlags.NoOriginalNode, baseNodeFactory); @@ -1929,7 +1929,6 @@ namespace Parser { } return node; } - } export function fixupParentReferences(rootNode: Node) { @@ -1948,7 +1947,8 @@ namespace Parser { statements: readonly Statement[], endOfFileToken: EndOfFileToken, flags: NodeFlags, - setExternalModuleIndicator: (sourceFile: SourceFile) => void): SourceFile { + setExternalModuleIndicator: (sourceFile: SourceFile) => void, + ): SourceFile { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible let sourceFile = factory.createSourceFile(statements, endOfFileToken, flags); @@ -2470,7 +2470,7 @@ namespace Parser { if (lastError) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)) + createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)), ); } } @@ -2588,8 +2588,7 @@ namespace Parser { } const pos = getNodePos(); - const result = - kind === SyntaxKind.Identifier ? factoryCreateIdentifier("", /*originalKeywordKind*/ undefined) : + const result = kind === SyntaxKind.Identifier ? factoryCreateIdentifier("", /*originalKeywordKind*/ undefined) : isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) : kind === SyntaxKind.NumericLiteral ? factoryCreateNumericLiteral("", /*numericLiteralFlags*/ undefined) : kind === SyntaxKind.StringLiteral ? factoryCreateStringLiteral("", /*isSingleQuote*/ undefined) : @@ -2756,9 +2755,9 @@ namespace Parser { function canFollowExportModifier(): boolean { return token() === SyntaxKind.AtToken || token() !== SyntaxKind.AsteriskToken - && token() !== SyntaxKind.AsKeyword - && token() !== SyntaxKind.OpenBraceToken - && canFollowModifier(); + && token() !== SyntaxKind.AsKeyword + && token() !== SyntaxKind.OpenBraceToken + && canFollowModifier(); } function nextTokenCanFollowExportModifier(): boolean { @@ -2930,9 +2929,10 @@ namespace Parser { } function isHeritageClauseExtendsOrImplementsKeyword(): boolean { - if (token() === SyntaxKind.ImplementsKeyword || - token() === SyntaxKind.ExtendsKeyword) { - + if ( + token() === SyntaxKind.ImplementsKeyword || + token() === SyntaxKind.ExtendsKeyword + ) { return lookAhead(nextTokenIsStartOfExpression); } @@ -3179,54 +3179,53 @@ namespace Parser { case ParsingContext.Parameters: return isReusableParameter(node); - // Any other lists we do not care about reusing nodes in. But feel free to add if - // you can do so safely. Danger areas involve nodes that may involve speculative - // parsing. If speculative parsing is involved with the node, then the range the - // parser reached while looking ahead might be in the edited range (see the example - // in canReuseVariableDeclaratorNode for a good case of this). - - // case ParsingContext.HeritageClauses: - // This would probably be safe to reuse. There is no speculative parsing with - // heritage clauses. - - // case ParsingContext.TypeParameters: - // This would probably be safe to reuse. There is no speculative parsing with - // type parameters. Note that that's because type *parameters* only occur in - // unambiguous *type* contexts. While type *arguments* occur in very ambiguous - // *expression* contexts. - - // case ParsingContext.TupleElementTypes: - // This would probably be safe to reuse. There is no speculative parsing with - // tuple types. - - // Technically, type argument list types are probably safe to reuse. While - // speculative parsing is involved with them (since type argument lists are only - // produced from speculative parsing a < as a type argument list), we only have - // the types because speculative parsing succeeded. Thus, the lookahead never - // went past the end of the list and rewound. - // case ParsingContext.TypeArguments: - - // Note: these are almost certainly not safe to ever reuse. Expressions commonly - // need a large amount of lookahead, and we should not reuse them as they may - // have actually intersected the edit. - // case ParsingContext.ArgumentExpressions: - - // This is not safe to reuse for the same reason as the 'AssignmentExpression' - // cases. i.e. a property assignment may end with an expression, and thus might - // have lookahead far beyond it's old node. - // case ParsingContext.ObjectLiteralMembers: - - // This is probably not safe to reuse. There can be speculative parsing with - // type names in a heritage clause. There can be generic names in the type - // name list, and there can be left hand side expressions (which can have type - // arguments.) - // case ParsingContext.HeritageClauseElement: - - // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes - // on any given element. Same for children. - // case ParsingContext.JsxAttributes: - // case ParsingContext.JsxChildren: - + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + + // case ParsingContext.HeritageClauses: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + + // case ParsingContext.TypeParameters: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + + // case ParsingContext.TupleElementTypes: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + // case ParsingContext.TypeArguments: + + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + // case ParsingContext.ArgumentExpressions: + + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + // case ParsingContext.ObjectLiteralMembers: + + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + // case ParsingContext.HeritageClauseElement: + + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + // case ParsingContext.JsxAttributes: + // case ParsingContext.JsxChildren: } return false; @@ -3377,43 +3376,66 @@ namespace Parser { return token() === SyntaxKind.DefaultKeyword ? parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.ExportKeyword)) : parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); - case ParsingContext.BlockStatements: return parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); - case ParsingContext.SwitchClauses: return parseErrorAtCurrentToken(Diagnostics.case_or_default_expected); - case ParsingContext.SwitchClauseStatements: return parseErrorAtCurrentToken(Diagnostics.Statement_expected); + case ParsingContext.BlockStatements: + return parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); + case ParsingContext.SwitchClauses: + return parseErrorAtCurrentToken(Diagnostics.case_or_default_expected); + case ParsingContext.SwitchClauseStatements: + return parseErrorAtCurrentToken(Diagnostics.Statement_expected); case ParsingContext.RestProperties: // fallthrough - case ParsingContext.TypeMembers: return parseErrorAtCurrentToken(Diagnostics.Property_or_signature_expected); - case ParsingContext.ClassMembers: return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected); - case ParsingContext.EnumMembers: return parseErrorAtCurrentToken(Diagnostics.Enum_member_expected); - case ParsingContext.HeritageClauseElement: return parseErrorAtCurrentToken(Diagnostics.Expression_expected); + case ParsingContext.TypeMembers: + return parseErrorAtCurrentToken(Diagnostics.Property_or_signature_expected); + case ParsingContext.ClassMembers: + return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected); + case ParsingContext.EnumMembers: + return parseErrorAtCurrentToken(Diagnostics.Enum_member_expected); + case ParsingContext.HeritageClauseElement: + return parseErrorAtCurrentToken(Diagnostics.Expression_expected); case ParsingContext.VariableDeclarations: return isKeyword(token()) ? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, tokenToString(token())!) : parseErrorAtCurrentToken(Diagnostics.Variable_declaration_expected); - case ParsingContext.ObjectBindingElements: return parseErrorAtCurrentToken(Diagnostics.Property_destructuring_pattern_expected); - case ParsingContext.ArrayBindingElements: return parseErrorAtCurrentToken(Diagnostics.Array_element_destructuring_pattern_expected); - case ParsingContext.ArgumentExpressions: return parseErrorAtCurrentToken(Diagnostics.Argument_expression_expected); - case ParsingContext.ObjectLiteralMembers: return parseErrorAtCurrentToken(Diagnostics.Property_assignment_expected); - case ParsingContext.ArrayLiteralMembers: return parseErrorAtCurrentToken(Diagnostics.Expression_or_comma_expected); - case ParsingContext.JSDocParameters: return parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected); + case ParsingContext.ObjectBindingElements: + return parseErrorAtCurrentToken(Diagnostics.Property_destructuring_pattern_expected); + case ParsingContext.ArrayBindingElements: + return parseErrorAtCurrentToken(Diagnostics.Array_element_destructuring_pattern_expected); + case ParsingContext.ArgumentExpressions: + return parseErrorAtCurrentToken(Diagnostics.Argument_expression_expected); + case ParsingContext.ObjectLiteralMembers: + return parseErrorAtCurrentToken(Diagnostics.Property_assignment_expected); + case ParsingContext.ArrayLiteralMembers: + return parseErrorAtCurrentToken(Diagnostics.Expression_or_comma_expected); + case ParsingContext.JSDocParameters: + return parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected); case ParsingContext.Parameters: return isKeyword(token()) ? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_parameter_name, tokenToString(token())!) : parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected); - case ParsingContext.TypeParameters: return parseErrorAtCurrentToken(Diagnostics.Type_parameter_declaration_expected); - case ParsingContext.TypeArguments: return parseErrorAtCurrentToken(Diagnostics.Type_argument_expected); - case ParsingContext.TupleElementTypes: return parseErrorAtCurrentToken(Diagnostics.Type_expected); - case ParsingContext.HeritageClauses: return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); + case ParsingContext.TypeParameters: + return parseErrorAtCurrentToken(Diagnostics.Type_parameter_declaration_expected); + case ParsingContext.TypeArguments: + return parseErrorAtCurrentToken(Diagnostics.Type_argument_expected); + case ParsingContext.TupleElementTypes: + return parseErrorAtCurrentToken(Diagnostics.Type_expected); + case ParsingContext.HeritageClauses: + return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); case ParsingContext.ImportOrExportSpecifiers: if (token() === SyntaxKind.FromKeyword) { return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); } return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); - case ParsingContext.JsxAttributes: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); - case ParsingContext.JsxChildren: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); - case ParsingContext.AssertEntries: return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); // AssertionKey. - case ParsingContext.JSDocComment: return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); - case ParsingContext.Count: return Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. - default: Debug.assertNever(context); + case ParsingContext.JsxAttributes: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case ParsingContext.JsxChildren: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case ParsingContext.AssertEntries: + return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); // AssertionKey. + case ParsingContext.JSDocComment: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case ParsingContext.Count: + return Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. + default: + Debug.assertNever(context); } } @@ -3529,9 +3551,9 @@ namespace Parser { entity = finishNode( factory.createQualifiedName( entity, - parseRightSideOfDot(allowReservedWords, /*allowPrivateIdentifiers*/ false, /*allowUnicodeEscapeSequenceInIdentifierName*/ true) as Identifier + parseRightSideOfDot(allowReservedWords, /*allowPrivateIdentifiers*/ false, /*allowUnicodeEscapeSequenceInIdentifierName*/ true) as Identifier, ), - pos + pos, ); } return entity; @@ -3601,9 +3623,9 @@ namespace Parser { return finishNode( factory.createTemplateExpression( parseTemplateHead(isTaggedTemplate), - parseTemplateSpans(isTaggedTemplate) + parseTemplateSpans(isTaggedTemplate), ), - pos + pos, ); } @@ -3612,9 +3634,9 @@ namespace Parser { return finishNode( factory.createTemplateLiteralType( parseTemplateHead(/*isTaggedTemplate*/ false), - parseTemplateTypeSpans() + parseTemplateTypeSpans(), ), - pos + pos, ); } @@ -3635,9 +3657,9 @@ namespace Parser { return finishNode( factory.createTemplateLiteralTypeSpan( parseType(), - parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false) + parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false), ), - pos + pos, ); } @@ -3657,9 +3679,9 @@ namespace Parser { return finishNode( factory.createTemplateSpan( allowInAnd(parseExpression), - parseLiteralOfTemplateSpan(isTaggedTemplate) + parseLiteralOfTemplateSpan(isTaggedTemplate), ), - pos + pos, ); } @@ -3690,8 +3712,7 @@ namespace Parser { function parseLiteralLikeNode(kind: SyntaxKind): LiteralLikeNode { const pos = getNodePos(); - const node = - isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & TokenFlags.TemplateLiteralLikeFlags) : + const node = isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & TokenFlags.TemplateLiteralLikeFlags) : // Note that theoretically the following condition would hold true literals like 009, // which is not octal. But because of how the scanner separates the tokens, we would // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. @@ -3731,9 +3752,9 @@ namespace Parser { return finishNode( factory.createTypeReferenceNode( parseEntityNameOfTypeReference(), - parseTypeArgumentsOfTypeReference() + parseTypeArgumentsOfTypeReference(), ), - pos + pos, ); } @@ -3792,12 +3813,14 @@ namespace Parser { // Foo // Foo(?= // (?| - if (token() === SyntaxKind.CommaToken || + if ( + token() === SyntaxKind.CommaToken || token() === SyntaxKind.CloseBraceToken || token() === SyntaxKind.CloseParenToken || token() === SyntaxKind.GreaterThanToken || token() === SyntaxKind.EqualsToken || - token() === SyntaxKind.BarToken) { + token() === SyntaxKind.BarToken + ) { return finishNode(factory.createJSDocUnknownType(), pos); } else { @@ -3832,9 +3855,9 @@ namespace Parser { name!, /*questionToken*/ undefined, parseJSDocType(), - /*initializer*/ undefined + /*initializer*/ undefined, ), - pos + pos, ); } @@ -3844,7 +3867,8 @@ namespace Parser { if (parseOptional(SyntaxKind.ModuleKeyword)) { // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here? const moduleTag = factory.createJSDocNamepathType(/*type*/ undefined!); - terminate: while (true) { + terminate: + while (true) { switch (token()) { case SyntaxKind.CloseBraceToken: case SyntaxKind.EndOfFileToken: @@ -3982,7 +4006,7 @@ namespace Parser { createIdentifier(/*isIdentifier*/ true), /*questionToken*/ undefined, parseTypeAnnotation(), - /*initializer*/ undefined + /*initializer*/ undefined, ); const modifier = firstOrUndefined(modifiers); @@ -4010,11 +4034,11 @@ namespace Parser { parseNameOfParameter(modifiers), parseOptionalToken(SyntaxKind.QuestionToken), parseTypeAnnotation(), - parseInitializer() + parseInitializer(), ), - pos + pos, ), - hasJSDoc + hasJSDoc, ); topLevel = savedTopLevel; return node; @@ -4221,10 +4245,12 @@ namespace Parser { function isTypeMemberStart(): boolean { // Return true if we have the start of a signature member - if (token() === SyntaxKind.OpenParenToken || + if ( + token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken || token() === SyntaxKind.GetKeyword || - token() === SyntaxKind.SetKeyword) { + token() === SyntaxKind.SetKeyword + ) { return true; } let idToken = false; @@ -4408,9 +4434,9 @@ namespace Parser { const pos = getNodePos(); return finishNode( factory.createTupleTypeNode( - parseBracketedList(ParsingContext.TupleElementTypes, parseTupleElementNameOrTupleElementType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken) + parseBracketedList(ParsingContext.TupleElementTypes, parseTupleElementNameOrTupleElementType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken), ), - pos + pos, ); } @@ -4458,10 +4484,9 @@ namespace Parser { if (negative) { nextToken(); } - let expression: BooleanLiteral | NullLiteral | LiteralExpression | PrefixUnaryExpression = - token() === SyntaxKind.TrueKeyword || token() === SyntaxKind.FalseKeyword || token() === SyntaxKind.NullKeyword ? - parseTokenNode() : - parseLiteralLikeNode(token()) as LiteralExpression; + let expression: BooleanLiteral | NullLiteral | LiteralExpression | PrefixUnaryExpression = token() === SyntaxKind.TrueKeyword || token() === SyntaxKind.FalseKeyword || token() === SyntaxKind.NullKeyword ? + parseTokenNode() : + parseLiteralLikeNode(token()) as LiteralExpression; if (negative) { expression = finishNode(factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, expression), pos); } @@ -4486,7 +4511,7 @@ namespace Parser { if (lastError && lastError.code === Diagnostics._0_expected.code) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") + createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}"), ); } } @@ -4721,7 +4746,7 @@ namespace Parser { } function parseFunctionOrConstructorTypeToError( - isInUnionType: boolean + isInUnionType: boolean, ): TypeNode | undefined { // the function type and constructor type shorthand notation // are not allowed directly in unions and intersections, but we'll @@ -4738,7 +4763,6 @@ namespace Parser { diagnostic = isInUnionType ? Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type : Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type; - } parseErrorAtRange(type, diagnostic); return type; @@ -4749,7 +4773,7 @@ namespace Parser { function parseUnionOrIntersectionType( operator: SyntaxKind.BarToken | SyntaxKind.AmpersandToken, parseConstituentType: () => TypeNode, - createTypeNode: (types: NodeArray) => UnionOrIntersectionTypeNode + createTypeNode: (types: NodeArray) => UnionOrIntersectionTypeNode, ): TypeNode { const pos = getNodePos(); const isUnionType = operator === SyntaxKind.BarToken; @@ -4818,8 +4842,10 @@ namespace Parser { if (skipParameterStart()) { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration - if (token() === SyntaxKind.ColonToken || token() === SyntaxKind.CommaToken || - token() === SyntaxKind.QuestionToken || token() === SyntaxKind.EqualsToken) { + if ( + token() === SyntaxKind.ColonToken || token() === SyntaxKind.CommaToken || + token() === SyntaxKind.QuestionToken || token() === SyntaxKind.EqualsToken + ) { // ( xxx : // ( xxx , // ( xxx ? @@ -5103,14 +5129,16 @@ namespace Parser { // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] nextToken(); - if (!scanner.hasPrecedingLineBreak() && - (token() === SyntaxKind.AsteriskToken || isStartOfExpression())) { + if ( + !scanner.hasPrecedingLineBreak() && + (token() === SyntaxKind.AsteriskToken || isStartOfExpression()) + ) { return finishNode( factory.createYieldExpression( parseOptionalToken(SyntaxKind.AsteriskToken), - parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) + parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), ), - pos + pos, ); } else { @@ -5128,7 +5156,7 @@ namespace Parser { identifier, /*questionToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined + /*initializer*/ undefined, ); finishNode(parameter, identifier.pos); @@ -5409,13 +5437,13 @@ namespace Parser { let unwrappedType = type; while (unwrappedType?.kind === SyntaxKind.ParenthesizedType) { - unwrappedType = (unwrappedType as ParenthesizedTypeNode).type; // Skip parens if need be + unwrappedType = (unwrappedType as ParenthesizedTypeNode).type; // Skip parens if need be } const hasJSDocFunctionType = unwrappedType && isJSDocFunctionType(unwrappedType); if (!allowAmbiguity && token() !== SyntaxKind.EqualsGreaterThanToken && (hasJSDocFunctionType || token() !== SyntaxKind.OpenBraceToken)) { // Returning undefined here will cause our caller to rewind to where we started from. - return undefined; + return undefined; } // If we have an arrow, then try to parse the body. Even if not, try to parse if we @@ -5461,11 +5489,13 @@ namespace Parser { return parseFunctionBlock(isAsync ? SignatureFlags.Await : SignatureFlags.None); } - if (token() !== SyntaxKind.SemicolonToken && + if ( + token() !== SyntaxKind.SemicolonToken && token() !== SyntaxKind.FunctionKeyword && token() !== SyntaxKind.ClassKeyword && isStartOfStatement() && - !isStartOfExpressionStatement()) { + !isStartOfExpressionStatement() + ) { // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) // // Here we try to recover from a potential error situation in the case where the @@ -5510,9 +5540,9 @@ namespace Parser { colonToken = parseExpectedToken(SyntaxKind.ColonToken), nodeIsPresent(colonToken) ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) - : createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken)) + : createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken)), ), - pos + pos, ); } @@ -5655,7 +5685,6 @@ namespace Parser { * ES7 ExponentiationExpression: * 1) UnaryExpression[?Yield] * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] - * */ function parseUnaryExpressionOrHigher(): UnaryExpression | BinaryExpression { /** @@ -5968,19 +5997,24 @@ namespace Parser { let closingElement: JsxClosingElement; const lastChild: JsxChild | undefined = children[children.length - 1]; - if (lastChild?.kind === SyntaxKind.JsxElement + if ( + lastChild?.kind === SyntaxKind.JsxElement && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) - && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) { + && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName) + ) { // when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement, // restructure (
(......
)) --> (
(......)
) // (no need to error; the parent will error) const end = lastChild.children.end; - const newLast = finishNode(factory.createJsxElement( - lastChild.openingElement, - lastChild.children, - finishNode(factory.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end)), - lastChild.openingElement.pos, - end); + const newLast = finishNode( + factory.createJsxElement( + lastChild.openingElement, + lastChild.children, + finishNode(factory.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end), + ), + lastChild.openingElement.pos, + end, + ); children = createNodeArray([...children.slice(0, children.length - 1), newLast], children.pos, end); closingElement = lastChild.closingElement; @@ -6080,10 +6114,12 @@ namespace Parser { const child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); if (!child) break; list.push(child); - if (isJsxOpeningElement(openingTag) + if ( + isJsxOpeningElement(openingTag) && child?.kind === SyntaxKind.JsxElement && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) - && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) { + && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName) + ) { // stop after parsing a mismatched child like
...(
) in order to reattach the higher break; } @@ -6413,7 +6449,7 @@ namespace Parser { typeArguments, token() === SyntaxKind.NoSubstitutionTemplateLiteral ? (reScanTemplateToken(/*isTaggedTemplate*/ true), parseLiteralNode() as NoSubstitutionTemplateLiteral) : - parseTemplateExpression(/*isTaggedTemplate*/ true) + parseTemplateExpression(/*isTaggedTemplate*/ true), ); if (questionDotToken || tag.flags & NodeFlags.OptionalChain) { (tagExpression as Mutable).flags |= NodeFlags.OptionalChain; @@ -6492,9 +6528,9 @@ namespace Parser { function canFollowTypeArgumentsInExpression(): boolean { switch (token()) { // These tokens can follow a type argument list in a call expression. - case SyntaxKind.OpenParenToken: // foo( - case SyntaxKind.NoSubstitutionTemplateLiteral: // foo `...` - case SyntaxKind.TemplateHead: // foo `...${100}...` + case SyntaxKind.OpenParenToken: // foo( + case SyntaxKind.NoSubstitutionTemplateLiteral: // foo `...` + case SyntaxKind.TemplateHead: // foo `...${100}...` return true; // A type argument list followed by `<` never makes sense, and a type argument list followed // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in @@ -6839,9 +6875,11 @@ namespace Parser { let initializer!: VariableDeclarationList | Expression; if (token() !== SyntaxKind.SemicolonToken) { - if (token() === SyntaxKind.VarKeyword || token() === SyntaxKind.LetKeyword || token() === SyntaxKind.ConstKeyword || + if ( + token() === SyntaxKind.VarKeyword || token() === SyntaxKind.LetKeyword || token() === SyntaxKind.ConstKeyword || token() === SyntaxKind.UsingKeyword && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || - token() === SyntaxKind.AwaitKeyword && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf)) { + token() === SyntaxKind.AwaitKeyword && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf) + ) { initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); } else { @@ -7143,9 +7181,11 @@ namespace Parser { if (currentToken === SyntaxKind.TypeKeyword) { currentToken = lookAhead(nextToken); } - if (currentToken === SyntaxKind.EqualsToken || currentToken === SyntaxKind.AsteriskToken || + if ( + currentToken === SyntaxKind.EqualsToken || currentToken === SyntaxKind.AsteriskToken || currentToken === SyntaxKind.OpenBraceToken || currentToken === SyntaxKind.DefaultKeyword || - currentToken === SyntaxKind.AsKeyword || currentToken === SyntaxKind.AtToken) { + currentToken === SyntaxKind.AsKeyword || currentToken === SyntaxKind.AtToken + ) { return true; } continue; @@ -7537,8 +7577,10 @@ namespace Parser { const hasJSDoc = hasPrecedingJSDocComment(); const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); let exclamationToken: ExclamationToken | undefined; - if (allowExclamation && name.kind === SyntaxKind.Identifier && - token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) { + if ( + allowExclamation && name.kind === SyntaxKind.Identifier && + token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak() + ) { exclamationToken = parseTokenNode>(); } const type = parseTypeAnnotation(); @@ -7591,8 +7633,10 @@ namespace Parser { const savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); - declarations = parseDelimitedList(ParsingContext.VariableDeclarations, - inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation); + declarations = parseDelimitedList( + ParsingContext.VariableDeclarations, + inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation, + ); setDisallowInContext(savedDisallowIn); } @@ -7667,7 +7711,7 @@ namespace Parser { name: PropertyName, questionToken: QuestionToken | undefined, exclamationToken: ExclamationToken | undefined, - diagnosticMessage?: DiagnosticMessage + diagnosticMessage?: DiagnosticMessage, ): MethodDeclaration { const isGenerator = asteriskToken ? SignatureFlags.Yield : SignatureFlags.None; const isAsync = some(modifiers, isAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None; @@ -7683,7 +7727,7 @@ namespace Parser { typeParameters, parameters, type, - body + body, ); // An exclamation token on a method is invalid syntax and will be handled by the grammar checker @@ -7696,7 +7740,7 @@ namespace Parser { hasJSDoc: boolean, modifiers: NodeArray | undefined, name: PropertyName, - questionToken: QuestionToken | undefined + questionToken: QuestionToken | undefined, ): PropertyDeclaration { const exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(SyntaxKind.ExclamationToken) : undefined; const type = parseTypeAnnotation(); @@ -7707,14 +7751,15 @@ namespace Parser { name, questionToken || exclamationToken, type, - initializer); + initializer, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parsePropertyOrMethodDeclaration( pos: number, hasJSDoc: boolean, - modifiers: NodeArray | undefined + modifiers: NodeArray | undefined, ): PropertyDeclaration | MethodDeclaration { const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); const name = parsePropertyName(); @@ -7791,12 +7836,12 @@ namespace Parser { // If it *is* a keyword, but not an accessor, check a little farther along // to see if it should actually be parsed as a class member. switch (token()) { - case SyntaxKind.OpenParenToken: // Method declaration - case SyntaxKind.LessThanToken: // Generic Method declaration - case SyntaxKind.ExclamationToken: // Non-null assertion on property name - case SyntaxKind.ColonToken: // Type Annotation for declaration - case SyntaxKind.EqualsToken: // Initializer for declaration - case SyntaxKind.QuestionToken: // Not valid, but permitted so that it gets caught later on. + case SyntaxKind.OpenParenToken: // Method declaration + case SyntaxKind.LessThanToken: // Generic Method declaration + case SyntaxKind.ExclamationToken: // Non-null assertion on property name + case SyntaxKind.ColonToken: // Type Annotation for declaration + case SyntaxKind.EqualsToken: // Initializer for declaration + case SyntaxKind.QuestionToken: // Not valid, but permitted so that it gets caught later on. return true; default: // Covers @@ -7883,12 +7928,12 @@ namespace Parser { } /* - * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. - * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect - * and turns it into a standalone declaration), then it is better to parse it and report an error later. - * - * In such situations, 'permitConstAsModifier' should be set to true. - */ + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitConstAsModifier' should be set to true. + */ function parseModifiers(allowDecorators: false, permitConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): NodeArray | undefined; function parseModifiers(allowDecorators: true, permitConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): NodeArray | undefined; function parseModifiers(allowDecorators: boolean, permitConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): NodeArray | undefined { @@ -7978,11 +8023,13 @@ namespace Parser { // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name - if (tokenIsIdentifierOrKeyword(token()) || + if ( + tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.StringLiteral || token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.AsteriskToken || - token() === SyntaxKind.OpenBracketToken) { + token() === SyntaxKind.OpenBracketToken + ) { const isAmbient = some(modifiers, isDeclareModifier); if (isAmbient) { for (const m of modifiers!) { @@ -8269,7 +8316,8 @@ namespace Parser { } let isTypeOnly = false; - if (token() !== SyntaxKind.FromKeyword && + if ( + token() !== SyntaxKind.FromKeyword && identifier?.escapedText === "type" && (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration()) ) { @@ -8285,9 +8333,10 @@ namespace Parser { // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; let importClause: ImportClause | undefined; - if (identifier || // import id + if ( + identifier || // import id token() === SyntaxKind.AsteriskToken || // import * - token() === SyntaxKind.OpenBraceToken // import { + token() === SyntaxKind.OpenBraceToken // import { ) { importClause = parseImportClause(identifier, afterImportPos, isTypeOnly); parseExpected(SyntaxKind.FromKeyword); @@ -8326,7 +8375,7 @@ namespace Parser { if (lastError && lastError.code === Diagnostics._0_expected.code) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}") + createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}"), ); } } @@ -8368,8 +8417,10 @@ namespace Parser { // If there was no default import or if there is comma token after default import // parse namespace or named imports let namedBindings: NamespaceImport | NamedImports | undefined; - if (!identifier || - parseOptional(SyntaxKind.CommaToken)) { + if ( + !identifier || + parseOptional(SyntaxKind.CommaToken) + ) { namedBindings = token() === SyntaxKind.AsteriskToken ? parseNamespaceImport() : parseNamedImportsOrExports(SyntaxKind.NamedImports); } @@ -8581,6 +8632,7 @@ namespace Parser { return withJSDoc(finishNode(node, pos), hasJSDoc); } + // dprint-ignore const enum ParsingContext { SourceElements, // Elements in source file BlockStatements, // Statements in block @@ -8608,17 +8660,17 @@ namespace Parser { ImportOrExportSpecifiers, // Named import clause's import specifier list, AssertEntries, // Import entries list. JSDocComment, // Parsing via JSDocParser - Count // Number of parsing contexts + Count, // Number of parsing contexts } const enum Tristate { False, True, - Unknown + Unknown, } export namespace JSDocParser { - export function parseJSDocTypeExpressionForTests(content: string, start: number | undefined, length: number | undefined): { jsDocTypeExpression: JSDocTypeExpression, diagnostics: Diagnostic[] } | undefined { + export function parseJSDocTypeExpressionForTests(content: string, start: number | undefined, length: number | undefined): { jsDocTypeExpression: JSDocTypeExpression; diagnostics: Diagnostic[]; } | undefined { initializeState("file.js", content, ScriptTarget.Latest, /*syntaxCursor*/ undefined, ScriptKind.JS); scanner.setText(content, start, length); currentToken = scanner.scan(); @@ -8668,7 +8720,7 @@ namespace Parser { return finishNode(result, pos); } - export function parseIsolatedJSDocComment(content: string, start: number | undefined, length: number | undefined): { jsDoc: JSDoc, diagnostics: Diagnostic[] } | undefined { + export function parseIsolatedJSDocComment(content: string, start: number | undefined, length: number | undefined): { jsDoc: JSDoc; diagnostics: Diagnostic[]; } | undefined { initializeState("", content, ScriptTarget.Latest, /*syntaxCursor*/ undefined, ScriptKind.JS); const jsDoc = doInsideOfContext(NodeFlags.JSDoc, () => parseJSDocCommentWorker(start, length)); @@ -8764,7 +8816,8 @@ namespace Parser { state = JSDocState.BeginningOfLine; indent = 0; } - loop: while (true) { + loop: + while (true) { switch (token()) { case SyntaxKind.AtToken: removeTrailingWhitespace(comments); @@ -9040,7 +9093,8 @@ namespace Parser { state = JSDocState.SawAsterisk; } let tok = token() as JSDocSyntaxKind | SyntaxKind.JSDocCommentTextToken; - loop: while (true) { + loop: + while (true) { switch (tok) { case SyntaxKind.NewLineTrivia: state = JSDocState.BeginningOfLine; @@ -9163,9 +9217,11 @@ namespace Parser { function parseJSDocLinkPrefix() { skipWhitespaceOrAsterisk(); - if (token() === SyntaxKind.OpenBraceToken + if ( + token() === SyntaxKind.OpenBraceToken && nextTokenJSDoc() === SyntaxKind.AtToken - && tokenIsIdentifierOrKeyword(nextTokenJSDoc())) { + && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + ) { const kind = scanner.getTokenValue(); if (isJSDocLinkTag(kind)) return kind; } @@ -9198,7 +9254,7 @@ namespace Parser { return token() === SyntaxKind.OpenBraceToken ? parseJSDocTypeExpression() : undefined; } - function parseBracketNameInPropertyAndParamTag(): { name: EntityName, isBracketed: boolean } { + function parseBracketNameInPropertyAndParamTag(): { name: EntityName; isBracketed: boolean; } { // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' const isBracketed = parseOptionalJsdoc(SyntaxKind.OpenBracketToken); if (isBracketed) { @@ -9365,14 +9421,14 @@ namespace Parser { return finishNode(factory.createJSDocSatisfiesTag(tagName, typeExpression, comments), start); } - function parseExpressionWithTypeArgumentsForAugments(): ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression } { + function parseExpressionWithTypeArgumentsForAugments(): ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression; } { const usedBrace = parseOptional(SyntaxKind.OpenBraceToken); const pos = getNodePos(); const expression = parsePropertyAccessEntityNameExpression(); scanner.setInJSDocType(true); const typeArguments = tryParseTypeArguments(); scanner.setInJSDocType(false); - const node = factory.createExpressionWithTypeArguments(expression, typeArguments) as ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression }; + const node = factory.createExpressionWithTypeArguments(expression, typeArguments) as ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression; }; const res = finishNode(node, pos); if (usedBrace) { parseExpected(SyntaxKind.CloseBraceToken); @@ -9476,7 +9532,7 @@ namespace Parser { /*modifiers*/ undefined, typeNameOrNamespaceName, body, - nested ? NodeFlags.NestedNamespace : undefined + nested ? NodeFlags.NestedNamespace : undefined, ) as JSDocNamespaceDeclaration; return finishNode(jsDocNamespaceNode, start); } @@ -9562,8 +9618,10 @@ namespace Parser { case SyntaxKind.AtToken: if (canParseTag) { const child = tryParseChildTag(target, indent); - if (child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) && - name && (isIdentifierNode(child.name) || !escapedTextsEqual(name, child.name.left))) { + if ( + child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) && + name && (isIdentifierNode(child.name) || !escapedTextsEqual(name, child.name.left)) + ) { return false; } return child; @@ -9652,7 +9710,8 @@ namespace Parser { typeParameters.push(node); } skipWhitespaceOrAsterisk(); - } while (parseOptionalJsdoc(SyntaxKind.CommaToken)); + } + while (parseOptionalJsdoc(SyntaxKind.CommaToken)); return createNodeArray(typeParameters, pos); } @@ -9781,8 +9840,7 @@ namespace IncrementalParser { // // Also, mark any syntax elements that intersect the changed span. We know, up front, // that we cannot reuse these elements. - updateTokenPositionsAndMarkElements(incrementalSourceFile, - changeRange.span.start, textSpanEnd(changeRange.span), textSpanEnd(textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, textSpanEnd(changeRange.span), textSpanEnd(textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); // Now that we've set up our internal incremental state just proceed and parse the // source file in the normal fashion. When possible the parser will retrieve and @@ -9803,7 +9861,7 @@ namespace IncrementalParser { delta, oldText, newText, - aggressiveChecks + aggressiveChecks, ); result.impliedNodeFormat = sourceFile.impliedNodeFormat; return result; @@ -9817,7 +9875,7 @@ namespace IncrementalParser { delta: number, oldText: string, newText: string, - aggressiveChecks: boolean + aggressiveChecks: boolean, ): CommentDirective[] | undefined { if (!oldDirectives) return newDirectives; let commentDirectives: CommentDirective[] | undefined; @@ -9834,7 +9892,7 @@ namespace IncrementalParser { // end, forward or backward appropriately. const updatedDirective: CommentDirective = { range: { pos: range.pos + delta, end: range.end + delta }, - type + type, }; commentDirectives = append(commentDirectives, updatedDirective); if (aggressiveChecks) { @@ -10016,8 +10074,8 @@ namespace IncrementalParser { delta: number, oldText: string, newText: string, - aggressiveChecks: boolean): void { - + aggressiveChecks: boolean, + ): void { visitNode(sourceFile); return; @@ -10280,7 +10338,7 @@ namespace IncrementalParser { // Either we don'd have a node, or we have a node at the position being asked for. Debug.assert(!current || current.pos === position); return current as IncrementalNode; - } + }, }; // Finds the highest element in the tree we can find that starts at the provided position. @@ -10342,7 +10400,7 @@ namespace IncrementalParser { } const enum InvalidPosition { - Value = -1 + Value = -1, } } @@ -10433,7 +10491,8 @@ export function processPragmasIntoFields(context: PragmaContext, reportDiagnosti case "amd-dependency": { context.amdDependencies = map( toArray(entryOrList) as PragmaPseudoMap["amd-dependency"][], - x => ({ name: x.arguments.name, path: x.arguments.path })); + x => ({ name: x.arguments.name, path: x.arguments.path }), + ); break; } case "amd-module": { @@ -10459,7 +10518,7 @@ export function processPragmasIntoFields(context: PragmaContext, reportDiagnosti context.checkJsDirective = { enabled: key === "ts-check", end: entry.range.end, - pos: entry.range.pos + pos: entry.range.pos, }; } }); @@ -10470,7 +10529,8 @@ export function processPragmasIntoFields(context: PragmaContext, reportDiagnosti case "jsximportsource": case "jsxruntime": return; // Accessed directly - default: Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? + default: + Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future? } }); } @@ -10496,7 +10556,7 @@ function extractPragmas(pragmas: PragmaPseudoMapEntry[], range: CommentRange, te return; } if (pragma.args) { - const argument: {[index: string]: string | {value: string, pos: number, end: number}} = {}; + const argument: { [index: string]: string | { value: string; pos: number; end: number; }; } = {}; for (const arg of pragma.args) { const matcher = getNamedArgRegEx(arg.name); const matchResult = matcher.exec(text); @@ -10510,7 +10570,7 @@ function extractPragmas(pragmas: PragmaPseudoMapEntry[], range: CommentRange, te argument[arg.name] = { value, pos: startPos, - end: startPos + value.length + end: startPos + value.length, }; } else { @@ -10554,11 +10614,11 @@ function addPragmaForMatch(pragmas: PragmaPseudoMapEntry[], range: CommentRange, return; } -function getNamedPragmaArguments(pragma: PragmaDefinition, text: string | undefined): {[index: string]: string} | "fail" { +function getNamedPragmaArguments(pragma: PragmaDefinition, text: string | undefined): { [index: string]: string; } | "fail" { if (!text) return {}; if (!pragma.args) return {}; const args = trimString(text).split(/\s+/); - const argMap: {[index: string]: string} = {}; + const argMap: { [index: string]: string; } = {}; for (let i = 0; i < pragma.args.length; i++) { const argument = pragma.args[i]; if (!args[i] && !argument.optional) { diff --git a/src/compiler/path.ts b/src/compiler/path.ts index 661997d28d354..c77fa141f071d 100644 --- a/src/compiler/path.ts +++ b/src/compiler/path.ts @@ -194,8 +194,10 @@ function getEncodedRootLength(path: string): number { // special case interpreted as "the machine from which the URL is being interpreted". const scheme = path.slice(0, schemeEnd); const authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + if ( + scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1)) + ) { const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); if (volumeSeparatorEnd !== -1) { if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) { @@ -452,7 +454,7 @@ function pathComponents(path: string, rootLength: number) { } /** @internal */ -export type PathPathComponents = Path[] & { __pathComponensBrand: any }; +export type PathPathComponents = Path[] & { __pathComponensBrand: any; }; /** * Parse a path into an array containing a root component (at index 0) and zero or more path @@ -950,7 +952,7 @@ export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, rela resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, - getCanonicalFileName + getCanonicalFileName, ); const firstComponent = pathComponents[0]; diff --git a/src/compiler/perfLogger.ts b/src/compiler/perfLogger.ts index 20ec69d035af2..f2476db967541 100644 --- a/src/compiler/perfLogger.ts +++ b/src/compiler/perfLogger.ts @@ -22,7 +22,6 @@ export interface PerfLogger { logStopScheduledOperation(): void; } - // Load optional module to enable Event Tracing for Windows // See https://github.com/microsoft/typescript-etw for more information let etwModule: typeof import("@microsoft/typescript-etw") | undefined; diff --git a/src/compiler/performance.ts b/src/compiler/performance.ts index 4f2096ec7204f..1605fa5e3562a 100644 --- a/src/compiler/performance.ts +++ b/src/compiler/performance.ts @@ -35,7 +35,7 @@ export function createTimer(measureName: string, startMarkName: string, endMarkN let enterCount = 0; return { enter, - exit + exit, }; function enter() { diff --git a/src/compiler/performanceCore.ts b/src/compiler/performanceCore.ts index 3f8a459bb0d75..a214ced47ef2c 100644 --- a/src/compiler/performanceCore.ts +++ b/src/compiler/performanceCore.ts @@ -41,7 +41,7 @@ export interface PerformanceObserverEntryList { /** @internal */ export interface PerformanceObserver { disconnect(): void; - observe(options: { entryTypes: readonly ("mark" | "measure")[] }): void; + observe(options: { entryTypes: readonly ("mark" | "measure")[]; }): void; } /** @internal */ @@ -66,16 +66,18 @@ function hasRequiredAPI(performance: Performance | undefined, PerformanceObserve } function tryGetWebPerformanceHooks(): PerformanceHooks | undefined { - if (typeof performance === "object" && + if ( + typeof performance === "object" && typeof PerformanceObserver === "function" && - hasRequiredAPI(performance, PerformanceObserver)) { + hasRequiredAPI(performance, PerformanceObserver) + ) { return { // For now we always write native performance events when running in the browser. We may // make this conditional in the future if we find that native web performance hooks // in the browser also slow down compilation. shouldWriteNativeEvents: true, performance, - PerformanceObserver + PerformanceObserver, }; } } @@ -89,7 +91,7 @@ function tryGetNodePerformanceHooks(): PerformanceHooks | undefined { // By default, only write native events when generating a cpu profile or using the v8 profiler. shouldWriteNativeEvents: false, performance, - PerformanceObserver + PerformanceObserver, }; } } @@ -114,7 +116,6 @@ export function tryGetNativePerformanceHooks() { * * @internal */ -export const timestamp = - nativePerformance ? () => nativePerformance.now() : +export const timestamp = nativePerformance ? () => nativePerformance.now() : Date.now ? Date.now : () => +(new Date()); diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 9d1c258cec3e5..9e8af35bf4e62 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -404,7 +404,7 @@ export function createCompilerHost(options: CompilerOptions, setParentNodes?: bo export function createGetSourceFile( readFile: ProgramHost["readFile"], getCompilerOptions: () => CompilerOptions, - setParentNodes: boolean | undefined + setParentNodes: boolean | undefined, ): CompilerHost["getSourceFile"] { return (fileName, languageVersionOrOptions, onError) => { let text: string | undefined; @@ -428,7 +428,7 @@ export function createGetSourceFile( export function createWriteFileMeasuringIO( actualWriteFile: (path: string, data: string, writeByteOrderMark: boolean) => void, createDirectory: (path: string) => void, - directoryExists: (path: string) => boolean + directoryExists: (path: string) => boolean, ): CompilerHost["writeFile"] { return (fileName, data, writeByteOrderMark, onError) => { try { @@ -443,7 +443,7 @@ export function createWriteFileMeasuringIO( writeByteOrderMark, actualWriteFile, createDirectory, - directoryExists + directoryExists, ); performance.mark("afterIOWrite"); @@ -500,7 +500,7 @@ export function createCompilerHostWorker(options: CompilerOptions, setParentNode realpath, readDirectory: (path, extensions, include, exclude, depth) => system.readDirectory(path, extensions, include, exclude, depth), createDirectory: d => system.createDirectory(d), - createHash: maybeBind(system, system.createHash) + createHash: maybeBind(system, system.createHash), }; return compilerHost; } @@ -518,7 +518,7 @@ export interface CompilerHostLikeForCache { export function changeCompilerHostLikeToUseCache( host: CompilerHostLikeForCache, toPath: (fileName: string) => Path, - getSourceFile?: CompilerHost["getSourceFile"] + getSourceFile?: CompilerHost["getSourceFile"], ) { const originalReadFile = host.readFile; const originalFileExists = host.fileExists; @@ -625,7 +625,7 @@ export function changeCompilerHostLikeToUseCache( originalCreateDirectory, originalWriteFile, getSourceFileWithCache, - readFileWithCache + readFileWithCache, }; } @@ -680,7 +680,7 @@ export enum ForegroundColorEscapeSequences { Red = "\u001b[91m", Yellow = "\u001b[93m", Blue = "\u001b[94m", - Cyan = "\u001b[96m" + Cyan = "\u001b[96m", } const gutterStyleSequence = "\u001b[7m"; const gutterSeparator = " "; @@ -690,10 +690,14 @@ const halfIndent = " "; const indent = " "; function getCategoryFormat(category: DiagnosticCategory): ForegroundColorEscapeSequences { switch (category) { - case DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; - case DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; - case DiagnosticCategory.Suggestion: return Debug.fail("Should never get an Info diagnostic on the command line."); - case DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + case DiagnosticCategory.Error: + return ForegroundColorEscapeSequences.Red; + case DiagnosticCategory.Warning: + return ForegroundColorEscapeSequences.Yellow; + case DiagnosticCategory.Suggestion: + return Debug.fail("Should never get an Info diagnostic on the command line."); + case DiagnosticCategory.Message: + return ForegroundColorEscapeSequences.Blue; } } @@ -726,8 +730,8 @@ function formatCodeSpan(file: SourceFile, start: number, length: number, indent: const lineStart = getPositionOfLineAndCharacter(file, i, 0); const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; let lineContent = file.text.slice(lineStart, lineEnd); - lineContent = trimStringEnd(lineContent); // trim from end - lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces + lineContent = trimStringEnd(lineContent); // trim from end + lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; @@ -888,7 +892,7 @@ export function isExclusivelyTypeOnlyImportOrExport(decl: ImportDeclaration | Ex * @param usage The module reference string * @returns The final resolution mode of the import */ -export function getModeForUsageLocation(file: { impliedNodeFormat?: ResolutionMode }, usage: StringLiteralLike) { +export function getModeForUsageLocation(file: { impliedNodeFormat?: ResolutionMode; }, usage: StringLiteralLike) { if (file.impliedNodeFormat === undefined) return undefined; if ((isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent))) { const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent); @@ -947,7 +951,6 @@ export interface ResolutionNameAndModeGetter { getMode(entry: Entry, file: SourceFile): ResolutionMode; } - /** @internal */ export interface ResolutionLoader { nameAndMode: ResolutionNameAndModeGetter; @@ -974,15 +977,16 @@ export function createModuleResolutionLoader( ): ResolutionLoader { return { nameAndMode: moduleResolutionNameAndModeGetter, - resolve: (moduleName, resolutionMode) => resolveModuleName( - moduleName, - containingFile, - options, - host, - cache, - redirectedReference, - resolutionMode, - ), + resolve: (moduleName, resolutionMode) => + resolveModuleName( + moduleName, + containingFile, + options, + host, + cache, + redirectedReference, + resolutionMode, + ), }; } @@ -1007,15 +1011,16 @@ export function createTypeReferenceResolutionLoader { return { nameAndMode: typeReferenceResolutionNameAndModeGetter, - resolve: (typeRef, resoluionMode) => resolveTypeReferenceDirective( - typeRef, - containingFile, - options, - host, - redirectedReference, - cache, - resoluionMode, - ), + resolve: (typeRef, resoluionMode) => + resolveTypeReferenceDirective( + typeRef, + containingFile, + options, + host, + redirectedReference, + cache, + resoluionMode, + ), }; } @@ -1056,7 +1061,7 @@ export function loadWithModeAwareCache( resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined, - cb: (resolvedProjectReference: ResolvedProjectReference, parent: ResolvedProjectReference | undefined) => T | undefined + cb: (resolvedProjectReference: ResolvedProjectReference, parent: ResolvedProjectReference | undefined) => T | undefined, ): T | undefined { return forEachProjectReference(/*projectReferences*/ undefined, resolvedProjectReferences, (resolvedRef, parent) => resolvedRef && cb(resolvedRef, parent)); } @@ -1065,7 +1070,7 @@ function forEachProjectReference( projectReferences: readonly ProjectReference[] | undefined, resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined, cbResolvedRef: (resolvedRef: ResolvedProjectReference | undefined, parent: ResolvedProjectReference | undefined, index: number) => T | undefined, - cbRef?: (projectReferences: readonly ProjectReference[] | undefined, parent: ResolvedProjectReference | undefined) => T | undefined + cbRef?: (projectReferences: readonly ProjectReference[] | undefined, parent: ResolvedProjectReference | undefined) => T | undefined, ): T | undefined { let seenResolvedRefs: Set | undefined; @@ -1076,7 +1081,6 @@ function forEachProjectReference( resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined, parent: ResolvedProjectReference | undefined, ): T | undefined { - // Visit project references first if (cbRef) { const result = cbRef(projectReferences, parent); @@ -1209,7 +1213,7 @@ export function isProgramUptoDate( hasInvalidatedLibResolutions: HasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames: HasChangedAutomaticTypeDirectiveNames | undefined, getParsedCommandLine: (fileName: string) => ParsedCommandLine | undefined, - projectReferences: readonly ProjectReference[] | undefined + projectReferences: readonly ProjectReference[] | undefined, ): boolean { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames?.()) return false; @@ -1257,7 +1261,7 @@ export function isProgramUptoDate( function resolvedProjectReferenceUptoDate(oldResolvedRef: ResolvedProjectReference | undefined, oldRef: ProjectReference): boolean { if (oldResolvedRef) { - // Assume true + // Assume true if (contains(seenResolvedRefs, oldResolvedRef)) return true; const refPath = resolveProjectReferencePath(oldRef); @@ -1276,8 +1280,7 @@ export function isProgramUptoDate( (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); // If child project references are upto date, this project reference is uptodate - return !forEach(oldResolvedRef.references, (childResolvedRef, index) => - !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences![index])); + return !forEach(oldResolvedRef.references, (childResolvedRef, index) => !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences![index])); } // In old program, not able to resolve project reference path, @@ -1511,7 +1514,6 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg let packageMap: Map | undefined; - // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. // This works as imported modules are discovered recursively in a depth first manner, specifically: // - For each root file, findSourceFile is called. @@ -1575,12 +1577,13 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg redirectedReference, options, containingSourceFile, - ).map(resolved => resolved ? - ((resolved as ResolvedModuleFull).extension !== undefined) ? - { resolvedModule: resolved as ResolvedModuleFull } : - // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. - { resolvedModule: { ...resolved, extension: extensionFromPath(resolved.resolvedFileName) } } : - emptyResolution + ).map(resolved => + resolved ? + ((resolved as ResolvedModuleFull).extension !== undefined) ? + { resolvedModule: resolved as ResolvedModuleFull } : + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + { resolvedModule: { ...resolved, extension: extensionFromPath(resolved.resolvedFileName) } } : + emptyResolution ); moduleResolutionCache = host.getModuleResolutionCache?.(); } @@ -1648,8 +1651,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg } else { const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache?.getPackageJsonInfoCache()); - actualResolveLibrary = (libraryName, resolveFrom, options) => - resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); + actualResolveLibrary = (libraryName, resolveFrom, options) => resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); } // Map from a stringified PackageId to the source file with that id. @@ -1689,7 +1691,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg toPath, getResolvedProjectReferences, getSourceOfProjectReferenceRedirect, - forEachResolvedProjectReference + forEachResolvedProjectReference, }); const readFile = host.readFile.bind(host) as typeof host.readFile; @@ -1800,9 +1802,11 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg const oldSourceFiles = oldProgram.getSourceFiles(); for (const oldSourceFile of oldSourceFiles) { const newFile = getSourceFileByPath(oldSourceFile.resolvedPath); - if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || + if ( + shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // old file wasn't redirect but new file is - (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path) + ) { host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } @@ -1826,7 +1830,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg if (!projectReferenceRedirects?.has(toPath(oldRefPath))) { host.onReleaseParsedCommandLine!(oldRefPath, oldResolvedRef, oldProgram!.getCompilerOptions()); } - } + }, ); } @@ -1952,7 +1956,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg if (!resolution.resolutionDiagnostics?.length) return; (fileProcessingDiagnostics ??= []).push({ kind: FilePreprocessingDiagnosticsKind.ResolutionDiagnostics, - diagnostics: resolution.resolutionDiagnostics + diagnostics: resolution.resolutionDiagnostics, }); } @@ -2056,7 +2060,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg () => mapDefined(emittedFiles, file => file.isDeclarationFile ? undefined : file.fileName), currentDirectory, getCanonicalFileName, - commonSourceDirectory => checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory) + commonSourceDirectory => checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory), ); } return commonSourceDirectory; @@ -2129,14 +2133,15 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg const oldResolution = oldSourceFile.resolvedModules?.get(moduleName.text, mode); if (oldResolution?.resolvedModule) { if (isTraceEnabled(options, host)) { - trace(host, + trace( + host, oldResolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2, moduleName.text, getNormalizedAbsolutePath(file.originalFileName, currentDirectory), oldResolution.resolvedModule.resolvedFileName, - oldResolution.resolvedModule.packageId && packageIdToString(oldResolution.resolvedModule.packageId) + oldResolution.resolvedModule.packageId && packageIdToString(oldResolution.resolvedModule.packageId), ); } (result ??= new Array(moduleNames.length))[i] = oldResolution; @@ -2263,14 +2268,15 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg const oldResolution = (!isString(containingFile) ? oldSourceFile?.resolvedTypeReferenceDirectiveNames : oldProgram?.getAutomaticTypeDirectiveResolutions())?.get(typeDirectiveName, mode); if (oldResolution?.resolvedTypeReferenceDirective) { if (isTraceEnabled(options, host)) { - trace(host, + trace( + host, oldResolution.resolvedTypeReferenceDirective.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2, typeDirectiveName, !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile, oldResolution.resolvedTypeReferenceDirective.resolvedFileName, - oldResolution.resolvedTypeReferenceDirective.packageId && packageIdToString(oldResolution.resolvedTypeReferenceDirective.packageId) + oldResolution.resolvedTypeReferenceDirective.packageId && packageIdToString(oldResolution.resolvedTypeReferenceDirective.packageId), ); } (result ??= new Array(typeDirectiveNames.length))[i] = oldResolution; @@ -2329,7 +2335,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // If array of references is changed, we cant resue old program const newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path)!.commandLine.projectReferences : projectReferences; return !arrayIsEqualTo(oldProjectReferences, newReferences, projectReferenceIsEqualTo); - } + }, ); } @@ -2361,7 +2367,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; - const modifiedSourceFiles: { oldFile: SourceFile, newFile: SourceFile }[] = []; + const modifiedSourceFiles: { oldFile: SourceFile; newFile: SourceFile; }[] = []; structureIsReused = StructureIsReused.Completely; // If the missing file paths are now present, it can change the progam structure, @@ -2372,7 +2378,10 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg } const oldSourceFiles = oldProgram.getSourceFiles(); - const enum SeenPackageName { Exists, Modified } + const enum SeenPackageName { + Exists, + Modified, + } const seenPackageNames = new Map(); for (const oldSourceFile of oldSourceFiles) { @@ -2530,8 +2539,10 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg return StructureIsReused.SafeModules; } - if (oldProgram.resolvedLibReferences && - forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual)) { + if ( + oldProgram.resolvedLibReferences && + forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual) + ) { return StructureIsReused.SafeModules; } @@ -2623,7 +2634,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: readonly SourceFile[], - data?: WriteFileCallbackData + data?: WriteFileCallbackData, ) { host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); } @@ -2638,7 +2649,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg /*targetSourceFile*/ undefined, /*transformers*/ noTransformers, /*emitOnly*/ false, - /*onlyBuildInfo*/ true + /*onlyBuildInfo*/ true, ); performance.mark("afterEmit"); @@ -2736,7 +2747,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg getTransformers(options, customTransformers, emitOnly), emitOnly, /*onlyBuildInfo*/ false, - forceDtsEmit + forceDtsEmit, ); performance.mark("afterEmit"); @@ -2755,7 +2766,8 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg function getDiagnosticsHelper( sourceFile: SourceFile | undefined, getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken | undefined) => readonly T[], - cancellationToken: CancellationToken | undefined): readonly T[] { + cancellationToken: CancellationToken | undefined, + ): readonly T[] { if (sourceFile) { return sortAndDeduplicateDiagnostics(getDiagnostics(sourceFile, cancellationToken)); } @@ -2776,7 +2788,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg } function getCachedSemanticDiagnostics(sourceFile?: SourceFile): readonly Diagnostic[] | undefined { - return sourceFile + return sourceFile ? cachedBindAndCheckDiagnosticsForFile.perFile?.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics; } @@ -2839,7 +2851,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken | undefined): readonly Diagnostic[] { return concatenate( filterSemanticDiagnostics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), - getProgramDiagnostics(sourceFile) + getProgramDiagnostics(sourceFile), ); } @@ -2867,7 +2879,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // - check JS: .js files with either // ts-check or checkJs: true // - external: files that are added by plugins const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === ScriptKind.TS || sourceFile.scriptKind === ScriptKind.TSX - || sourceFile.scriptKind === ScriptKind.External || isPlainJs || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred); + || sourceFile.scriptKind === ScriptKind.External || isPlainJs || isCheckJs || sourceFile.scriptKind === ScriptKind.Deferred); let bindDiagnostics: readonly Diagnostic[] = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray; let checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : emptyArray; if (isPlainJs) { @@ -3119,9 +3131,11 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // Check modifiers of property declaration if (nodes === (parent as PropertyDeclaration).modifiers) { for (const modifier of nodes as NodeArray) { - if (isModifier(modifier) + if ( + isModifier(modifier) && modifier.kind !== SyntaxKind.StaticKeyword - && modifier.kind !== SyntaxKind.AccessorKeyword) { + && modifier.kind !== SyntaxKind.AccessorKeyword + ) { diagnostics.push(createDiagnosticForNode(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); } } @@ -3211,7 +3225,6 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg cache: DiagnosticCache, getDiagnostics: (sourceFile: T, cancellationToken: CancellationToken | undefined) => readonly U[], ): readonly U[] { - const cachedResult = sourceFile ? cache.perFile?.get(sourceFile.path) : cache.allDiagnostics; @@ -3236,7 +3249,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg function getOptionsDiagnostics(): SortedReadonlyArray { return sortAndDeduplicateDiagnostics(concatenate( programDiagnostics.getGlobalDiagnostics(), - getOptionsDiagnosticsOfConfigFile() + getOptionsDiagnosticsOfConfigFile(), )); } @@ -3299,8 +3312,10 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // If we are importing helpers, we need to add a synthetic reference to resolve the // helpers library. - if ((getIsolatedModules(options) || isExternalModuleFile) - && !file.isDeclarationFile) { + if ( + (getIsolatedModules(options) || isExternalModuleFile) + && !file.isDeclarationFile + ) { if (options.importHelpers) { // synthesize 'import "tslib"' declaration imports = [createSyntheticImport(externalHelpersModuleNameText, file)]; @@ -3428,8 +3443,8 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg fileName: string, getSourceFile: (fileName: string) => SourceFile | undefined, fail?: (diagnostic: DiagnosticMessage, ...argument: string[]) => void, - reason?: FileIncludeReason): SourceFile | undefined { - + reason?: FileIncludeReason, + ): SourceFile | undefined { if (hasExtension(fileName)) { const canonicalFileName = host.getCanonicalFileName(fileName); if (!options.allowNonTsExtensions && !forEach(flatten(supportedExtensionsWithJsonIfResolveJsonModule), extension => fileExtensionIs(canonicalFileName, extension))) { @@ -3483,7 +3498,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg fileName, fileName => findSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason, packageId), // TODO: GH#18217 (diagnostic, ...args) => addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, diagnostic, args), - reason + reason, ); } @@ -3545,11 +3560,13 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // but the resolved real path may be the .d.ts from project reference // Note:: Currently we try the real path only if the // file is from node_modules to avoid having to run real path on all file paths - if (!source && + if ( + !source && host.realpath && options.preserveSymlinks && isDeclarationFileName(fileName) && - stringContains(fileName, nodeModulesPathPart)) { + stringContains(fileName, nodeModulesPathPart) + ) { const realPath = toPath(host.realpath(fileName)); if (realPath !== path) source = getSourceOfProjectReferenceRedirect(realPath); } @@ -3689,7 +3706,6 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg processLibReferenceDirectives(file); } - // always process imported modules to record module name resolutions processImportedModules(file); @@ -3733,7 +3749,6 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg return getResolvedProjectReferenceToRedirect(fileName); } - function getProjectReferenceOutputName(referencedProject: ResolvedProjectReference, fileName: string) { const out = outFile(referencedProject.commandLine.options); return out ? @@ -3750,8 +3765,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg forEachResolvedProjectReference(referencedProject => { // not input file from the referenced project, ignore if (toPath(options.configFilePath!) !== referencedProject.sourceFile.path) { - referencedProject.commandLine.fileNames.forEach(f => - mapFromFileToProjectReferenceRedirects!.set(toPath(f), referencedProject.sourceFile.path)); + referencedProject.commandLine.fileNames.forEach(f => mapFromFileToProjectReferenceRedirects!.set(toPath(f), referencedProject.sourceFile.path)); } }); } @@ -3761,7 +3775,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg } function forEachResolvedProjectReference( - cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined + cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined, ): T | undefined { return ts_forEachResolvedProjectReference(resolvedProjectReferences, cb); } @@ -3810,7 +3824,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, - { kind: FileIncludeKind.ReferenceFile, file: file.path, index, } + { kind: FileIncludeKind.ReferenceFile, file: file.path, index }, ); }); } @@ -3834,11 +3848,11 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg (fileProcessingDiagnostics ??= []).push({ kind: FilePreprocessingDiagnosticsKind.ResolutionDiagnostics, diagnostics: [ - createDiagnosticForRange(file, ref, Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext) - ] + createDiagnosticForRange(file, ref, Diagnostics.resolution_mode_assertions_are_only_supported_when_moduleResolution_is_node16_or_nodenext), + ], }); } - processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: FileIncludeKind.TypeReferenceDirective, file: file.path, index, }); + processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: FileIncludeKind.TypeReferenceDirective, file: file.path, index }); } } @@ -3846,7 +3860,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg typeReferenceDirective: string, mode: ResolutionMode, resolution: ResolvedTypeReferenceDirectiveWithFailedLookupLocations, - reason: FileIncludeReason + reason: FileIncludeReason, ): void { tracing?.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolution.resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined }); processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason); @@ -3857,7 +3871,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg typeReferenceDirective: string, mode: ResolutionMode, resolution: ResolvedTypeReferenceDirectiveWithFailedLookupLocations, - reason: FileIncludeReason + reason: FileIncludeReason, ): void { addResolutionDiagnostics(resolution); // If we already found this library as a primary reference - nothing to do @@ -3887,7 +3901,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg existingFile, reason, Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, - [typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName!, previousResolution.resolvedFileName!] + [typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName!, previousResolution.resolvedFileName!], ); } } @@ -3929,16 +3943,17 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg if (oldResolution.resolution && isTraceEnabled(options, host)) { const libraryName = getLibraryNameFromLibFileName(libFileName); const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); - trace(host, + trace( + host, oldResolution.resolution.resolvedModule ? - oldResolution.resolution.resolvedModule.packageId ? + oldResolution.resolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, libraryName, getNormalizedAbsolutePath(resolveFrom, currentDirectory), oldResolution.resolution.resolvedModule?.resolvedFileName, - oldResolution.resolution.resolvedModule?.packageId && packageIdToString(oldResolution.resolution.resolvedModule.packageId) + oldResolution.resolution.resolvedModule?.packageId && packageIdToString(oldResolution.resolution.resolvedModule.packageId), ); } (resolvedLibProcessing ??= new Map()).set(libFileName, oldResolution); @@ -3958,7 +3973,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg resolution, actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : - combinePaths(defaultLibraryPath, libFileName) + combinePaths(defaultLibraryPath, libFileName), }; (resolvedLibProcessing ??= new Map()).set(libFileName, result); return result; @@ -3969,7 +3984,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg const { libName, libFileName } = getLibFileNameFromLibReference(libReference); if (libFileName) { // we ignore any 'no-default-lib' reference set on this file. - processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true, { kind: FileIncludeKind.LibReferenceDirective, file: file.path, index, }); + processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true, { kind: FileIncludeKind.LibReferenceDirective, file: file.path, index }); } else { const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts"); @@ -3978,7 +3993,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg const args = suggestion ? [libName, suggestion] : [libName]; (fileProcessingDiagnostics ||= []).push({ kind: FilePreprocessingDiagnosticsKind.FilePreprocessingReferencedDiagnostic, - reason: { kind: FileIncludeKind.LibReferenceDirective, file: file.path, index, }, + reason: { kind: FileIncludeKind.LibReferenceDirective, file: file.path, index }, diagnostic, args, }); @@ -4042,7 +4057,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, - { kind: FileIncludeKind.Import, file: file.path, index, }, + { kind: FileIncludeKind.Import, file: file.path, index }, resolution.packageId, ); } @@ -4068,7 +4083,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg addProgramDiagnosticExplainingFile( sourceFile, Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, - [sourceFile.fileName, rootDirectory] + [sourceFile.fileName, rootDirectory], ); allFilesBelongToPath = false; } @@ -4186,7 +4201,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg addProgramDiagnosticExplainingFile( file, Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, - [file.fileName, options.configFilePath || ""] + [file.fileName, options.configFilePath || ""], ); } } @@ -4307,11 +4322,12 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // there has to be common source directory if user specified --outdir || --rootDir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted - if (options.outDir || // there is --outDir specified + if ( + options.outDir || // there is --outDir specified options.rootDir || // there is --rootDir specified options.sourceRoot || // there is --sourceRoot specified - options.mapRoot) { // there is --mapRoot specified - + options.mapRoot // there is --mapRoot specified + ) { // Precalculate and cache the common source directory const dir = getCommonSourceDirectory(); @@ -4339,8 +4355,10 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg } } - if (options.emitDecoratorMetadata && - !options.experimentalDecorators) { + if ( + options.emitDecoratorMetadata && + !options.experimentalDecorators + ) { createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); } @@ -4436,12 +4454,11 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg createOptionValueDiagnostic("module", Diagnostics.Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1, moduleResolutionName, moduleResolutionName); } - // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { const emitHost = getEmitHost(); const emitFilesSeen = new Set(); - forEachEmittedFile(emitHost, (emitFileNames) => { + forEachEmittedFile(emitHost, emitFileNames => { if (!options.emitDeclarationOnly) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); } @@ -4621,7 +4638,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg file: file && file.path, fileProcessingReason, diagnostic, - args + args, }); } @@ -4679,13 +4696,10 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg case FileIncludeKind.SourceFromProjectReference: case FileIncludeKind.OutputFromProjectReference: const referencedResolvedRef = Debug.checkDefined(resolvedProjectReferences?.[reason.index]); - const referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, parent, index) => - resolvedRef === referencedResolvedRef ? { sourceFile: parent?.sourceFile || options.configFile!, index } : undefined - ); + const referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, parent, index) => resolvedRef === referencedResolvedRef ? { sourceFile: parent?.sourceFile || options.configFile!, index } : undefined); if (!referenceInfo) return undefined; const { sourceFile, index } = referenceInfo; - const referencesSyntax = forEachTsConfigPropArray(sourceFile as TsConfigSourceFile, "references", - property => isArrayLiteralExpression(property.initializer) ? property.initializer : undefined); + const referencesSyntax = forEachTsConfigPropArray(sourceFile as TsConfigSourceFile, "references", property => isArrayLiteralExpression(property.initializer) ? property.initializer : undefined); return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile( sourceFile, @@ -4778,10 +4792,17 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg function createDiagnosticForOptionPaths(onKey: boolean, key: string, message: DiagnosticMessage, ...args: DiagnosticArguments) { let needCompilerDiagnostic = true; forEachOptionPathsSyntax(pathProp => { - if (isObjectLiteralExpression(pathProp.initializer) && + if ( + isObjectLiteralExpression(pathProp.initializer) && createOptionDiagnosticInObjectLiteralSyntax( - pathProp.initializer, onKey, key, /*key2*/ undefined, - message, ...args)) { + pathProp.initializer, + onKey, + key, + /*key2*/ undefined, + message, + ...args, + ) + ) { needCompilerDiagnostic = false; } }); @@ -4817,8 +4838,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg } function createDiagnosticForReference(sourceFile: JsonSourceFile | undefined, index: number, message: DiagnosticMessage, ...args: DiagnosticArguments) { - const referencesSyntax = forEachTsConfigPropArray(sourceFile || options.configFile, "references", - property => isArrayLiteralExpression(property.initializer) ? property.initializer : undefined); + const referencesSyntax = forEachTsConfigPropArray(sourceFile || options.configFile, "references", property => isArrayLiteralExpression(property.initializer) ? property.initializer : undefined); if (referencesSyntax && referencesSyntax.elements.length > index) { programDiagnostics.add(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile!, referencesSyntax.elements[index], message, ...args)); } @@ -4850,7 +4870,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg _compilerOptionsObjectLiteralSyntax = forEachPropertyAssignment( getTsConfigObjectLiteralExpression(options.configFile), "compilerOptions", - prop => isObjectLiteralExpression(prop.initializer) ? prop.initializer : undefined + prop => isObjectLiteralExpression(prop.initializer) ? prop.initializer : undefined, ) || false; } return _compilerOptionsObjectLiteralSyntax || undefined; @@ -5057,11 +5077,12 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host: HostForUseSource const dirPathWithTrailingDirectorySeparator = `${dirPath}${directorySeparator}`; return forEachKey( setOfDeclarationDirectories!, - declDirPath => dirPath === declDirPath || + declDirPath => + dirPath === declDirPath || // Any parent directory of declaration dir startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) || // Any directory inside declaration dir - startsWith(dirPath, `${declDirPath}/`) + startsWith(dirPath, `${declDirPath}/`), ); } @@ -5076,8 +5097,10 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host: HostForUseSource const real = normalizePath(originalRealpath.call(host.compilerHost, directory)); let realPath: Path; - if (real === directory || - (realPath = ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) { + if ( + real === directory || + (realPath = ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath + ) { // not symlinked symlinkCache.setSymlinkedDirectory(directoryPath, false); return; @@ -5085,7 +5108,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host: HostForUseSource symlinkCache.setSymlinkedDirectory(directory, { real: ensureTrailingDirectorySeparator(real), - realPath + realPath, }); } @@ -5115,11 +5138,11 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host: HostForUseSource const absolutePath = getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory()); symlinkCache.setSymlinkedFile( fileOrDirectoryPath, - `${symlinkedDirectory.real}${absolutePath.replace(new RegExp(directoryPath, "i"), "")}` + `${symlinkedDirectory.real}${absolutePath.replace(new RegExp(directoryPath, "i"), "")}`, ); } return result; - } + }, ) || false; } } @@ -5132,7 +5155,7 @@ export function handleNoEmitOptions( program: Program | T, sourceFile: SourceFile | undefined, writeFile: WriteFileCallback | undefined, - cancellationToken: CancellationToken | undefined + cancellationToken: CancellationToken | undefined, ): EmitResult | undefined { const options = program.getCompilerOptions(); if (options.noEmit) { @@ -5151,7 +5174,7 @@ export function handleNoEmitOptions( ...program.getOptionsDiagnostics(cancellationToken), ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), ...program.getGlobalDiagnostics(cancellationToken), - ...program.getSemanticDiagnostics(sourceFile, cancellationToken) + ...program.getSemanticDiagnostics(sourceFile, cancellationToken), ]; if (diagnostics.length === 0 && getEmitDeclarations(program.getCompilerOptions())) { @@ -5175,7 +5198,7 @@ export function filterSemanticDiagnostics(diagnostic: readonly Diagnostic[], opt /** @internal */ export function parseConfigHostFromCompilerHostLike( - host: (CompilerHost | ProgramHost) & { onUnRecoverableConfigFileDiagnostic?: DiagnosticReporter }, + host: (CompilerHost | ProgramHost) & { onUnRecoverableConfigFileDiagnostic?: DiagnosticReporter; }, directoryStructureHost: DirectoryStructureHost = host, ): ParseConfigFileHost { return { @@ -5191,7 +5214,7 @@ export function parseConfigHostFromCompilerHostLike( useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined, - trace: host.trace ? (s) => host.trace!(s) : undefined, + trace: host.trace ? s => host.trace!(s) : undefined, }; } @@ -5234,7 +5257,7 @@ export function resolveProjectReferencePath(ref: ProjectReference): ResolvedConf * * @internal */ -export function getResolutionDiagnostic(options: CompilerOptions, { extension }: ResolvedModuleFull, { isDeclarationFile }: { isDeclarationFile: SourceFile["isDeclarationFile"] }): DiagnosticMessage | undefined { +export function getResolutionDiagnostic(options: CompilerOptions, { extension }: ResolvedModuleFull, { isDeclarationFile }: { isDeclarationFile: SourceFile["isDeclarationFile"]; }): DiagnosticMessage | undefined { switch (extension) { case Extension.Ts: case Extension.Dts: diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 7d6ac150c05e8..fccc476dbfb60 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -107,7 +107,7 @@ export interface ResolutionCache { redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile | undefined, - reusedNames: readonly T[] | undefined + reusedNames: readonly T[] | undefined, ): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[]; resolveLibrary( libraryName: string, @@ -132,7 +132,6 @@ export interface ResolutionCache { hasChangedAutomaticTypeDirectiveNames(): boolean; isFileWithInvalidatedNonRelativeUnresolvedImports(path: Path): boolean; - startCachingPerDirectoryResolution(): void; finishCachingPerDirectoryResolution(newProgram: Program | undefined, oldProgram: Program | undefined): void; @@ -230,17 +229,21 @@ function perceivedOsRootLengthForWatching(pathComponents: Readonly, length: number, - nonRecursive?: boolean + nonRecursive?: boolean, ): DirectoryOfFailedLookupWatch { return { dir: getPathFromPathComponents(dirComponents, length), @@ -410,8 +413,7 @@ export function getRootPathSplitLength(rootPath: Path) { return rootPath.split(directorySeparator).length - (hasTrailingDirectorySeparator(rootPath) ? 1 : 0); } -type GetResolutionWithResolvedFileName = - (resolution: T) => R | undefined; +type GetResolutionWithResolvedFileName = (resolution: T) => R | undefined; /** @internal */ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string, logChangesWhenResolvingModule: boolean): ResolutionCache { @@ -569,11 +571,13 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD const collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; return { - hasInvalidatedResolutions: path => customHasInvalidatedResolutions(path) || + hasInvalidatedResolutions: path => + customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!collected?.has(path) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), - hasInvalidatedLibResolutions: libFileName => customHasInvalidatedLibResolutions(libFileName) || + hasInvalidatedLibResolutions: libFileName => + customHasInvalidatedLibResolutions(libFileName) || !!resolvedLibraries?.get(libFileName)?.isInvalidated, }; } @@ -688,13 +692,14 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD ): ResolutionLoader { return { nameAndMode: moduleResolutionNameAndModeGetter, - resolve: (moduleName, resoluionMode) => resolveModuleName( - moduleName, - containingFile, - options, - redirectedReference, - resoluionMode, - ), + resolve: (moduleName, resoluionMode) => + resolveModuleName( + moduleName, + containingFile, + options, + redirectedReference, + resoluionMode, + ), }; } @@ -713,10 +718,18 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD deferWatchingNonRelativeResolution: boolean; } function resolveNamesWithLocalCache({ - entries, containingFile, containingSourceFile, redirectedReference, options, - perFileCache, reusedNames, - loader, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution, - shouldRetryResolution, logChanges, + entries, + containingFile, + containingSourceFile, + redirectedReference, + options, + perFileCache, + reusedNames, + loader, + getResolutionWithResolvedFileName, + deferWatchingNonRelativeResolution, + shouldRetryResolution, + logChanges, }: ResolveNamesWithLocalCacheInput): readonly T[] { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = perFileCache.get(path) || perFileCache.set(path, createModeAwareCache()).get(path)!; @@ -736,10 +749,12 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD const mode = loader.nameAndMode.getMode(entry, containingSourceFile); let resolution = resolutionsInFile.get(name, mode); // Resolution is valid if it is present and not invalidated - if (!seenNamesInFile.has(name, mode) && + if ( + !seenNamesInFile.has(name, mode) && (allModuleAndTypeResolutionsAreInvalidated || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution)))) { + (hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) + ) { const existingResolution = resolution; resolution = loader.resolve(name, mode); if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { @@ -770,14 +785,14 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved : resolved?.resolvedFileName ? - resolved.packageId ? - Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : - Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : - Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved, + resolved.packageId ? + Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : + Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : + Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_not_resolved, name, containingFile, resolved?.resolvedFileName, - resolved?.packageId && packageIdToString(resolved.packageId) + resolved?.packageId && packageIdToString(resolved.packageId), ); } } @@ -785,11 +800,13 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD seenNamesInFile.set(name, mode, true); resolvedModules.push(resolution); } - reusedNames?.forEach(entry => seenNamesInFile.set( - loader.nameAndMode.getName(entry), - loader.nameAndMode.getMode(entry, containingSourceFile), - true, - )); + reusedNames?.forEach(entry => + seenNamesInFile.set( + loader.nameAndMode.getName(entry), + loader.nameAndMode.getMode(entry, containingSourceFile), + true, + ) + ); if (resolutionsInFile.size() !== seenNamesInFile.size()) { // Stop watching and remove the unused name resolutionsInFile.forEach((resolution, name, mode) => { @@ -826,8 +843,8 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile | undefined, - reusedNames: readonly T[] | undefined - ): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[]{ + reusedNames: readonly T[] | undefined, + ): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[] { return resolveNamesWithLocalCache({ entries: typeDirectiveReferences, containingFile, @@ -841,7 +858,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD redirectedReference, options, resolutionHost.getCompilerHost?.() || resolutionHost, - typeReferenceDirectiveResolutionCache + typeReferenceDirectiveResolutionCache, ), getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, shouldRetryResolution: resolution => resolution.resolvedTypeReferenceDirective === undefined, @@ -908,7 +925,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD libraryName, resolveFrom, resolved?.resolvedFileName, - resolved?.packageId && packageIdToString(resolved.packageId) + resolved?.packageId && packageIdToString(resolved.packageId), ); } } @@ -1053,7 +1070,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD actualWatcher.close(); // Ensure when watching symlinked package.json, we can close the actual file watcher only once actualWatcher = noopFileWatcher; - } + }, } : actualWatcher, resolutions: forResolution ? 1 : 0, files: forResolution ? 0 : 1, @@ -1218,9 +1235,11 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD removeResolutionsOfFile(filePath); // Resolution is invalidated if the resulting file name is same as the deleted file path const prevHasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - if (invalidateResolutions(resolvedFileToResolution.get(filePath), returnTrue) && + if ( + invalidateResolutions(resolvedFileToResolution.get(filePath), returnTrue) && hasChangedAutomaticTypeDirectiveNames && - !prevHasChangedAutomaticTypeDirectiveNames) { + !prevHasChangedAutomaticTypeDirectiveNames + ) { resolutionHost.onChangedAutomaticTypeDirectiveNames(); } } @@ -1250,8 +1269,10 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path const dirOfFileOrDirectory = getDirectoryPath(fileOrDirectoryPath); - if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || - isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + if ( + isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory) + ) { // Invalidate any resolution from this directory (failedLookupChecks ||= new Set()).add(fileOrDirectoryPath); (startsWithPathChecks ||= new Set()).add(fileOrDirectoryPath); @@ -1333,8 +1354,9 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD function isInvalidatedFailedLookup(locationPath: Path) { return failedLookupChecks?.has(locationPath) || firstDefinedIterator(startsWithPathChecks?.keys() || [], fileOrDirectoryPath => startsWith(locationPath, fileOrDirectoryPath) ? true : undefined) || - firstDefinedIterator(isInDirectoryChecks?.keys() || [], dirPath => locationPath.length > dirPath.length && - startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : undefined); + firstDefinedIterator(isInDirectoryChecks?.keys() || [], dirPath => + locationPath.length > dirPath.length && + startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : undefined); } function canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution: ResolutionWithFailedLookupLocations) { @@ -1369,7 +1391,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD rootPath, rootPathComponents, getCurrentDirectory, - dirPath => directoryWatchesOfFailedLookups.has(dirPath) + dirPath => directoryWatchesOfFailedLookups.has(dirPath), ); if (dirPath) { scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath); @@ -1400,8 +1422,8 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD arrayToMap(typeRoots, tr => resolutionHost.toPath(tr)), { createNewValue: createTypeRootsWatch, - onDeleteValue: closeFileWatcher - } + onDeleteValue: closeFileWatcher, + }, ); } else { @@ -1423,4 +1445,4 @@ function resolutionIsSymlink(resolution: ResolutionWithFailedLookupLocations) { (resolution as ResolvedModuleWithFailedLookupLocations).resolvedModule?.originalPath || (resolution as ResolvedTypeReferenceDirectiveWithFailedLookupLocations).resolvedTypeReferenceDirective?.originalPath ); -} \ No newline at end of file +} diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index ccba86326b1cf..76eba96386352 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -292,8 +292,10 @@ const textToToken = new Map(Object.entries({ Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt */ -const unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; -const unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; +// dprint-ignore +const unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500 ]; +// dprint-ignore +const unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500 ]; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers @@ -317,8 +319,10 @@ const unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 2 Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt */ -const unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; -const unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; +// dprint-ignore +const unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500 ]; +// dprint-ignore +const unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500 ]; /** * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1 @@ -326,7 +330,9 @@ const unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 2 * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start */ +// dprint-ignore const unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; +// dprint-ignore const unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; /** @@ -373,14 +379,14 @@ function lookupInUnicodeMap(code: number, map: readonly number[]): boolean { return languageVersion! >= ScriptTarget.ES2015 ? lookupInUnicodeMap(code, unicodeESNextIdentifierStart) : languageVersion === ScriptTarget.ES5 ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) : - lookupInUnicodeMap(code, unicodeES3IdentifierStart); + lookupInUnicodeMap(code, unicodeES3IdentifierStart); } function isUnicodeIdentifierPart(code: number, languageVersion: ScriptTarget | undefined) { return languageVersion! >= ScriptTarget.ES2015 ? lookupInUnicodeMap(code, unicodeESNextIdentifierPart) : languageVersion === ScriptTarget.ES5 ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) : - lookupInUnicodeMap(code, unicodeES3IdentifierPart); + lookupInUnicodeMap(code, unicodeES3IdentifierPart); } function makeReverseMap(source: Map): string[] { @@ -482,7 +488,7 @@ export function computeLineAndCharacterOfPosition(lineStarts: readonly number[], const lineNumber = computeLineOfPosition(lineStarts, position); return { line: lineNumber, - character: position - lineStarts[lineNumber] + character: position - lineStarts[lineNumber], }; } @@ -809,7 +815,8 @@ function iterateCommentRanges(reduce: boolean, text: string, pos: number, pos = shebang.length; } } - scan: while (pos >= 0 && pos < text.length) { + scan: + while (pos >= 0 && pos < text.length) { const ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: @@ -971,14 +978,7 @@ export function isIdentifierText(name: string, languageVersion: ScriptTarget | u } // 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 { - +export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant = LanguageVariant.Standard, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner { // Why var? It avoids TDZ checks in the runtime which can be costly. // See: https://github.com/microsoft/TypeScript/issues/52924 /* eslint-disable no-var */ @@ -987,7 +987,6 @@ export function createScanner(languageVersion: ScriptTarget, // Current position (end position of text of current token) var pos: number; - // end of text var end: number; @@ -1312,9 +1311,10 @@ export function createScanner(languageVersion: ScriptTarget, if (ch >= CharacterCodes.A && ch <= CharacterCodes.F) { ch += CharacterCodes.a - CharacterCodes.A; // standardize hex literals to lowercase } - else if (!((ch >= CharacterCodes._0 && ch <= CharacterCodes._9) || - (ch >= CharacterCodes.a && ch <= CharacterCodes.f) - )) { + else if ( + !((ch >= CharacterCodes._0 && ch <= CharacterCodes._9) || + (ch >= CharacterCodes.a && ch <= CharacterCodes.f)) + ) { break; } valueChars.push(ch); @@ -1518,7 +1518,7 @@ export function createScanner(languageVersion: ScriptTarget, case CharacterCodes.singleQuote: return "'"; case CharacterCodes.doubleQuote: - return "\""; + return '"'; case CharacterCodes.u: if (pos < end && text.charCodeAt(pos) === CharacterCodes.openBrace) { // '\u{DDDDDDDD}' @@ -1649,7 +1649,6 @@ export function createScanner(languageVersion: ScriptTarget, return -1; } - function peekExtendedUnicodeEscape(): number { if (codePointAt(text, pos + 1) === CharacterCodes.u && codePointAt(text, pos + 2) === CharacterCodes.openBrace) { const start = pos; @@ -1767,8 +1766,8 @@ export function createScanner(languageVersion: ScriptTarget, const numericValue = tokenFlags & TokenFlags.BinarySpecifier ? parseInt(tokenValue.slice(2), 2) // skip "0b" : tokenFlags & TokenFlags.OctalSpecifier - ? parseInt(tokenValue.slice(2), 8) // skip "0o" - : +tokenValue; + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; tokenValue = "" + numericValue; return SyntaxKind.NumericLiteral; } @@ -2092,9 +2091,11 @@ export function createScanner(languageVersion: ScriptTarget, if (text.charCodeAt(pos + 1) === CharacterCodes.equals) { return pos += 2, token = SyntaxKind.LessThanEqualsToken; } - if (languageVariant === LanguageVariant.JSX && + if ( + languageVariant === LanguageVariant.JSX && text.charCodeAt(pos + 1) === CharacterCodes.slash && - text.charCodeAt(pos + 2) !== CharacterCodes.asterisk) { + text.charCodeAt(pos + 2) !== CharacterCodes.asterisk + ) { return pos += 2, token = SyntaxKind.LessThanSlashToken; } pos++; @@ -2586,16 +2587,16 @@ export function createScanner(languageVersion: ScriptTarget, if (pos >= end) { return token = SyntaxKind.EndOfFileToken; } - for (let ch = text.charCodeAt(pos); - pos < end && (!isLineBreak(ch) && ch !== CharacterCodes.backtick); - ch = codePointAt(text, ++pos)) { + for (let ch = text.charCodeAt(pos); pos < end && (!isLineBreak(ch) && ch !== CharacterCodes.backtick); ch = codePointAt(text, ++pos)) { if (!inBackticks) { if (ch === CharacterCodes.openBrace) { break; } - else if (ch === CharacterCodes.at + else if ( + ch === CharacterCodes.at && pos - 1 >= 0 && isWhiteSpaceSingleLine(text.charCodeAt(pos - 1)) - && !(pos + 1 < end && isWhiteSpaceLike(text.charCodeAt(pos + 1)))) { + && !(pos + 1 < end && isWhiteSpaceLike(text.charCodeAt(pos + 1))) + ) { // @ doesn't start a new tag inside ``, and elsewhere, only after whitespace and before non-whitespace break; } diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts index d17e8c55c1cd6..1c8af4fccab61 100644 --- a/src/compiler/semver.ts +++ b/src/compiler/semver.ts @@ -109,20 +109,24 @@ export class Version { increment(field: "major" | "minor" | "patch") { switch (field) { - case "major": return new Version(this.major + 1, 0, 0); - case "minor": return new Version(this.major, this.minor + 1, 0); - case "patch": return new Version(this.major, this.minor, this.patch + 1); - default: return Debug.assertNever(field); + case "major": + return new Version(this.major + 1, 0, 0); + case "minor": + return new Version(this.major, this.minor + 1, 0); + case "patch": + return new Version(this.major, this.minor, this.patch + 1); + default: + return Debug.assertNever(field); } } - with(fields: { major?: number, minor?: number, patch?: number, prerelease?: string | readonly string[], build?: string | readonly string[] }) { + with(fields: { major?: number; minor?: number; patch?: number; prerelease?: string | readonly string[]; build?: string | readonly string[]; }) { const { major = this.major, minor = this.minor, patch = this.patch, prerelease = this.prerelease, - build = this.build + build = this.build, } = fields; return new Version(major, minor, patch, prerelease, build); } @@ -147,7 +151,7 @@ function tryParseComponents(text: string) { minor: parseInt(minor, 10), patch: parseInt(patch, 10), prerelease, - build + build, }; } @@ -300,7 +304,8 @@ function parsePartial(text: string) { isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, - build); + build, + ); return { version, major, minor, patch }; } @@ -319,8 +324,9 @@ function parseHyphen(left: string, right: string, comparators: Comparator[]) { if (!isWildcard(rightResult.major)) { comparators.push( isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : - isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : - createComparator("<=", rightResult.version)); + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version), + ); } return true; @@ -335,29 +341,39 @@ function parseComparator(operator: string, text: string, comparators: Comparator switch (operator) { case "~": comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment( - isWildcard(minor) ? "major" : - "minor"))); + comparators.push(createComparator( + "<", + version.increment( + isWildcard(minor) ? "major" : + "minor", + ), + )); break; case "^": comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment( - version.major > 0 || isWildcard(minor) ? "major" : - version.minor > 0 || isWildcard(patch) ? "minor" : - "patch"))); + comparators.push(createComparator( + "<", + version.increment( + version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch", + ), + )); break; case "<": case ">=": comparators.push( isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version.with({ prerelease: "0" })) : - createComparator(operator, version)); + createComparator(operator, version), + ); break; case "<=": case ">": comparators.push( isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major").with({ prerelease: "0" })) : - isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : - createComparator(operator, version)); + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : + createComparator(operator, version), + ); break; case "=": case undefined: @@ -408,12 +424,18 @@ function testAlternative(version: Version, comparators: readonly Comparator[]) { function testComparator(version: Version, operator: Comparator["operator"], operand: Version) { const cmp = version.compareTo(operand); switch (operator) { - case "<": return cmp < 0; - case "<=": return cmp <= 0; - case ">": return cmp > 0; - case ">=": return cmp >= 0; - case "=": return cmp === 0; - default: return Debug.assertNever(operator); + case "<": + return cmp < 0; + case "<=": + return cmp <= 0; + case ">": + return cmp > 0; + case ">=": + return cmp >= 0; + case "=": + return cmp === 0; + default: + return Debug.assertNever(operator); } } diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index 78ebf13ba0878..fedc66d6e77c9 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -81,16 +81,12 @@ export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoo addMapping, appendSourceMap, toJSON, - toString: () => JSON.stringify(toJSON()) + toString: () => JSON.stringify(toJSON()), }; function addSource(fileName: string) { enter(); - const source = getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, - fileName, - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); + const source = getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); let sourceIndex = sourceToSourceIndexMap.get(source); if (sourceIndex === undefined) { @@ -153,8 +149,10 @@ export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoo Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative"); enter(); // If this location wasn't recorded or the location in source is going backwards, record the mapping - if (isNewGeneratedPosition(generatedLine, generatedCharacter) || - isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) { + if ( + isNewGeneratedPosition(generatedLine, generatedCharacter) || + isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) + ) { commitPendingMapping(); pendingGeneratedLine = generatedLine; pendingGeneratedCharacter = generatedCharacter; @@ -185,15 +183,21 @@ export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoo let nameIndexToNewNameIndexMap: number[] | undefined; const mappingIterator = decodeMappings(map.mappings); for (const raw of mappingIterator) { - if (end && ( - raw.generatedLine > end.line || - (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) { + if ( + end && ( + raw.generatedLine > end.line || + (raw.generatedLine === end.line && raw.generatedCharacter > end.character) + ) + ) { break; } - if (start && ( - raw.generatedLine < start.line || - (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) { + if ( + start && ( + raw.generatedLine < start.line || + (start.line === raw.generatedLine && raw.generatedCharacter < start.character) + ) + ) { continue; } // Then reencode all the updated mappings into the overall map @@ -350,7 +354,8 @@ export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoo currentDigit = currentDigit | 32; } appendMappingCharCode(base64FormatEncode(currentDigit)); - } while (inValue > 0); + } + while (inValue > 0); } } @@ -373,7 +378,7 @@ export interface LineInfo { export function getLineInfo(text: string, lineStarts: readonly number[]): LineInfo { return { getLineCount: () => lineStarts.length, - getLineText: line => text.substring(lineStarts[line], lineStarts[line + 1]) + getLineText: line => text.substring(lineStarts[line], lineStarts[line + 1]), }; } @@ -468,9 +473,15 @@ export function decodeMappings(mappings: string): MappingsDecoder { // TODO(jakebailey): can we implement this without writing next ourselves? return { - get pos() { return pos; }, - get error() { return error; }, - get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); }, + get pos() { + return pos; + }, + get error() { + return error; + }, + get state() { + return captureMapping(/*hasSource*/ true, /*hasName*/ true); + }, next() { while (!done && pos < mappings.length) { const ch = mappings.charCodeAt(pos); @@ -529,7 +540,7 @@ export function decodeMappings(mappings: string): MappingsDecoder { }, [Symbol.iterator]() { return this; - } + }, }; function captureMapping(hasSource: true, hasName: true): Required; @@ -541,11 +552,11 @@ export function decodeMappings(mappings: string): MappingsDecoder { sourceIndex: hasSource ? sourceIndex : undefined, sourceLine: hasSource ? sourceLine : undefined, sourceCharacter: hasSource ? sourceCharacter : undefined, - nameIndex: hasName ? nameIndex : undefined + nameIndex: hasName ? nameIndex : undefined, }; } - function stopIterating(): { value: never, done: true } { + function stopIterating(): { value: never; done: true; } { done = true; return { value: undefined!, done: true }; } @@ -610,11 +621,11 @@ export function decodeMappings(mappings: string): MappingsDecoder { export function sameMapping(left: T, right: T) { return left === right || left.generatedLine === right.generatedLine - && left.generatedCharacter === right.generatedCharacter - && left.sourceIndex === right.sourceIndex - && left.sourceLine === right.sourceLine - && left.sourceCharacter === right.sourceCharacter - && left.nameIndex === right.nameIndex; + && left.generatedCharacter === right.generatedCharacter + && left.sourceIndex === right.sourceIndex + && left.sourceLine === right.sourceLine + && left.sourceCharacter === right.sourceCharacter + && left.nameIndex === right.nameIndex; } /** @internal */ @@ -700,7 +711,7 @@ export function createDocumentPositionMapper(host: DocumentPositionMapperHost, m return { getSourcePosition, - getGeneratedPosition + getGeneratedPosition, }; function processMapping(mapping: Mapping): MappedPosition { @@ -721,7 +732,7 @@ export function createDocumentPositionMapper(host: DocumentPositionMapperHost, m source, sourceIndex: mapping.sourceIndex, sourcePosition, - nameIndex: mapping.nameIndex + nameIndex: mapping.nameIndex, }; } @@ -810,5 +821,5 @@ export function createDocumentPositionMapper(host: DocumentPositionMapperHost, m /** @internal */ export const identitySourceMapConsumer: DocumentPositionMapper = { getSourcePosition: identity, - getGeneratedPosition: identity + getGeneratedPosition: identity, }; diff --git a/src/compiler/symbolWalker.ts b/src/compiler/symbolWalker.ts index 09853623cc5db..3adeee07406e4 100644 --- a/src/compiler/symbolWalker.ts +++ b/src/compiler/symbolWalker.ts @@ -37,8 +37,8 @@ export function createGetSymbolWalker( getResolvedSymbol: (node: Identifier) => Symbol, getConstraintOfTypeParameter: (typeParameter: TypeParameter) => Type | undefined, getFirstIdentifier: (node: EntityNameOrEntityNameExpression) => Identifier, - getTypeArguments: (type: TypeReference) => readonly Type[]) { - + getTypeArguments: (type: TypeReference) => readonly Type[], +) { return getSymbolWalker; function getSymbolWalker(accept: (symbol: Symbol) => boolean = () => true): SymbolWalker { @@ -214,4 +214,3 @@ export function createGetSymbolWalker( } } } - diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index db12d3a6dd96e..14e6f04b77afa 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -81,7 +81,7 @@ export function setStackTraceLimit() { export enum FileWatcherEventKind { Created, Changed, - Deleted + Deleted, } export type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, modifiedTime?: Date) => void; @@ -96,7 +96,7 @@ interface WatchedFile { export enum PollingInterval { High = 2000, Medium = 500, - Low = 250 + Low = 250, } /** @internal */ @@ -122,7 +122,7 @@ function createPollingIntervalBasedLevels(levels: Levels) { return { [PollingInterval.Low]: levels.Low, [PollingInterval.Medium]: levels.Medium, - [PollingInterval.High]: levels.High + [PollingInterval.High]: levels.High, }; } @@ -186,8 +186,9 @@ interface WatchedFileWithIsClosed extends WatchedFile { function pollWatchedFileQueue( host: { getModifiedTime: NonNullable; }, queue: (T | undefined)[], - pollIndex: number, chunkSize: number, - callbackOnWatchFileStat?: (watchedFile: T, pollIndex: number, fileChanged: boolean) => void + pollIndex: number, + chunkSize: number, + callbackOnWatchFileStat?: (watchedFile: T, pollIndex: number, fileChanged: boolean) => void, ) { let definedValueCopyToIndex = pollIndex; // Max visit would be all elements of the queue @@ -263,7 +264,7 @@ function createDynamicPriorityPollingWatchFile(host: { fileName, callback, unchangedPolls: 0, - mtime: getModifiedTime(host, fileName) + mtime: getModifiedTime(host, fileName), }; watchedFiles.push(file); @@ -274,7 +275,7 @@ function createDynamicPriorityPollingWatchFile(host: { // Remove from watchedFiles unorderedRemoveItem(watchedFiles, file); // Do not update polling interval queue since that will happen as part of polling - } + }, }; } @@ -317,7 +318,7 @@ function createDynamicPriorityPollingWatchFile(host: { queue, pollIndex, chunkSize, - onWatchFileStat + onWatchFileStat, ); function onWatchFileStat(watchedFile: WatchedFileWithUnchangedPolls, pollIndex: number, fileChanged: boolean) { @@ -402,7 +403,7 @@ function createUseFsEventsOnParentDirectoryWatchFile(fsWatch: FsWatch, useCaseSe watcher.referenceCount--; } fileWatcherCallbacks.remove(filePath, callback); - } + }, }; } @@ -424,7 +425,7 @@ function createUseFsEventsOnParentDirectoryWatchFile(fsWatch: FsWatch, useCaseSe }, /*recursive*/ false, PollingInterval.Medium, - fallbackOptions + fallbackOptions, ) as DirectoryWatcher; watcher.referenceCount = 0; dirWatchers.set(dirPath, watcher); @@ -445,7 +446,7 @@ function createFixedChunkSizePollingWatchFile(host: { const file: WatchedFileWithIsClosed = { fileName, callback, - mtime: getModifiedTime(host, fileName) + mtime: getModifiedTime(host, fileName), }; watchedFiles.push(file); scheduleNextPoll(); @@ -453,7 +454,7 @@ function createFixedChunkSizePollingWatchFile(host: { close: () => { file.isClosed = true; unorderedRemoveItem(watchedFiles, file); - } + }, }; } @@ -469,7 +470,7 @@ function createFixedChunkSizePollingWatchFile(host: { } } -interface SingleFileWatcher{ +interface SingleFileWatcher { watcher: FileWatcher; callbacks: T[]; } @@ -488,11 +489,13 @@ function createSingleWatcherPerName cache.get(path)?.callbacks.slice().forEach(cb => cb(param1, param2, param3)) - ) as T), - callbacks: [callback] + watcher: createWatcher( + ( + // Cant infer types correctly so lets satisfy checker + (param1: any, param2: never, param3: any) => cache.get(path)?.callbacks.slice().forEach(cb => cb(param1, param2, param3)) + ) as T, + ), + callbacks: [callback], }); } @@ -505,7 +508,7 @@ function createSingleWatcherPerName recursive ? - createDirectoryWatcher(dirName, options, callback) : - watchDirectory(dirName, callback, recursive, options); + return (dirName, callback, recursive, options) => + recursive ? + createDirectoryWatcher(dirName, options, callback) : + watchDirectory(dirName, callback, recursive, options); /** * Create the directory watcher for the dirPath. @@ -608,22 +612,27 @@ function createDirectoryWatcherSupportingRecursive({ } else { directoryWatcher = { - watcher: watchDirectory(dirName, fileName => { - if (isIgnoredPath(fileName, options)) return; + watcher: watchDirectory( + dirName, + fileName => { + if (isIgnoredPath(fileName, options)) return; - if (options?.synchronousWatchDirectory) { - // Call the actual callback - invokeCallbacks(dirPath, fileName); + if (options?.synchronousWatchDirectory) { + // Call the actual callback + invokeCallbacks(dirPath, fileName); - // Iterate through existing children and update the watches if needed - updateChildWatches(dirName, dirPath, options); - } - else { - nonSyncUpdateChildWatches(dirName, dirPath, fileName, options); - } - }, /*recursive*/ false, options), + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath, options); + } + else { + nonSyncUpdateChildWatches(dirName, dirPath, fileName, options); + } + }, + /*recursive*/ false, + options, + ), refCount: 1, - childWatches: emptyArray + childWatches: emptyArray, }; cache.set(dirPath, directoryWatcher); updateChildWatches(dirName, dirPath, options); @@ -646,7 +655,7 @@ function createDirectoryWatcherSupportingRecursive({ cache.delete(dirPath); closeFileWatcherOf(directoryWatcher); directoryWatcher.childWatches.forEach(closeFileWatcher); - } + }, }; } @@ -778,7 +787,7 @@ function createDirectoryWatcherSupportingRecursive({ (child, childWatcher) => filePathComparer(child, childWatcher.dirName), createAndAddChildDirectoryWatcher, closeFileWatcher, - addChildDirectoryWatcher + addChildDirectoryWatcher, ); parentWatcher.childWatches = newChildWatches || emptyArray; return hasChanges; @@ -834,7 +843,7 @@ function createFileWatcherCallback(callback: FsWatchCallback): FileWatcherCallba function createFsWatchCallbackForFileWatcherCallback( fileName: string, callback: FileWatcherCallback, - getModifiedTime: NonNullable + getModifiedTime: NonNullable, ): FsWatchCallback { return (eventName, _relativeFileName, modifiedTime) => { if (eventName === "rename") { @@ -938,7 +947,7 @@ export function createSystemWatchFunctions({ let hitSystemWatcherLimit = false; return { watchFile, - watchDirectory + watchDirectory, }; function watchFile(fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, options: WatchOptions | undefined): FileWatcher { @@ -960,7 +969,7 @@ export function createSystemWatchFunctions({ createFsWatchCallbackForFileWatcherCallback(fileName, callback, getModifiedTime), /*recursive*/ false, pollingInterval, - getFallbackOptions(options) + getFallbackOptions(options), ); case WatchFileKind.UseFsEventsOnParentDirectory: if (!nonPollingWatchFile) { @@ -1010,14 +1019,14 @@ export function createSystemWatchFunctions({ function generateWatchFileOptions( watchFile: WatchFileKind, fallbackPolling: PollingWatchKind, - options: WatchOptions | undefined + options: WatchOptions | undefined, ): WatchOptions { const defaultFallbackPolling = options?.fallbackPolling; return { watchFile, fallbackPolling: defaultFallbackPolling === undefined ? fallbackPolling : - defaultFallbackPolling + defaultFallbackPolling, }; } @@ -1029,7 +1038,7 @@ export function createSystemWatchFunctions({ createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, - getFallbackOptions(options) + getFallbackOptions(options), ); } @@ -1042,7 +1051,7 @@ export function createSystemWatchFunctions({ watchDirectory: nonRecursiveWatchDirectory, realpath, setTimeout, - clearTimeout + clearTimeout, }); } return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options); @@ -1058,21 +1067,21 @@ export function createSystemWatchFunctions({ directoryName, () => callback(directoryName), PollingInterval.Medium, - /*options*/ undefined + /*options*/ undefined, ); case WatchDirectoryKind.DynamicPriorityPolling: return ensureDynamicPollingWatchFile()( directoryName, () => callback(directoryName), PollingInterval.Medium, - /*options*/ undefined + /*options*/ undefined, ); case WatchDirectoryKind.FixedChunkSizePolling: return ensureFixedChunkSizePollingWatchFile()( directoryName, () => callback(directoryName), /* pollingInterval */ undefined!, - /*options*/ undefined + /*options*/ undefined, ); case WatchDirectoryKind.UseFsEvents: return fsWatch( @@ -1081,7 +1090,7 @@ export function createSystemWatchFunctions({ createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, - getFallbackOptions(watchDirectoryOptions) + getFallbackOptions(watchDirectoryOptions), ); default: Debug.assertNever(watchDirectoryKind); @@ -1103,7 +1112,7 @@ export function createSystemWatchFunctions({ watchDirectory: WatchDirectoryKind.UseFsEvents, fallbackPolling: defaultFallbackPolling !== undefined ? defaultFallbackPolling : - undefined + undefined, }; } } @@ -1123,7 +1132,7 @@ export function createSystemWatchFunctions({ callback: FsWatchCallback, recursive: boolean, fallbackPollingInterval: PollingInterval, - fallbackOptions: WatchOptions | undefined + fallbackOptions: WatchOptions | undefined, ): FileWatcher { return createSingleWatcherPerName( recursive ? fsWatchesRecursive : fsWatches, @@ -1140,7 +1149,7 @@ export function createSystemWatchFunctions({ callback: FsWatchCallback, recursive: boolean, fallbackPollingInterval: PollingInterval, - fallbackOptions: WatchOptions | undefined + fallbackOptions: WatchOptions | undefined, ): FileWatcher { let lastDirectoryPartWithDirectorySeparator: string | undefined; let lastDirectoryPart: string | undefined; @@ -1159,7 +1168,7 @@ export function createSystemWatchFunctions({ watcher.close(); watcher = undefined; } - } + }, }; function updateWatcher(createWatcher: () => FileWatcher) { @@ -1186,7 +1195,7 @@ export function createSystemWatchFunctions({ recursive, inodeWatching ? callbackChangingToMissingFileSystemEntry : - callback + callback, ); // Watch the missing file or directory or error presentWatcher.on("error", () => { @@ -1218,10 +1227,12 @@ export function createSystemWatchFunctions({ } // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path - if (event === "rename" && + if ( + event === "rename" && (!relativeName || relativeName === lastDirectoryPart || - endsWith(relativeName, lastDirectoryPartWithDirectorySeparator!))) { + endsWith(relativeName, lastDirectoryPartWithDirectorySeparator!)) + ) { const modifiedTime = getModifiedTime(fileOrDirectory) || missingFileModifiedTime; if (originalRelativeName) callback(event, originalRelativeName, modifiedTime); callback(event, relativeName, modifiedTime); @@ -1248,7 +1259,7 @@ export function createSystemWatchFunctions({ fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, - fallbackOptions + fallbackOptions, ); } @@ -1272,7 +1283,7 @@ export function createSystemWatchFunctions({ } }, fallbackPollingInterval, - fallbackOptions + fallbackOptions, ); } } @@ -1293,7 +1304,8 @@ export function patchWriteFileEnsuringDirectory(sys: System) { !!writeBom, (path, data, writeByteOrderMark) => originalWriteFile.call(sys, path, data, writeByteOrderMark), path => sys.createDirectory(path), - path => sys.directoryExists(path)); + path => sys.directoryExists(path), + ); } export type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; @@ -1305,14 +1317,14 @@ export interface NodeBuffer extends Uint8Array { write(str: string, offset: number, encoding?: BufferEncoding): number; write(str: string, offset: number, length: number, encoding?: BufferEncoding): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: "Buffer"; data: number[] }; + toJSON(): { type: "Buffer"; data: number[]; }; equals(otherBuffer: Uint8Array): boolean; compare( otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, - sourceEnd?: number + sourceEnd?: number, ): number; copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(begin?: number, end?: number): Buffer; @@ -1375,7 +1387,7 @@ export interface NodeBuffer extends Uint8Array { } /** @internal */ -export interface Buffer extends NodeBuffer { } +export interface Buffer extends NodeBuffer {} // TODO: GH#18217 Methods on System are often used as if they are certainly defined export interface System { @@ -1513,7 +1525,7 @@ export let sys: System = (() => { write(s: string): void { process.stdout.write(s); }, - getWidthOfTerminal(){ + getWidthOfTerminal() { return process.stdout.columns; }, writeOutputIsTTY() { @@ -1593,7 +1605,7 @@ export let sys: System = (() => { process.stdout.write("\x1Bc"); }, setBlocking: () => { - const handle = (process.stdout as any)?._handle as { setBlocking?: (value: boolean) => void }; + const handle = (process.stdout as any)?._handle as { setBlocking?: (value: boolean) => void; }; if (handle && handle.setBlocking) { handle.setBlocking(true); } @@ -1609,7 +1621,7 @@ export let sys: System = (() => { catch (error) { return { module: undefined, modulePath: undefined, error }; } - } + }, }; return nodeSystem; @@ -1727,7 +1739,7 @@ export let sys: System = (() => { /** Convert all lowercase chars to uppercase, and vice-versa */ function swapCase(s: string): string { - return s.replace(/\w/g, (ch) => { + return s.replace(/\w/g, ch => { const up = ch.toUpperCase(); return ch === up ? ch.toLowerCase() : up; }); @@ -1737,7 +1749,7 @@ export let sys: System = (() => { _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged); let eventKind: FileWatcherEventKind; return { - close: () => _fs.unwatchFile(fileName, fileChanged) + close: () => _fs.unwatchFile(fileName, fileChanged), }; function fileChanged(curr: import("fs").Stats, prev: import("fs").Stats) { @@ -1777,7 +1789,7 @@ export let sys: System = (() => { fileOrDirectory, fsSupportsRecursiveFsWatch ? { persistent: true, recursive: !!recursive } : { persistent: true }, - callback + callback, ); } @@ -1906,9 +1918,12 @@ export let sys: System = (() => { return false; } switch (entryKind) { - case FileSystemEntryKind.File: return stat.isFile(); - case FileSystemEntryKind.Directory: return stat.isDirectory(); - default: return false; + case FileSystemEntryKind.File: + return stat.isFile(); + case FileSystemEntryKind.Directory: + return stat.isDirectory(); + default: + return false; } } catch (e) { @@ -2003,9 +2018,11 @@ export function setSys(s: System) { if (sys && sys.getEnvironmentVariable) { setCustomPollingValues(sys); - Debug.setAssertionLevel(/^development$/i.test(sys.getEnvironmentVariable("NODE_ENV")) - ? AssertionLevel.Normal - : AssertionLevel.None); + Debug.setAssertionLevel( + /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV")) + ? AssertionLevel.Normal + : AssertionLevel.None, + ); } if (sys && sys.debugMode) { Debug.isDebugging = true; diff --git a/src/compiler/tracing.ts b/src/compiler/tracing.ts index 4f091195827a8..42b69e0f7bce0 100644 --- a/src/compiler/tracing.ts +++ b/src/compiler/tracing.ts @@ -79,8 +79,7 @@ export namespace tracingEnabled { fs.mkdirSync(traceDir, { recursive: true }); } - const countPart = - mode === "build" ? `.${process.pid}-${++traceCount}` + const countPart = mode === "build" ? `.${process.pid}-${++traceCount}` : mode === "server" ? `.${process.pid}` : ``; const tracePath = combinePaths(traceDir, `trace${countPart}.json`); @@ -97,12 +96,12 @@ export namespace tracingEnabled { // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) const meta = { cat: "__metadata", ph: "M", ts: 1000 * timestamp(), pid: 1, tid: 1 }; - fs.writeSync(traceFd, + fs.writeSync( + traceFd, "[\n" - + [{ name: "process_name", args: { name: "tsc" }, ...meta }, - { name: "thread_name", args: { name: "Main" }, ...meta }, - { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }] - .map(v => JSON.stringify(v)).join(",\n")); + + [{ name: "process_name", args: { name: "tsc" }, ...meta }, { name: "thread_name", args: { name: "Main" }, ...meta }, { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }] + .map(v => JSON.stringify(v)).join(",\n"), + ); } /** Stops tracing for the in-progress project and dumps the type catalog. */ @@ -144,7 +143,7 @@ export namespace tracingEnabled { writeEvent("I", phase, name, args, `"s":"g"`); } - const eventStack: { phase: Phase, name: string, args?: Args, time: number, separateBeginAndEnd: boolean }[] = []; + const eventStack: { phase: Phase; name: string; args?: Args; time: number; separateBeginAndEnd: boolean; }[] = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event @@ -184,9 +183,7 @@ export namespace tracingEnabled { } } - function writeEvent(eventType: string, phase: Phase, name: string, args: Args | undefined, extras?: string, - time: number = 1000 * timestamp()) { - + function writeEvent(eventType: string, phase: Phase, name: string, args: Args | undefined, extras?: string, time: number = 1000 * timestamp()) { // In server mode, there's no easy way to dump type information, so we drop events that would require it. if (mode === "server" && phase === Phase.CheckTypes) return; diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index f8c1ee5d5eeca..3a37fe0f2d3f4 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -72,7 +72,7 @@ import { transformNodeModule, transformSystemModule, transformTypeScript, - VariableDeclaration + VariableDeclaration, } from "./_namespaces/ts"; import * as performance from "./_namespaces/ts.performance"; @@ -97,7 +97,7 @@ const enum TransformationState { Uninitialized, Initialized, Completed, - Disposed + Disposed, } const enum SyntaxKindFeatureFlags { @@ -290,13 +290,17 @@ export function transformNodes(resolver: EmitResolver | undefine enableEmitNotification, isSubstitutionEnabled, isEmitNotificationEnabled, - get onSubstituteNode() { return onSubstituteNode; }, + get onSubstituteNode() { + return onSubstituteNode; + }, set onSubstituteNode(value) { Debug.assert(state < TransformationState.Initialized, "Cannot modify transformation hooks after initialization has completed."); Debug.assert(value !== undefined, "Value must not be 'undefined'"); onSubstituteNode = value; }, - get onEmitNode() { return onEmitNode; }, + get onEmitNode() { + return onEmitNode; + }, set onEmitNode(value) { Debug.assert(state < TransformationState.Initialized, "Cannot modify transformation hooks after initialization has completed."); Debug.assert(value !== undefined, "Value must not be 'undefined'"); @@ -304,7 +308,7 @@ export function transformNodes(resolver: EmitResolver | undefine }, addDiagnostic(diag) { diagnostics.push(diag); - } + }, }; // Ensure the parse tree is clean before applying transformations @@ -346,7 +350,7 @@ export function transformNodes(resolver: EmitResolver | undefine emitNodeWithNotification, isEmitNotificationEnabled, dispose, - diagnostics + diagnostics, }; function transformRoot(node: T) { @@ -517,9 +521,11 @@ export function transformNodes(resolver: EmitResolver | undefine Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); let statements: Statement[] | undefined; - if (lexicalEnvironmentVariableDeclarations || + if ( + lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations || - lexicalEnvironmentStatements) { + lexicalEnvironmentStatements + ) { if (lexicalEnvironmentFunctionDeclarations) { statements = [...lexicalEnvironmentFunctionDeclarations]; } @@ -527,7 +533,7 @@ export function transformNodes(resolver: EmitResolver | undefine if (lexicalEnvironmentVariableDeclarations) { const statement = factory.createVariableStatement( /*modifiers*/ undefined, - factory.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations) + factory.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations), ); setEmitFlags(statement, EmitFlags.CustomPrologue); @@ -598,9 +604,9 @@ export function transformNodes(resolver: EmitResolver | undefine /*modifiers*/ undefined, factory.createVariableDeclarationList( blockScopedVariableDeclarations.map(identifier => factory.createVariableDeclaration(identifier)), - NodeFlags.Let - ) - ) + NodeFlags.Let, + ), + ), ] : undefined; blockScopeStackOffset--; blockScopedVariableDeclarations = blockScopedVariableDeclarationsStack[blockScopeStackOffset]; diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts index aa4fb43ebc954..ede44357f242d 100644 --- a/src/compiler/transformers/classFields.ts +++ b/src/compiler/transformers/classFields.ts @@ -224,7 +224,7 @@ import { visitNodes, Visitor, visitParameterList, - VisitResult + VisitResult, } from "../_namespaces/ts"; const enum ClassPropertySubstitutionFlags { @@ -358,7 +358,7 @@ export function transformClassFields(context: TransformationContext): (x: Source endLexicalEnvironment, startLexicalEnvironment, resumeLexicalEnvironment, - addBlockScopedVariable + addBlockScopedVariable, } = context; const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); @@ -378,8 +378,7 @@ export function transformClassFields(context: TransformationContext): (x: Source // We need to transform `accessor` fields when target < ESNext. // We may need to transform `accessor` fields when `useDefineForClassFields: false` - const shouldTransformAutoAccessors = - languageVersion < ScriptTarget.ESNext ? Ternary.True : + const shouldTransformAutoAccessors = languageVersion < ScriptTarget.ESNext ? Ternary.True : !useDefineForClassFields ? Ternary.Maybe : Ternary.False; @@ -391,8 +390,7 @@ export function transformClassFields(context: TransformationContext): (x: Source // the es2015 transformation handles those. const shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= ScriptTarget.ES2015; - const shouldTransformAnything = - shouldTransformInitializers || + const shouldTransformAnything = shouldTransformInitializers || shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformAutoAccessors === Ternary.True; @@ -458,8 +456,10 @@ export function transformClassFields(context: TransformationContext): (x: Source } function visitor(node: Node): VisitResult { - if (!(node.transformFlags & TransformFlags.ContainsClassFields) && - !(node.transformFlags & TransformFlags.ContainsLexicalThisOrSuper)) { + if ( + !(node.transformFlags & TransformFlags.ContainsClassFields) && + !(node.transformFlags & TransformFlags.ContainsLexicalThisOrSuper) + ) { return node; } @@ -514,7 +514,7 @@ export function transformClassFields(context: TransformationContext): (x: Source return setCurrentClassElementAnd( /*classElement*/ undefined, fallbackVisitor, - node + node, ); case SyntaxKind.Constructor: case SyntaxKind.MethodDeclaration: @@ -524,7 +524,7 @@ export function transformClassFields(context: TransformationContext): (x: Source return setCurrentClassElementAnd( node as ConstructorDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration, fallbackVisitor, - node + node, ); } default: @@ -591,24 +591,28 @@ export function transformClassFields(context: TransformationContext): (x: Source return setCurrentClassElementAnd( node as ConstructorDeclaration, visitConstructorDeclaration, - node as ConstructorDeclaration); + node as ConstructorDeclaration, + ); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.MethodDeclaration: return setCurrentClassElementAnd( node as MethodDeclaration | AccessorDeclaration, visitMethodOrAccessorDeclaration, - node as MethodDeclaration | AccessorDeclaration); + node as MethodDeclaration | AccessorDeclaration, + ); case SyntaxKind.PropertyDeclaration: return setCurrentClassElementAnd( node as PropertyDeclaration, visitPropertyDeclaration, - node as PropertyDeclaration); + node as PropertyDeclaration, + ); case SyntaxKind.ClassStaticBlockDeclaration: return setCurrentClassElementAnd( node as ClassStaticBlockDeclaration, visitClassStaticBlockDeclaration, - node as ClassStaticBlockDeclaration); + node as ClassStaticBlockDeclaration, + ); case SyntaxKind.ComputedPropertyName: return visitComputedPropertyName(node as ComputedPropertyName); case SyntaxKind.SemicolonClassElement: @@ -671,7 +675,7 @@ export function transformClassFields(context: TransformationContext): (x: Source const receiver = visitNode(node.right, visitor, isExpression); return setOriginalNode( emitHelpers().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver), - node + node, ); } @@ -853,9 +857,9 @@ export function transformClassFields(context: TransformationContext): (x: Source /*typeParameters*/ undefined, visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - visitFunctionBody(node.body!, visitor, context) - ) - ) + visitFunctionBody(node.body!, visitor, context), + ), + ), ); } @@ -993,7 +997,7 @@ export function transformClassFields(context: TransformationContext): (x: Source node.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined + /*initializer*/ undefined, ); } @@ -1007,7 +1011,7 @@ export function transformClassFields(context: TransformationContext): (x: Source visitNode(node.name, propertyNameVisitor, isPropertyName), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression), ); } @@ -1019,7 +1023,8 @@ export function transformClassFields(context: TransformationContext): (x: Source const expr = getPropertyNameExpressionIfNeeded( node.name, - /*shouldHoist*/ !!node.initializer || useDefineForClassFields); + /*shouldHoist*/ !!node.initializer || useDefineForClassFields, + ); if (expr) { getPendingExpressions().push(...flattenCommaList(expr)); } @@ -1028,7 +1033,7 @@ export function transformClassFields(context: TransformationContext): (x: Source const initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); if (initializerStatement) { const staticBlock = factory.createClassStaticBlockDeclaration( - factory.createBlock([initializerStatement]) + factory.createBlock([initializerStatement]), ); setOriginalNode(staticBlock, node); @@ -1052,7 +1057,7 @@ export function transformClassFields(context: TransformationContext): (x: Source visitNode(node.name, propertyNameVisitor, isPropertyName), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression), ); } @@ -1066,14 +1071,16 @@ export function transformClassFields(context: TransformationContext): (x: Source function shouldTransformAutoAccessorsInCurrentClass() { return shouldTransformAutoAccessors === Ternary.True || shouldTransformAutoAccessors === Ternary.Maybe && - !!lexicalEnvironment?.data && !!(lexicalEnvironment.data.facts & ClassFacts.WillHoistInitializersToConstructor); + !!lexicalEnvironment?.data && !!(lexicalEnvironment.data.facts & ClassFacts.WillHoistInitializersToConstructor); } function visitPropertyDeclaration(node: PropertyDeclaration) { // If this is an auto-accessor, we defer to `transformAutoAccessor`. That function // will in turn call `transformFieldInitializer` as needed. - if (isAutoAccessorPropertyDeclaration(node) && (shouldTransformAutoAccessorsInCurrentClass() || - hasStaticModifier(node) && getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements)) { + if ( + isAutoAccessorPropertyDeclaration(node) && (shouldTransformAutoAccessorsInCurrentClass() || + hasStaticModifier(node) && getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements) + ) { return transformAutoAccessor(node); } @@ -1116,21 +1123,21 @@ export function transformClassFields(context: TransformationContext): (x: Source receiver, info.brandCheckIdentifier, info.kind, - info.getterName + info.getterName, ); case PrivateIdentifierKind.Method: return emitHelpers().createClassPrivateFieldGetHelper( receiver, info.brandCheckIdentifier, info.kind, - info.methodName + info.methodName, ); case PrivateIdentifierKind.Field: return emitHelpers().createClassPrivateFieldGetHelper( receiver, info.brandCheckIdentifier, info.kind, - info.isStatic ? info.variableName : undefined + info.isStatic ? info.variableName : undefined, ); case "untransformed": return Debug.fail("Access helpers should not be created for untransformed private elements"); @@ -1147,18 +1154,20 @@ export function transformClassFields(context: TransformationContext): (x: Source return setTextRange( setOriginalNode( createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), - node + node, ), - node + node, ); } } - if (shouldTransformSuperInStaticInitializers && + if ( + shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isIdentifier(node.name) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && - lexicalEnvironment?.data) { + lexicalEnvironment?.data + ) { const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; if (facts & ClassFacts.ClassWasDecorated) { return visitInvalidSuperProperty(node); @@ -1168,7 +1177,7 @@ export function transformClassFields(context: TransformationContext): (x: Source const superProperty = factory.createReflectGetCall( superClassReference, factory.createStringLiteralFromNode(node.name), - classConstructor + classConstructor, ); setOriginalNode(superProperty, node.expression); setTextRange(superProperty, node.expression); @@ -1179,11 +1188,13 @@ export function transformClassFields(context: TransformationContext): (x: Source } function visitElementAccessExpression(node: ElementAccessExpression) { - if (shouldTransformSuperInStaticInitializers && + if ( + shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && - lexicalEnvironment?.data) { + lexicalEnvironment?.data + ) { const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; if (facts & ClassFacts.ClassWasDecorated) { return visitInvalidSuperProperty(node); @@ -1194,7 +1205,7 @@ export function transformClassFields(context: TransformationContext): (x: Source const superProperty = factory.createReflectGetCall( superClassReference, visitNode(node.argumentExpression, visitor, isExpression), - classConstructor + classConstructor, ); setOriginalNode(superProperty, node.expression); setTextRange(superProperty, node.expression); @@ -1205,8 +1216,10 @@ export function transformClassFields(context: TransformationContext): (x: Source } function visitPreOrPostfixUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression, discarded: boolean) { - if (node.operator === SyntaxKind.PlusPlusToken || - node.operator === SyntaxKind.MinusMinusToken) { + if ( + node.operator === SyntaxKind.PlusPlusToken || + node.operator === SyntaxKind.MinusMinusToken + ) { const operand = skipParentheses(node.operand); if (isPrivateIdentifierPropertyAccessExpression(operand)) { @@ -1223,7 +1236,7 @@ export function transformClassFields(context: TransformationContext): (x: Source info, initializeExpression || readExpression, expression, - SyntaxKind.EqualsToken + SyntaxKind.EqualsToken, ); setOriginalNode(expression, node); setTextRange(expression, node); @@ -1234,11 +1247,13 @@ export function transformClassFields(context: TransformationContext): (x: Source return expression; } } - else if (shouldTransformSuperInStaticInitializers && + else if ( + shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(operand) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && - lexicalEnvironment?.data) { + lexicalEnvironment?.data + ) { // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)` // converts `++super[f()]` into `(Reflect.set(_baseTemp, _a = f(), (_b = Reflect.get(_baseTemp, _a, _classTemp), _c = ++_b), _classTemp), _c)` // converts `--super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = --_a), _classTemp), _b)` @@ -1298,18 +1313,18 @@ export function transformClassFields(context: TransformationContext): (x: Source visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, visitor, context) + visitIterationBody(node.statement, visitor, context), ); } function visitExpressionStatement(node: ExpressionStatement) { return factory.updateExpressionStatement( node, - visitNode(node.expression, discardedValueVisitor, isExpression) + visitNode(node.expression, discardedValueVisitor, isExpression), ); } - function createCopiableReceiverExpr(receiver: Expression): { readExpression: Expression; initializeExpression: Expression | undefined } { + function createCopiableReceiverExpr(receiver: Expression): { readExpression: Expression; initializeExpression: Expression | undefined; } { const clone = nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver); if (receiver.kind === SyntaxKind.ThisKeyword && noSubstitution.has(receiver)) { noSubstitution.add(clone); @@ -1323,8 +1338,10 @@ export function transformClassFields(context: TransformationContext): (x: Source } function visitCallExpression(node: CallExpression) { - if (isPrivateIdentifierPropertyAccessExpression(node.expression) && - accessPrivateIdentifier(node.expression.name)) { + if ( + isPrivateIdentifierPropertyAccessExpression(node.expression) && + accessPrivateIdentifier(node.expression.name) + ) { // obj.#x() // Transform call expressions of private names to properly bind the `this` parameter. @@ -1335,22 +1352,24 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createPropertyAccessChain(visitNode(target, visitor, isExpression), node.questionDotToken, "call"), /*questionDotToken*/ undefined, /*typeArguments*/ undefined, - [visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)] + [visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)], ); } return factory.updateCallExpression( node, factory.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "call"), /*typeArguments*/ undefined, - [visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)] + [visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)], ); } - if (shouldTransformSuperInStaticInitializers && + if ( + shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.expression) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && - lexicalEnvironment?.data?.classConstructor) { + lexicalEnvironment?.data?.classConstructor + ) { // super.x() // super[x]() @@ -1358,7 +1377,7 @@ export function transformClassFields(context: TransformationContext): (x: Source const invocation = factory.createFunctionCallCall( visitNode(node.expression, visitor, isExpression), lexicalEnvironment.data.classConstructor, - visitNodes(node.arguments, visitor, isExpression) + visitNodes(node.arguments, visitor, isExpression), ); setOriginalNode(invocation, node); setTextRange(invocation, node); @@ -1369,8 +1388,10 @@ export function transformClassFields(context: TransformationContext): (x: Source } function visitTaggedTemplateExpression(node: TaggedTemplateExpression) { - if (isPrivateIdentifierPropertyAccessExpression(node.tag) && - accessPrivateIdentifier(node.tag.name)) { + if ( + isPrivateIdentifierPropertyAccessExpression(node.tag) && + accessPrivateIdentifier(node.tag.name) + ) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. const { thisArg, target } = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion); return factory.updateTaggedTemplateExpression( @@ -1378,23 +1399,24 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createCallExpression( factory.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "bind"), /*typeArguments*/ undefined, - [visitNode(thisArg, visitor, isExpression)] + [visitNode(thisArg, visitor, isExpression)], ), /*typeArguments*/ undefined, - visitNode(node.template, visitor, isTemplateLiteral) + visitNode(node.template, visitor, isTemplateLiteral), ); } - if (shouldTransformSuperInStaticInitializers && + if ( + shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.tag) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && - lexicalEnvironment?.data?.classConstructor) { - + lexicalEnvironment?.data?.classConstructor + ) { // converts `` super.f`x` `` into `` Reflect.get(_baseTemp, "f", _classTemp).bind(_classTemp)`x` `` const invocation = factory.createFunctionBindCall( visitNode(node.tag, visitor, isExpression), lexicalEnvironment.data.classConstructor, - [] + [], ); setOriginalNode(invocation, node); setTextRange(invocation, node); @@ -1402,7 +1424,7 @@ export function transformClassFields(context: TransformationContext): (x: Source node, invocation, /*typeArguments*/ undefined, - visitNode(node.template, visitor, isTemplateLiteral) + visitNode(node.template, visitor, isTemplateLiteral), ); } return visitEachChild(node, visitor, context); @@ -1418,8 +1440,10 @@ export function transformClassFields(context: TransformationContext): (x: Source const result = visitNode(node.body.statements[0].expression, visitor, isExpression); // If the generated `_classThis` assignment is a noop (i.e., `_classThis = _classThis`), we can // eliminate the expression - if (isAssignmentExpression(result, /*excludeCompoundAssignment*/ true) && - result.left === result.right) { + if ( + isAssignmentExpression(result, /*excludeCompoundAssignment*/ true) && + result.left === result.right + ) { return undefined; } return result; @@ -1433,7 +1457,7 @@ export function transformClassFields(context: TransformationContext): (x: Source let statements = setCurrentClassElementAnd( node, statements => visitNodes(statements, visitor, isStatement), - node.body.statements + node.body.statements, ); statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); @@ -1453,9 +1477,8 @@ export function transformClassFields(context: TransformationContext): (x: Source return false; } - const hasTransformableStatics = - (shouldTransformPrivateElementsOrClassStaticBlocks || - !!(getInternalEmitFlags(node) && InternalEmitFlags.TransformPrivateStaticElements)) && + const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || + !!(getInternalEmitFlags(node) && InternalEmitFlags.TransformPrivateStaticElements)) && some(staticPropertiesOrClassStaticBlocks, node => isClassStaticBlockDeclaration(node) || isPrivateIdentifierClassElementDeclaration(node) || @@ -1476,7 +1499,7 @@ export function transformClassFields(context: TransformationContext): (x: Source node, visitNode(node.left, assignmentTargetVisitor, isExpression), node.operatorToken, - visitNode(node.right, visitor, isExpression) + visitNode(node.right, visitor, isExpression), ); const expr = some(pendingExpressions) ? factory.inlineExpressions(compact([...pendingExpressions, node])) : @@ -1524,17 +1547,19 @@ export function transformClassFields(context: TransformationContext): (x: Source return setTextRange( setOriginalNode( createPrivateIdentifierAssignment(info, left.expression, node.right, node.operatorToken.kind), - node + node, ), - node + node, ); } } - else if (shouldTransformSuperInStaticInitializers && + else if ( + shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.left) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && - lexicalEnvironment?.data) { + lexicalEnvironment?.data + ) { // super.x = ... // super[x] = ... // super.x += ... @@ -1545,11 +1570,11 @@ export function transformClassFields(context: TransformationContext): (x: Source node, visitInvalidSuperProperty(node.left), node.operatorToken, - visitNode(node.right, visitor, isExpression)); + visitNode(node.right, visitor, isExpression), + ); } if (classConstructor && superClassReference) { - let setterName = - isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : + let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory.createStringLiteralFromNode(node.left.name) : undefined; if (setterName) { @@ -1568,14 +1593,14 @@ export function transformClassFields(context: TransformationContext): (x: Source const superPropertyGet = factory.createReflectGetCall( superClassReference, getterName, - classConstructor + classConstructor, ); setOriginalNode(superPropertyGet, node.left); setTextRange(superPropertyGet, node.left); expression = factory.createBinaryExpression( superPropertyGet, getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), - expression + expression, ); setTextRange(expression, node); } @@ -1590,7 +1615,7 @@ export function transformClassFields(context: TransformationContext): (x: Source superClassReference, setterName, expression, - classConstructor + classConstructor, ); setOriginalNode(expression, node); setTextRange(expression, node); @@ -1625,14 +1650,12 @@ export function transformClassFields(context: TransformationContext): (x: Source // ... // 2. Return ? NamedEvaluation of |Expression| with argument _name_. - const visitorFunc: Visitor = - discarded ? discardedValueVisitor : + const visitorFunc: Visitor = discarded ? discardedValueVisitor : visitor; const expression = visitNode(node.expression, visitorFunc, isExpression); return factory.updateParenthesizedExpression(node, expression); } - function createPrivateIdentifierAssignment(info: PrivateIdentifierInfo, receiver: Expression, right: Expression, operator: AssignmentOperator): Expression { receiver = visitNode(receiver, visitor, isExpression); right = visitNode(right, visitor, isExpression); @@ -1644,20 +1667,20 @@ export function transformClassFields(context: TransformationContext): (x: Source right = factory.createBinaryExpression( createPrivateIdentifierAccessHelper(info, readExpression), getNonAssignmentOperatorForCompoundAssignment(operator), - right + right, ); } setCommentRange(receiver, moveRangePos(receiver, -1)); - switch(info.kind) { + switch (info.kind) { case PrivateIdentifierKind.Accessor: return emitHelpers().createClassPrivateFieldSetHelper( receiver, info.brandCheckIdentifier, right, info.kind, - info.setterName + info.setterName, ); case PrivateIdentifierKind.Method: return emitHelpers().createClassPrivateFieldSetHelper( @@ -1665,7 +1688,7 @@ export function transformClassFields(context: TransformationContext): (x: Source info.brandCheckIdentifier, right, info.kind, - /*f*/ undefined + /*f*/ undefined, ); case PrivateIdentifierKind.Field: return emitHelpers().createClassPrivateFieldSetHelper( @@ -1673,7 +1696,7 @@ export function transformClassFields(context: TransformationContext): (x: Source info.brandCheckIdentifier, right, info.kind, - info.isStatic ? info.variableName : undefined + info.isStatic ? info.variableName : undefined, ); case "untransformed": return Debug.fail("Access helpers should not be created for untransformed private elements"); @@ -1702,8 +1725,10 @@ export function transformClassFields(context: TransformationContext): (x: Source let containsInstanceAutoAccessors = false; for (const member of node.members) { if (isStatic(member)) { - if (member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && - shouldTransformPrivateElementsOrClassStaticBlocks) { + if ( + member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && + shouldTransformPrivateElementsOrClassStaticBlocks + ) { facts |= ClassFacts.NeedsClassConstructorReference; } else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === Ternary.True && !node.name && !node.emitNode?.classThis) { @@ -1741,8 +1766,7 @@ export function transformClassFields(context: TransformationContext): (x: Source } } - const willHoistInitializersToConstructor = - shouldTransformInitializersUsingDefine && containsPublicInstanceFields || + const willHoistInitializersToConstructor = shouldTransformInitializersUsingDefine && containsPublicInstanceFields || shouldTransformInitializersUsingSet && containsInitializedPublicInstanceFields || shouldTransformPrivateElementsOrClassStaticBlocks && containsInstancePrivateElements || shouldTransformPrivateElementsOrClassStaticBlocks && containsInstanceAutoAccessors && shouldTransformAutoAccessors === Ternary.True; @@ -1763,9 +1787,9 @@ export function transformClassFields(context: TransformationContext): (x: Source node, factory.createAssignment( temp, - visitNode(node.expression, visitor, isExpression) + visitNode(node.expression, visitor, isExpression), ), - /*typeArguments*/ undefined + /*typeArguments*/ undefined, ); } return visitEachChild(node, visitor, context); @@ -1789,8 +1813,10 @@ export function transformClassFields(context: TransformationContext): (x: Source if (isStringLiteral(node.emitNode.assignedName)) { // If the class name was assigned from a string literal based on an Identifier, use the Identifier // as the prefix. - if (node.emitNode.assignedName.textSourceNode && - isIdentifier(node.emitNode.assignedName.textSourceNode)) { + if ( + node.emitNode.assignedName.textSourceNode && + isIdentifier(node.emitNode.assignedName.textSourceNode) + ) { getPrivateIdentifierEnvironment().data.className = node.emitNode.assignedName.textSourceNode; } // If the class name was assigned from a string literal that is a valid identifier, create an @@ -1808,7 +1834,7 @@ export function transformClassFields(context: TransformationContext): (x: Source if (some(privateInstanceMethodsAndAccessors)) { getPrivateIdentifierEnvironment().data.weakSetName = createHoistedVariableForClass( "instances", - privateInstanceMethodsAndAccessors[0].name + privateInstanceMethodsAndAccessors[0].name, ); } } @@ -1828,7 +1854,6 @@ export function transformClassFields(context: TransformationContext): (x: Source currentClassContainer = savedCurrentClassContainer; pendingExpressions = savedPendingExpressions; return result; - } function visitClassDeclaration(node: ClassDeclaration) { @@ -1899,7 +1924,7 @@ export function transformClassFields(context: TransformationContext): (x: Source statements.push(factory.createExportAssignment( /*modifiers*/ undefined, /*isExportEquals*/ false, - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) + factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true), )); } @@ -1915,7 +1940,7 @@ export function transformClassFields(context: TransformationContext): (x: Source node.name, /*typeParameters*/ undefined, heritageClauses, - members + members, ); statements.unshift(classDecl); @@ -1981,7 +2006,7 @@ export function transformClassFields(context: TransformationContext): (x: Source node.name, /*typeParameters*/ undefined, heritageClauses, - members + members, ); const expressions: Expression[] = []; @@ -1991,8 +2016,7 @@ export function transformClassFields(context: TransformationContext): (x: Source // Static initializers are transformed to `static {}` blocks when `useDefineForClassFields: false` // and not also transforming static blocks. - const hasTransformableStatics = - (shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements) && + const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements) && some(staticPropertiesOrClassStaticBlocks, node => isClassStaticBlockDeclaration(node) || isPrivateIdentifierClassElementDeclaration(node) || @@ -2062,9 +2086,11 @@ export function transformClassFields(context: TransformationContext): (x: Source } function visitThisExpression(node: ThisExpression) { - if (shouldTransformThisInStaticInitializers && currentClassElement && + if ( + shouldTransformThisInStaticInitializers && currentClassElement && isClassStaticBlockDeclaration(currentClassElement) && - lexicalEnvironment?.data) { + lexicalEnvironment?.data + ) { const { classThis, classConstructor } = lexicalEnvironment.data; return classThis ?? classConstructor ?? node; } @@ -2099,8 +2125,10 @@ export function transformClassFields(context: TransformationContext): (x: Source for (const member of node.members) { if (isAutoAccessorPropertyDeclaration(member)) { const storageName = factory.getGeneratedPrivateNameForNode(member.name, /*prefix*/ undefined, "_accessor_storage"); - if (shouldTransformPrivateElementsOrClassStaticBlocks || - shouldTransformPrivateStaticElementsInClass && hasStaticModifier(member)) { + if ( + shouldTransformPrivateElementsOrClassStaticBlocks || + shouldTransformPrivateStaticElementsInClass && hasStaticModifier(member) + ) { addPrivateIdentifierToEnvironment(member, storageName, addPrivateIdentifierPropertyDeclarationToEnvironment); } else { @@ -2140,7 +2168,8 @@ export function transformClassFields(context: TransformationContext): (x: Source /*parameters*/ [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, - factory.createBlock([statement])); + factory.createBlock([statement]), + ); prologue = factory.createAssignment(temp, arrow); statement = factory.createExpressionStatement(factory.createCallExpression(temp, /*typeArguments*/ undefined, [])); } @@ -2180,9 +2209,9 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createNewExpression( factory.createIdentifier("WeakSet"), /*typeArguments*/ undefined, - [] - ) - ) + [], + ), + ), ); } @@ -2211,12 +2240,12 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createConstructorDeclaration( /*modifiers*/ undefined, parameters ?? [], - body + body, ), - constructor || container + constructor || container, ), - constructor - ) + constructor, + ), ); } @@ -2235,7 +2264,8 @@ export function transformClassFields(context: TransformationContext): (x: Source superPath, superPathDepth + 1, initializerStatements, - constructor); + constructor, + ); const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); @@ -2244,7 +2274,8 @@ export function transformClassFields(context: TransformationContext): (x: Source superStatement, factory.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock))); + visitNode(superStatement.finallyBlock, visitor, isBlock), + )); } else { addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); @@ -2337,7 +2368,7 @@ export function transformClassFields(context: TransformationContext): (x: Source superStatementIndices, /*superPathDepth*/ 0, initializerStatements, - constructor + constructor, ); } else { @@ -2367,9 +2398,9 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createCallExpression( factory.createSuper(), /*typeArguments*/ undefined, - [factory.createSpreadElement(factory.createIdentifier("arguments"))] - ) - ) + [factory.createSpreadElement(factory.createIdentifier("arguments"))], + ), + ), ); } addRange(statements, initializerStatements); @@ -2389,11 +2420,11 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createBlock( setTextRange( factory.createNodeArray(statements), - /*location*/ constructor ? constructor.body!.statements : node.members + /*location*/ constructor ? constructor.body!.statements : node.members, ), - multiLine + multiLine, ), - /*location*/ constructor ? constructor.body : undefined + /*location*/ constructor ? constructor.body : undefined, ); } @@ -2510,12 +2541,11 @@ export function transformClassFields(context: TransformationContext): (x: Source property = transformNamedEvaluation(context, property); } - const propertyName = - hasAccessorModifier(property) ? - factory.getGeneratedPrivateNameForNode(property.name) : + const propertyName = hasAccessorModifier(property) ? + factory.getGeneratedPrivateNameForNode(property.name) : isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) ? - factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : - property.name; + factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : + property.name; if (hasStaticModifier(property)) { currentClassElement = property; @@ -2530,14 +2560,14 @@ export function transformClassFields(context: TransformationContext): (x: Source factory, receiver, visitNode(property.initializer, visitor, isExpression), - privateIdentifierInfo.brandCheckIdentifier + privateIdentifierInfo.brandCheckIdentifier, ); } else { return createPrivateStaticFieldInitializer( factory, privateIdentifierInfo.variableName, - visitNode(property.initializer, visitor, isExpression) + visitNode(property.initializer, visitor, isExpression), ); } } @@ -2566,11 +2596,13 @@ export function transformClassFields(context: TransformationContext): (x: Source const localName = factory.cloneNode(propertyName); if (initializer) { // unwrap `(__runInitializers(this, _instanceExtraInitializers), void 0)` - if (isParenthesizedExpression(initializer) && + if ( + isParenthesizedExpression(initializer) && isCommaExpression(initializer.expression) && isCallToHelper(initializer.expression.left, "___runInitializers" as __String) && isVoidExpression(initializer.expression.right) && - isNumericLiteral(initializer.expression.right.expression)) { + isNumericLiteral(initializer.expression.right.expression) + ) { initializer = initializer.expression.left; } initializer = factory.inlineExpressions([initializer, localName]); @@ -2647,8 +2679,8 @@ export function transformClassFields(context: TransformationContext): (x: Source Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); statements.push( factory.createExpressionStatement( - createPrivateInstanceMethodInitializer(factory, receiver, weakSetName) - ) + createPrivateInstanceMethodInitializer(factory, receiver, weakSetName), + ), ); } @@ -2657,11 +2689,13 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.updatePropertyAccessExpression( node, factory.createVoidZero(), - node.name) : + node.name, + ) : factory.updateElementAccessExpression( node, factory.createVoidZero(), - visitNode(node.argumentExpression, visitor, isExpression)); + visitNode(node.argumentExpression, visitor, isExpression), + ); } /** @@ -2728,7 +2762,7 @@ export function transformClassFields(context: TransformationContext): (x: Source privateEnv: PrivateEnv, isStatic: boolean, isValid: boolean, - previousInfo: PrivateIdentifierInfo | undefined + previousInfo: PrivateIdentifierInfo | undefined, ) { if (isAutoAccessorPropertyDeclaration(node)) { addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); @@ -2754,11 +2788,10 @@ export function transformClassFields(context: TransformationContext): (x: Source privateEnv: PrivateEnv, isStatic: boolean, isValid: boolean, - _previousInfo: PrivateIdentifierInfo | undefined + _previousInfo: PrivateIdentifierInfo | undefined, ) { if (isStatic) { - const brandCheckIdentifier = - Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment"); + const brandCheckIdentifier = Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment"); const variableName = createHoistedVariableForPrivateName(name); setPrivateIdentifier(privateEnv, name, { @@ -2784,8 +2817,8 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createNewExpression( factory.createIdentifier("WeakMap"), /*typeArguments*/ undefined, - [] - ) + [], + ), )); } } @@ -2797,7 +2830,7 @@ export function transformClassFields(context: TransformationContext): (x: Source privateEnv: PrivateEnv, isStatic: boolean, isValid: boolean, - _previousInfo: PrivateIdentifierInfo | undefined + _previousInfo: PrivateIdentifierInfo | undefined, ) { const methodName = createHoistedVariableForPrivateName(name); const brandCheckIdentifier = isStatic ? @@ -2820,7 +2853,7 @@ export function transformClassFields(context: TransformationContext): (x: Source privateEnv: PrivateEnv, isStatic: boolean, isValid: boolean, - previousInfo: PrivateIdentifierInfo | undefined + previousInfo: PrivateIdentifierInfo | undefined, ) { const getterName = createHoistedVariableForPrivateName(name, "_get"); const brandCheckIdentifier = isStatic ? @@ -2849,15 +2882,17 @@ export function transformClassFields(context: TransformationContext): (x: Source privateEnv: PrivateEnv, isStatic: boolean, isValid: boolean, - previousInfo: PrivateIdentifierInfo | undefined + previousInfo: PrivateIdentifierInfo | undefined, ) { const setterName = createHoistedVariableForPrivateName(name, "_set"); const brandCheckIdentifier = isStatic ? Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); - if (previousInfo?.kind === PrivateIdentifierKind.Accessor && - previousInfo.isStatic === isStatic && !previousInfo.setterName) { + if ( + previousInfo?.kind === PrivateIdentifierKind.Accessor && + previousInfo.isStatic === isStatic && !previousInfo.setterName + ) { previousInfo.setterName = setterName; } else { @@ -2879,7 +2914,7 @@ export function transformClassFields(context: TransformationContext): (x: Source privateEnv: PrivateEnv, isStatic: boolean, isValid: boolean, - _previousInfo: PrivateIdentifierInfo | undefined + _previousInfo: PrivateIdentifierInfo | undefined, ) { const getterName = createHoistedVariableForPrivateName(name, "_get"); const setterName = createHoistedVariableForPrivateName(name, "_set"); @@ -2907,8 +2942,8 @@ export function transformClassFields(context: TransformationContext): (x: Source privateEnv: PrivateEnv, isStatic: boolean, isValid: boolean, - previousInfo: PrivateIdentifierInfo | undefined - ) => void + previousInfo: PrivateIdentifierInfo | undefined, + ) => void, ) { const lex = getClassLexicalEnvironment(); const privateEnv = getPrivateIdentifierEnvironment(); @@ -2921,8 +2956,7 @@ export function transformClassFields(context: TransformationContext): (x: Source function createHoistedVariableForClass(name: string | PrivateIdentifier | undefined, node: PrivateIdentifier | ClassStaticBlockDeclaration, suffix?: string): Identifier { const { className } = getPrivateIdentifierEnvironment().data; const prefix: GeneratedNamePart | string = className ? { prefix: "_", node: className, suffix: "_" } : "_"; - const identifier = - typeof name === "object" ? factory.getGeneratedNameForNode(name, GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes, prefix, suffix) : + const identifier = typeof name === "object" ? factory.getGeneratedNameForNode(name, GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes, prefix, suffix) : typeof name === "string" ? factory.createUniqueName(name, GeneratedIdentifierFlags.Optimistic, prefix, suffix) : factory.createTempVariable(/*recordTempVariable*/ undefined, /*reservedInNestedScopes*/ true, prefix, suffix); @@ -2970,8 +3004,8 @@ export function transformClassFields(context: TransformationContext): (x: Source info, receiver, parameter, - SyntaxKind.EqualsToken - ) + SyntaxKind.EqualsToken, + ), ); } @@ -2983,18 +3017,19 @@ export function transformClassFields(context: TransformationContext): (x: Source if (isPrivateIdentifierPropertyAccessExpression(node)) { return wrapPrivateIdentifierForDestructuringTarget(node); } - else if (shouldTransformSuperInStaticInitializers && + else if ( + shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && - lexicalEnvironment?.data) { + lexicalEnvironment?.data + ) { const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; if (facts & ClassFacts.ClassWasDecorated) { return visitInvalidSuperProperty(node); } else if (classConstructor && superClassReference) { - const name = - isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : + const name = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory.createStringLiteralFromNode(node.name) : undefined; if (name) { @@ -3006,7 +3041,7 @@ export function transformClassFields(context: TransformationContext): (x: Source name, temp, classConstructor, - ) + ), ); } } @@ -3124,7 +3159,7 @@ export function transformClassFields(context: TransformationContext): (x: Source // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ]; return factory.updateArrayLiteralExpression( node, - visitNodes(node.elements, visitArrayAssignmentElement, isExpression) + visitNodes(node.elements, visitArrayAssignmentElement, isExpression), ); } else { @@ -3138,7 +3173,7 @@ export function transformClassFields(context: TransformationContext): (x: Source // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" }; return factory.updateObjectLiteralExpression( node, - visitNodes(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike) + visitNodes(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike), ); } } @@ -3231,9 +3266,11 @@ export function transformClassFields(context: TransformationContext): (x: Source } function substituteThisExpression(node: ThisExpression) { - if (enabledSubstitutions & ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference && + if ( + enabledSubstitutions & ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference && lexicalEnvironment?.data && - !noSubstitution.has(node)) { + !noSubstitution.has(node) + ) { const { facts, classConstructor, classThis } = lexicalEnvironment.data; const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor; if (substituteThis) { @@ -3242,7 +3279,7 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.cloneNode(substituteThis), node, ), - node + node, ); } if (facts & ClassFacts.ClassWasDecorated && legacyDecorators) { @@ -3285,8 +3322,8 @@ function createPrivateStaticFieldInitializer(factory: NodeFactory, variableName: return factory.createAssignment( variableName, factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("value", initializer || factory.createVoidZero()) - ]) + factory.createPropertyAssignment("value", initializer || factory.createVoidZero()), + ]), ); } @@ -3294,7 +3331,7 @@ function createPrivateInstanceFieldInitializer(factory: NodeFactory, receiver: L return factory.createCallExpression( factory.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ undefined, - [receiver, initializer || factory.createVoidZero()] + [receiver, initializer || factory.createVoidZero()], ); } @@ -3302,7 +3339,7 @@ function createPrivateInstanceMethodInitializer(factory: NodeFactory, receiver: return factory.createCallExpression( factory.createPropertyAccessExpression(weakSetName, "add"), /*typeArguments*/ undefined, - [receiver] + [receiver], ); } @@ -3310,7 +3347,7 @@ function isReservedPrivateName(node: PrivateIdentifier) { return !isGeneratedPrivateIdentifier(node) && node.escapedText === "#constructor"; } -type PrivateIdentifierInExpression = BinaryExpression & { readonly left: PrivateIdentifier, readonly token: InKeyword }; +type PrivateIdentifierInExpression = BinaryExpression & { readonly left: PrivateIdentifier; readonly token: InKeyword; }; function isPrivateIdentifierInExpression(node: BinaryExpression): node is PrivateIdentifierInExpression { return isPrivateIdentifier(node.left) @@ -3323,4 +3360,4 @@ function isStaticPropertyDeclaration(node: Node): node is PropertyDeclaration { function isStaticPropertyDeclarationOrClassStaticBlock(node: Node): node is ClassStaticBlockDeclaration | PropertyDeclaration { return isClassStaticBlockDeclaration(node) || isStaticPropertyDeclaration(node); -} \ No newline at end of file +} diff --git a/src/compiler/transformers/classThis.ts b/src/compiler/transformers/classThis.ts index b03cd68144b09..48f51ea8477c4 100644 --- a/src/compiler/transformers/classThis.ts +++ b/src/compiler/transformers/classThis.ts @@ -20,7 +20,7 @@ import { some, Statement, SyntaxKind, - ThisExpression + ThisExpression, } from "../_namespaces/ts"; /** @@ -52,14 +52,16 @@ export function createClassThisAssignmentBlock(factory: NodeFactory, classThis: /** @internal */ export type ClassThisAssignmentBlock = ClassStaticBlockDeclaration & { readonly body: Block & { - readonly statements: NodeArray & readonly [ - ExpressionStatement & { - readonly expression: AssignmentExpression & { - readonly left: Identifier; - readonly right: ThisExpression; - }; - } - ]; + readonly statements: + & NodeArray + & readonly [ + ExpressionStatement & { + readonly expression: AssignmentExpression & { + readonly left: Identifier; + readonly right: ThisExpression; + }; + }, + ]; }; }; @@ -99,11 +101,8 @@ export function classHasClassThisAssignment(node: ClassLikeDeclaration) { * expression that has already had its `EmitFlags` set or may have been tracked to prevent substitution. * @internal */ -export function injectClassThisAssignmentIfMissing(factory: NodeFactory, node: T, - classThis: Identifier, thisExpression?: ThisExpression): Extract>; -export function injectClassThisAssignmentIfMissing(factory: NodeFactory, node: T, - classThis: Identifier, thisExpression?: ThisExpression) { - +export function injectClassThisAssignmentIfMissing(factory: NodeFactory, node: T, classThis: Identifier, thisExpression?: ThisExpression): Extract>; +export function injectClassThisAssignmentIfMissing(factory: NodeFactory, node: T, classThis: Identifier, thisExpression?: ThisExpression) { // given: // // class C { @@ -134,14 +133,16 @@ export function injectClassThisAssignmentIfMissing (s.errorNode && canProduceDiagnostics(s.errorNode) ? createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ + getSymbolAccessibilityDiagnostic = s => (s.errorNode && canProduceDiagnostics(s.errorNode) ? createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({ diagnosticMessage: s.errorModuleName ? Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, - errorNode: s.errorNode || sourceFile + errorNode: s.errorNode || sourceFile, })); const result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled); getSymbolAccessibilityDiagnostic = oldDiag; @@ -504,8 +490,8 @@ export function transformDeclarations(context: TransformationContext) { refs = new Map(); libs = new Map(); let hasNoDefaultLib = false; - const bundle = factory.createBundle(map(node.sourceFiles, - sourceFile => { + const bundle = factory.createBundle( + map(node.sourceFiles, sourceFile => { if (sourceFile.isDeclarationFile) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -522,28 +508,37 @@ export function transformDeclarations(context: TransformationContext) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; const statements = isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : visitNodes(sourceFile.statements, visitDeclarationStatements, isStatement); - const newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration( - [factory.createModifier(SyntaxKind.DeclareKeyword)], - factory.createStringLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), - factory.createModuleBlock(setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)) - )], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + const newFile = factory.updateSourceFile( + sourceFile, + [factory.createModuleDeclaration( + [factory.createModifier(SyntaxKind.DeclareKeyword)], + factory.createStringLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), + factory.createModuleBlock(setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)), + )], + /*isDeclarationFile*/ true, + /*referencedFiles*/ [], + /*typeReferences*/ [], + /*hasNoDefaultLib*/ false, + /*libReferences*/ [], + ); return newFile; } needsDeclare = true; const updated = isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : visitNodes(sourceFile.statements, visitDeclarationStatements, isStatement); return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); - } - ), mapDefined(node.prepends, prepend => { - if (prepend.kind === SyntaxKind.InputFiles) { - const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal); - hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib; - collectReferences(sourceFile, refs); - recordTypeReferenceDirectivesIfNecessary(map(sourceFile.typeReferenceDirectives, ref => [ref.fileName, ref.resolutionMode])); - collectLibs(sourceFile, libs); - return sourceFile; - } - return prepend; - })); + }), + mapDefined(node.prepends, prepend => { + if (prepend.kind === SyntaxKind.InputFiles) { + const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal); + hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib; + collectReferences(sourceFile, refs); + recordTypeReferenceDirectivesIfNecessary(map(sourceFile.typeReferenceDirectives, ref => [ref.fileName, ref.resolutionMode])); + collectLibs(sourceFile, libs); + return sourceFile; + } + return prepend; + }), + ); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); bundle.syntheticLibReferences = getLibReferences(); @@ -650,7 +645,7 @@ export function transformDeclarations(context: TransformationContext) { declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false + /*isAbsolutePathAnUrl*/ false, ); if (startsWith(fileName, "./") && hasExtension(fileName)) { fileName = fileName.substring(2); @@ -708,13 +703,13 @@ export function transformDeclarations(context: TransformationContext) { return elem; } if (elem.propertyName && isIdentifier(elem.propertyName) && isIdentifier(elem.name) && !elem.symbol.isReferenced && !isIdentifierANonContextualKeyword(elem.propertyName)) { - // Unnecessary property renaming is forbidden in types, so remove renaming + // Unnecessary property renaming is forbidden in types, so remove renaming return factory.updateBindingElement( elem, elem.dotDotDotToken, /*propertyName*/ undefined, elem.propertyName, - shouldPrintWithInitializer(elem) ? elem.initializer : undefined + shouldPrintWithInitializer(elem) ? elem.initializer : undefined, ); } return factory.updateBindingElement( @@ -722,7 +717,7 @@ export function transformDeclarations(context: TransformationContext) { elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializersAndRenamings(elem.name), - shouldPrintWithInitializer(elem) ? elem.initializer : undefined + shouldPrintWithInitializer(elem) ? elem.initializer : undefined, ); } } @@ -740,7 +735,7 @@ export function transformDeclarations(context: TransformationContext) { filterBindingPatternInitializersAndRenamings(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.createToken(SyntaxKind.QuestionToken)) : undefined, ensureType(p, type || p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param - ensureNoInitializer(p) + ensureNoInitializer(p), ); if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag!; @@ -784,7 +779,7 @@ export function transformDeclarations(context: TransformationContext) { } const shouldUseResolverType = node.kind === SyntaxKind.Parameter && (resolver.isRequiredInitializedParameter(node) || - resolver.isOptionalUninitializedParameterProperty(node)); + resolver.isOptionalUninitializedParameterProperty(node)); if (type && !shouldUseResolverType) { return visitNode(type, visitDeclarationSubtree, isTypeNode); } @@ -805,9 +800,11 @@ export function transformDeclarations(context: TransformationContext) { if (node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement) { return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } - if (node.kind === SyntaxKind.Parameter + if ( + node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.PropertyDeclaration - || node.kind === SyntaxKind.PropertySignature) { + || node.kind === SyntaxKind.PropertySignature + ) { if (isPropertySignature(node) || !node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); } @@ -901,7 +898,7 @@ export function transformDeclarations(context: TransformationContext) { newValueParameter = factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - "value" + "value", ); } newParams = append(newParams, newValueParameter); @@ -967,7 +964,7 @@ export function transformDeclarations(context: TransformationContext) { decl.modifiers, decl.isTypeOnly, decl.name, - factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)) + factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)), ); } else { @@ -987,29 +984,41 @@ export function transformDeclarations(context: TransformationContext) { decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier), - getResolutionModeOverrideForClauseInNightly(decl.assertClause) + getResolutionModeOverrideForClauseInNightly(decl.assertClause), ); } // The `importClause` visibility corresponds to the default's visibility. const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; if (!decl.importClause.namedBindings) { // No named bindings (either namespace or list), meaning the import is just default or should be elided - return visibleDefaultBinding && factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause( - decl.importClause, - decl.importClause.isTypeOnly, - visibleDefaultBinding, - /*namedBindings*/ undefined, - ), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)); + return visibleDefaultBinding && factory.updateImportDeclaration( + decl, + decl.modifiers, + factory.updateImportClause( + decl.importClause, + decl.importClause.isTypeOnly, + visibleDefaultBinding, + /*namedBindings*/ undefined, + ), + rewriteModuleSpecifier(decl, decl.moduleSpecifier), + getResolutionModeOverrideForClauseInNightly(decl.assertClause), + ); } if (decl.importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { // Namespace import (optionally with visible default) const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; - return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, decl.modifiers, factory.updateImportClause( - decl.importClause, - decl.importClause.isTypeOnly, - visibleDefaultBinding, - namedBindings, - ), rewriteModuleSpecifier(decl, decl.moduleSpecifier), getResolutionModeOverrideForClauseInNightly(decl.assertClause)) : undefined; + return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration( + decl, + decl.modifiers, + factory.updateImportClause( + decl.importClause, + decl.importClause.isTypeOnly, + visibleDefaultBinding, + namedBindings, + ), + rewriteModuleSpecifier(decl, decl.moduleSpecifier), + getResolutionModeOverrideForClauseInNightly(decl.assertClause), + ) : undefined; } // Named imports (optionally with visible default) const bindingList = mapDefined(decl.importClause.namedBindings.elements, b => resolver.isDeclarationVisible(b) ? b : undefined); @@ -1024,7 +1033,7 @@ export function transformDeclarations(context: TransformationContext) { bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, ), rewriteModuleSpecifier(decl, decl.moduleSpecifier), - getResolutionModeOverrideForClauseInNightly(decl.assertClause) + getResolutionModeOverrideForClauseInNightly(decl.assertClause), ); } // Augmentation of export depends on import @@ -1034,7 +1043,7 @@ export function transformDeclarations(context: TransformationContext) { decl.modifiers, /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier), - getResolutionModeOverrideForClauseInNightly(decl.assertClause) + getResolutionModeOverrideForClauseInNightly(decl.assertClause), ); } // Nothing visible @@ -1130,7 +1139,7 @@ export function transformDeclarations(context: TransformationContext) { // We'd see a TDZ violation at runtime const canProduceDiagnostic = canProduceDiagnostics(input); const oldWithinObjectLiteralType = suppressNewDiagnosticContexts; - let shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === SyntaxKind.TypeLiteral || input.kind === SyntaxKind.MappedType) && input.parent.kind !== SyntaxKind.TypeAliasDeclaration); + let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === SyntaxKind.TypeLiteral || input.kind === SyntaxKind.MappedType) && input.parent.kind !== SyntaxKind.TypeAliasDeclaration; // Emit methods which are private as properties with no type information if (isMethodDeclaration(input) || isMethodSignature(input)) { @@ -1172,14 +1181,14 @@ export function transformDeclarations(context: TransformationContext) { input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type) + ensureType(input, input.type), )); case SyntaxKind.Constructor: { // A constructor declaration may not have a type annotation const ctor = factory.createConstructorDeclaration( /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, ModifierFlags.None), - /*body*/ undefined + /*body*/ undefined, ); return cleanup(ctor); } @@ -1195,7 +1204,7 @@ export function transformDeclarations(context: TransformationContext) { ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), - /*body*/ undefined + /*body*/ undefined, ); return cleanup(sig); } @@ -1210,7 +1219,8 @@ export function transformDeclarations(context: TransformationContext) { input.name, updateAccessorParamsList(input, hasEffectiveModifier(input, ModifierFlags.Private)), ensureType(input, accessorType), - /*body*/ undefined)); + /*body*/ undefined, + )); } case SyntaxKind.SetAccessor: { if (isPrivateIdentifier(input.name)) { @@ -1221,7 +1231,8 @@ export function transformDeclarations(context: TransformationContext) { ensureModifiers(input), input.name, updateAccessorParamsList(input, hasEffectiveModifier(input, ModifierFlags.Private)), - /*body*/ undefined)); + /*body*/ undefined, + )); } case SyntaxKind.PropertyDeclaration: if (isPrivateIdentifier(input.name)) { @@ -1233,7 +1244,7 @@ export function transformDeclarations(context: TransformationContext) { input.name, input.questionToken, ensureType(input, input.type), - ensureNoInitializer(input) + ensureNoInitializer(input), )); case SyntaxKind.PropertySignature: if (isPrivateIdentifier(input.name)) { @@ -1244,7 +1255,7 @@ export function transformDeclarations(context: TransformationContext) { ensureModifiers(input), input.name, input.questionToken, - ensureType(input, input.type) + ensureType(input, input.type), )); case SyntaxKind.MethodSignature: { if (isPrivateIdentifier(input.name)) { @@ -1257,7 +1268,7 @@ export function transformDeclarations(context: TransformationContext) { input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type) + ensureType(input, input.type), )); } case SyntaxKind.CallSignature: { @@ -1265,7 +1276,7 @@ export function transformDeclarations(context: TransformationContext) { input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type) + ensureType(input, input.type), )); } case SyntaxKind.IndexSignature: { @@ -1273,7 +1284,7 @@ export function transformDeclarations(context: TransformationContext) { input, ensureModifiers(input), updateParamsList(input, input.parameters), - visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) + visitNode(input.type, visitDeclarationSubtree, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword), )); } case SyntaxKind.VariableDeclaration: { @@ -1320,10 +1331,11 @@ export function transformDeclarations(context: TransformationContext) { input.assertions, input.qualifier, visitNodes(input.typeArguments, visitDeclarationSubtree, isTypeNode), - input.isTypeOf + input.isTypeOf, )); } - default: Debug.assertNever(input, `Attempted to process unhandled node kind: ${Debug.formatSyntaxKind((input as Node).kind)}`); + default: + Debug.assertNever(input, `Attempted to process unhandled node kind: ${Debug.formatSyntaxKind((input as Node).kind)}`); } } @@ -1378,7 +1390,7 @@ export function transformDeclarations(context: TransformationContext) { input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), - getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined + getResolutionModeOverrideForClause(input.assertClause) ? input.assertClause : undefined, ); } case SyntaxKind.ExportAssignment: { @@ -1394,7 +1406,7 @@ export function transformDeclarations(context: TransformationContext) { const newId = factory.createUniqueName("_default", GeneratedIdentifierFlags.Optimistic); getSymbolAccessibilityDiagnostic = () => ({ diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: input + errorNode: input, }); errorFallbackNode = input; const varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); @@ -1429,7 +1441,7 @@ export function transformDeclarations(context: TransformationContext) { node: ModuleDeclaration, modifiers: readonly ModifierLike[] | undefined, name: ModuleName, - body: ModuleBody | undefined + body: ModuleBody | undefined, ) { const updated = factory.updateModuleDeclaration(node, modifiers, name, body); @@ -1441,7 +1453,7 @@ export function transformDeclarations(context: TransformationContext) { updated.modifiers, updated.name, updated.body, - updated.flags | NodeFlags.Namespace + updated.flags | NodeFlags.Namespace, ); setOriginalNode(fixed, updated); @@ -1489,7 +1501,7 @@ export function transformDeclarations(context: TransformationContext) { ensureModifiers(input), input.name, visitNodes(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), - Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)) + Debug.checkDefined(visitNode(input.type, visitDeclarationSubtree, isTypeNode)), )); needsDeclare = previousNeedsDeclare; return clean; @@ -1501,7 +1513,7 @@ export function transformDeclarations(context: TransformationContext) { input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), - visitNodes(input.members, visitDeclarationSubtree, isTypeElement) + visitNodes(input.members, visitDeclarationSubtree, isTypeElement), )); } case SyntaxKind.FunctionDeclaration: { @@ -1514,7 +1526,7 @@ export function transformDeclarations(context: TransformationContext) { ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), - /*body*/ undefined + /*body*/ undefined, )); if (clean && resolver.isExpandoFunctionDeclaration(input) && shouldEmitFunctionProperties(input)) { const props = resolver.getPropertiesOfContainerFunction(input); @@ -1552,7 +1564,7 @@ export function transformDeclarations(context: TransformationContext) { /*isTypeOnly*/ false, factory.createNamedExports(map(exportMappings, ([gen, exp]) => { return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp); - })) + })), )); } const namespaceDecl = factory.createModuleDeclaration(ensureModifiers(input), input.name!, factory.createModuleBlock(declarations), NodeFlags.Namespace); @@ -1569,20 +1581,20 @@ export function transformDeclarations(context: TransformationContext) { clean.typeParameters, clean.parameters, clean.type, - /*body*/ undefined + /*body*/ undefined, ); const namespaceDeclaration = factory.updateModuleDeclaration( namespaceDecl, modifiers, namespaceDecl.name, - namespaceDecl.body + namespaceDecl.body, ); const exportDefaultDeclaration = factory.createExportAssignment( /*modifiers*/ undefined, /*isExportEquals*/ false, - namespaceDecl.name + namespaceDecl.name, ); if (isSourceFile(input.parent)) { @@ -1631,7 +1643,7 @@ export function transformDeclarations(context: TransformationContext) { input, mods, isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, - body + body, )); } else { @@ -1647,7 +1659,7 @@ export function transformDeclarations(context: TransformationContext) { input, mods, input.name, - body as ModuleBody + body as ModuleBody, )); } } @@ -1660,16 +1672,20 @@ export function transformDeclarations(context: TransformationContext) { let parameterProperties: readonly PropertyDeclaration[] | undefined; if (ctor) { const oldDiag = getSymbolAccessibilityDiagnostic; - parameterProperties = compact(flatMap(ctor.parameters, (param) => { + parameterProperties = compact(flatMap(ctor.parameters, param => { if (!hasSyntacticModifier(param, ModifierFlags.ParameterPropertyModifier) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === SyntaxKind.Identifier) { - return preserveJsDoc(factory.createPropertyDeclaration( - ensureModifiers(param), - param.name, - param.questionToken, - ensureType(param, param.type), - ensureNoInitializer(param)), param); + return preserveJsDoc( + factory.createPropertyDeclaration( + ensureModifiers(param), + param.name, + param.questionToken, + ensureType(param, param.type), + ensureNoInitializer(param), + ), + param, + ); } else { // Pattern - this is currently an error, but we emit declarations for it somewhat correctly @@ -1689,7 +1705,7 @@ export function transformDeclarations(context: TransformationContext) { elem.name as Identifier, /*questionOrExclamationToken*/ undefined, ensureType(elem, /*type*/ undefined), - /*initializer*/ undefined + /*initializer*/ undefined, )); } return elems; @@ -1707,8 +1723,8 @@ export function transformDeclarations(context: TransformationContext) { factory.createPrivateIdentifier("#private"), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined - ) + /*initializer*/ undefined, + ), ] : undefined; const memberNodes = concatenate(concatenate(privateIdentifier, parameterProperties), visitNodes(input.members, visitDeclarationSubtree, isClassElement)); const members = factory.createNodeArray(memberNodes); @@ -1722,7 +1738,7 @@ export function transformDeclarations(context: TransformationContext) { getSymbolAccessibilityDiagnostic = () => ({ diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause, - typeName: input.name + typeName: input.name, }); const varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); const statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(SyntaxKind.DeclareKeyword)] : [], factory.createVariableDeclarationList([varDecl], NodeFlags.Const)); @@ -1736,14 +1752,17 @@ export function transformDeclarations(context: TransformationContext) { } return factory.updateHeritageClause(clause, visitNodes(factory.createNodeArray(filter(clause.types, t => isEntityNameExpression(t.expression) || t.expression.kind === SyntaxKind.NullKeyword)), visitDeclarationSubtree, isExpressionWithTypeArguments)); })); - return [statement, cleanup(factory.updateClassDeclaration( - input, - modifiers, - input.name, - typeParameters, - heritageClauses, - members - ))!]; // TODO: GH#18217 + return [ + statement, + cleanup(factory.updateClassDeclaration( + input, + modifiers, + input.name, + typeParameters, + heritageClauses, + members, + ))!, + ]; // TODO: GH#18217 } else { const heritageClauses = transformHeritageClauses(input.heritageClauses); @@ -1753,7 +1772,7 @@ export function transformDeclarations(context: TransformationContext) { input.name, typeParameters, heritageClauses, - members + members, )); } } @@ -1761,19 +1780,24 @@ export function transformDeclarations(context: TransformationContext) { return cleanup(transformVariableStatement(input)); } case SyntaxKind.EnumDeclaration: { - return cleanup(factory.updateEnumDeclaration(input, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(mapDefined(input.members, m => { - if (shouldStripInternal(m)) return; - // Rewrite enum values to their constants, if available - const constValue = resolver.getConstantValue(m); - const newInitializer = constValue === undefined - ? undefined - : typeof constValue === "string" - ? factory.createStringLiteral(constValue) - : constValue < 0 - ? factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(constValue))) - : factory.createNumericLiteral(constValue); - return preserveJsDoc(factory.updateEnumMember(m, m.name, newInitializer), m); - })))); + return cleanup(factory.updateEnumDeclaration( + input, + factory.createNodeArray(ensureModifiers(input)), + input.name, + factory.createNodeArray(mapDefined(input.members, m => { + if (shouldStripInternal(m)) return; + // Rewrite enum values to their constants, if available + const constValue = resolver.getConstantValue(m); + const newInitializer = constValue === undefined + ? undefined + : typeof constValue === "string" + ? factory.createStringLiteral(constValue) + : constValue < 0 + ? factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(constValue))) + : factory.createNumericLiteral(constValue); + return preserveJsDoc(factory.updateEnumMember(m, m.name, newInitializer), m); + })), + )); } } // Anything left unhandled is an error, so this should be unreachable @@ -1901,9 +1925,20 @@ export function transformDeclarations(context: TransformationContext) { } function transformHeritageClauses(nodes: NodeArray | undefined) { - return factory.createNodeArray(filter(map(nodes, clause => factory.updateHeritageClause(clause, visitNodes(factory.createNodeArray(filter(clause.types, t => { - return isEntityNameExpression(t.expression) || (clause.token === SyntaxKind.ExtendsKeyword && t.expression.kind === SyntaxKind.NullKeyword); - })), visitDeclarationSubtree, isExpressionWithTypeArguments))), clause => clause.types && !!clause.types.length)); + return factory.createNodeArray(filter( + map(nodes, clause => + factory.updateHeritageClause( + clause, + visitNodes( + factory.createNodeArray(filter(clause.types, t => { + return isEntityNameExpression(t.expression) || (clause.token === SyntaxKind.ExtendsKeyword && t.expression.kind === SyntaxKind.NullKeyword); + })), + visitDeclarationSubtree, + isExpressionWithTypeArguments, + ), + )), + clause => clause.types && !!clause.types.length, + )); } } @@ -1937,8 +1972,8 @@ function getTypeAnnotationFromAccessor(accessor: AccessorDeclaration): TypeNode return accessor.kind === SyntaxKind.GetAccessor ? accessor.type // Getter - return type : accessor.parameters.length > 0 - ? accessor.parameters[0].type // Setter parameter type - : undefined; + ? accessor.parameters[0].type // Setter parameter type + : undefined; } } diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 2e3154aa7f710..09c388378bd5c 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -66,7 +66,7 @@ import { } from "../../_namespaces/ts"; /** @internal */ -export type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => (SymbolAccessibilityDiagnostic | undefined); +export type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic | undefined; /** @internal */ export interface SymbolAccessibilityDiagnostic { @@ -144,7 +144,7 @@ export function createGetSymbolAccessibilityDiagnosticForNodeName(node: Declarat return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name + typeName: (node as NamedDeclaration).name, } : undefined; } @@ -175,7 +175,7 @@ export function createGetSymbolAccessibilityDiagnosticForNodeName(node: Declarat return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name + typeName: (node as NamedDeclaration).name, } : undefined; } @@ -245,8 +245,10 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression || node.kind === SyntaxKind.BinaryExpression || node.kind === SyntaxKind.PropertySignature || - (node.kind === SyntaxKind.Parameter && hasSyntacticModifier(node.parent, ModifierFlags.Private))) { + else if ( + node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression || node.kind === SyntaxKind.BinaryExpression || node.kind === SyntaxKind.PropertySignature || + (node.kind === SyntaxKind.Parameter && hasSyntacticModifier(node.parent, ModifierFlags.Private)) + ) { // TODO(jfreeman): Deal with computed properties in error reporting. if (isStatic(node)) { return symbolAccessibilityResult.errorModuleName ? @@ -276,7 +278,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name + typeName: (node as NamedDeclaration).name, } : undefined; } @@ -315,7 +317,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return { diagnosticMessage, errorNode: (node as NamedDeclaration).name!, - typeName: (node as NamedDeclaration).name + typeName: (node as NamedDeclaration).name, }; } @@ -381,7 +383,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return { diagnosticMessage, - errorNode: (node as NamedDeclaration).name || node + errorNode: (node as NamedDeclaration).name || node, }; } @@ -390,7 +392,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name + typeName: (node as NamedDeclaration).name, } : undefined; } @@ -523,7 +525,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name + typeName: (node as NamedDeclaration).name, }; } @@ -534,8 +536,8 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD // Class or Interface implemented/extended is inaccessible diagnosticMessage = isHeritageClause(node.parent) && node.parent.token === SyntaxKind.ImplementsKeyword ? Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : - node.parent.parent.name ? Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 : - Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0; + node.parent.parent.name ? Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 : + Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0; } else { // interface is inaccessible @@ -545,7 +547,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return { diagnosticMessage, errorNode: node, - typeName: getNameOfDeclaration(node.parent.parent as Declaration) + typeName: getNameOfDeclaration(node.parent.parent as Declaration), }; } @@ -553,7 +555,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return { diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, - typeName: (node as NamedDeclaration).name + typeName: (node as NamedDeclaration).name, }; } diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index 27a991d0f3402..1a3b93e8b77fa 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -97,11 +97,12 @@ export const enum FlattenLevel { */ export function flattenDestructuringAssignment( node: VariableDeclaration | DestructuringAssignment, - visitor: ((node: Node) => VisitResult), + visitor: (node: Node) => VisitResult, context: TransformationContext, level: FlattenLevel, needsValue?: boolean, - createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression): Expression { + createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression, +): Expression { let location: TextRange = node; let value: Expression | undefined; if (isDestructuringAssignment(node)) { @@ -128,15 +129,17 @@ export function flattenDestructuringAssignment( createArrayBindingOrAssignmentPattern: elements => makeArrayAssignmentPattern(context.factory, elements), createObjectBindingOrAssignmentPattern: elements => makeObjectAssignmentPattern(context.factory, elements), createArrayBindingOrAssignmentElement: makeAssignmentElement, - visitor + visitor, }; if (value) { value = visitNode(value, visitor, isExpression); Debug.assert(value); - if (isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || - bindingOrAssignmentElementContainsNonLiteralComputedName(node)) { + if ( + isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node) + ) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); @@ -183,7 +186,7 @@ export function flattenDestructuringAssignment( ? createAssignmentCallback(target as Identifier, value, location) : setTextRange( context.factory.createAssignment(Debug.checkDefined(visitNode(target as Expression, visitor, isExpression)), value), - location + location, ); expression.original = original; emitExpression(expression); @@ -244,9 +247,10 @@ export function flattenDestructuringBinding( level: FlattenLevel, rval?: Expression, hoistTempVariables = false, - skipInitializer?: boolean): VariableDeclaration[] { + skipInitializer?: boolean, +): VariableDeclaration[] { let pendingExpressions: Expression[] | undefined; - const pendingDeclarations: { pendingExpressions?: Expression[], name: BindingName, value: Expression, location?: TextRange, original?: Node; }[] = []; + const pendingDeclarations: { pendingExpressions?: Expression[]; name: BindingName; value: Expression; location?: TextRange; original?: Node; }[] = []; const declarations: VariableDeclaration[] = []; const flattenContext: FlattenContext = { context, @@ -258,13 +262,15 @@ export function flattenDestructuringBinding( createArrayBindingOrAssignmentPattern: elements => makeArrayBindingPattern(context.factory, elements), createObjectBindingOrAssignmentPattern: elements => makeObjectBindingPattern(context.factory, elements), createArrayBindingOrAssignmentElement: name => makeBindingElement(context.factory, name), - visitor + visitor, }; if (isVariableDeclaration(node)) { let initializer = getInitializerOfBindingOrAssignmentElement(node); - if (initializer && (isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || - bindingOrAssignmentElementContainsNonLiteralComputedName(node))) { + if ( + initializer && (isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || + bindingOrAssignmentElementContainsNonLiteralComputedName(node)) + ) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. initializer = ensureIdentifier(flattenContext, Debug.checkDefined(visitNode(initializer, flattenContext.visitor, isExpression)), /*reuseIdentifierExpressions*/ false, initializer); @@ -285,7 +291,7 @@ export function flattenDestructuringBinding( const pendingDeclaration = last(pendingDeclarations); pendingDeclaration.pendingExpressions = append( pendingDeclaration.pendingExpressions, - context.factory.createAssignment(temp, pendingDeclaration.value) + context.factory.createAssignment(temp, pendingDeclaration.value), ); addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; @@ -296,7 +302,7 @@ export function flattenDestructuringBinding( name, /*exclamationToken*/ undefined, /*type*/ undefined, - pendingExpressions ? context.factory.inlineExpressions(append(pendingExpressions, value)) : value + pendingExpressions ? context.factory.inlineExpressions(append(pendingExpressions, value)) : value, ); variable.original = original; setTextRange(variable, location); @@ -333,7 +339,8 @@ function flattenBindingOrAssignmentElement( element: BindingOrAssignmentElement, value: Expression | undefined, location: TextRange, - skipInitializer?: boolean) { + skipInitializer?: boolean, +) { const bindingTarget = getTargetOfBindingOrAssignmentElement(element)!; // TODO: GH#18217 if (!skipInitializer) { const initializer = visitNode(getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, isExpression); @@ -392,10 +399,12 @@ function flattenObjectBindingOrAssignmentPattern(flattenContext: FlattenContext, const element = elements[i]; if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { const propertyName = getPropertyNameOfBindingOrAssignmentElement(element)!; - if (flattenContext.level >= FlattenLevel.ObjectRest + if ( + flattenContext.level >= FlattenLevel.ObjectRest && !(element.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread)) && !(getTargetOfBindingOrAssignmentElement(element)!.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread)) - && !isComputedPropertyName(propertyName)) { + && !isComputedPropertyName(propertyName) + ) { bindingElements = append(bindingElements, visitNode(element, flattenContext.visitor, isBindingOrAssignmentElement)); } else { @@ -445,16 +454,18 @@ function flattenArrayBindingOrAssignmentPattern(flattenContext: FlattenContext, value, numElements > 0 && getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) ? undefined - : numElements + : numElements, ), - location + location, ), /*reuseIdentifierExpressions*/ false, - location + location, ); } - else if (numElements !== 1 && (flattenContext.level < FlattenLevel.ObjectRest || numElements === 0) - || every(elements, isOmittedExpression)) { + else if ( + numElements !== 1 && (flattenContext.level < FlattenLevel.ObjectRest || numElements === 0) + || every(elements, isOmittedExpression) + ) { // For anything other than a single-element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. Additionally, if we have zero elements // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 5e2b895a23498..3cb50067125d5 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -208,7 +208,7 @@ import { VisitResult, VoidExpression, WhileStatement, - YieldExpression + YieldExpression, } from "../_namespaces/ts"; const enum ES2015SubstitutionFlags { @@ -264,19 +264,19 @@ interface LoopOutParameter { const enum LoopOutParameterFlags { None = 0, - Body = 1 << 0, // Modified in the body of the iteration statement - Initializer = 1 << 1, // Set in the initializer of a ForStatement + Body = 1 << 0, // Modified in the body of the iteration statement + Initializer = 1 << 1, // Set in the initializer of a ForStatement } const enum CopyDirection { ToOriginal, - ToOutParameter + ToOutParameter, } const enum Jump { - Break = 1 << 1, - Continue = 1 << 2, - Return = 1 << 3 + Break = 1 << 1, + Continue = 1 << 2, + Return = 1 << 3, } interface ConvertedLoopState { @@ -360,6 +360,7 @@ interface ConvertedLoopState { type LoopConverter = (node: T, outermostLabeledStatement: LabeledStatement | undefined, convertedLoopBodyStatements: Statement[] | undefined, ancestorFacts: HierarchyFacts) => Statement; // Facts we track as we traverse the tree +// dprint-ignore const enum HierarchyFacts { None = 0, @@ -459,6 +460,7 @@ const enum HierarchyFacts { FunctionSubtreeExcludes = NewTarget | CapturedLexicalThis, } +// dprint-ignore const enum SpreadSegmentKind { None, // Not a spread segment UnpackedSpread, // A spread segment that must be packed (i.e., converting `[...[1, , 2]]` into `[1, undefined, 2]`) @@ -500,7 +502,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile function recordTaggedTemplateString(temp: Identifier) { taggedTemplateStringDeclarations = append( taggedTemplateStringDeclarations, - factory.createVariableDeclaration(temp)); + factory.createVariableDeclaration(temp), + ); } /** @@ -601,7 +604,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile if (isPropertyDeclaration(original) && hasStaticModifier(original)) { const ancestorFacts = enterSubtree( HierarchyFacts.StaticInitializerExcludes, - HierarchyFacts.StaticInitializerIncludes + HierarchyFacts.StaticInitializerIncludes, ); const result = visitorWorker(node, /*expressionResultIsUnused*/ false); exitSubtree(ancestorFacts, HierarchyFacts.FunctionSubtreeExcludes, HierarchyFacts.None); @@ -776,15 +779,15 @@ export function transformES2015(context: TransformationContext): (x: SourceFile addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { statements.push( - factory.createVariableStatement(/*modifiers*/ undefined, - factory.createVariableDeclarationList(taggedTemplateStringDeclarations))); + factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations)), + ); } factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, HierarchyFacts.None, HierarchyFacts.None); return factory.updateSourceFile( node, - setTextRange(factory.createNodeArray(concatenate(prologue, statements)), node.statements) + setTextRange(factory.createNodeArray(concatenate(prologue, statements)), node.statements), ); } @@ -824,10 +827,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createIdentifier("value"), node.expression ? Debug.checkDefined(visitNode(node.expression, visitor, isExpression)) - : factory.createVoidZero() - ) - ] - ) + : factory.createVoidZero(), + ), + ], + ), ); } else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) { @@ -862,10 +865,13 @@ export function transformES2015(context: TransformationContext): (x: SourceFile } } if (node.flags & NodeFlags.IdentifierHasExtendedUnicodeEscape) { - return setOriginalNode(setTextRange( - factory.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), - node - ), node); + return setOriginalNode( + setTextRange( + factory.createIdentifier(unescapeLeadingUnderscores(node.escapedText)), + node, + ), + node, + ); } return node; } @@ -877,8 +883,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement const jump = node.kind === SyntaxKind.BreakStatement ? Jump.Break : Jump.Continue; - const canUseBreakOrContinue = - (node.label && convertedLoopState.labels && convertedLoopState.labels.get(idText(node.label))) || + const canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps! & jump)); if (!canUseBreakOrContinue) { @@ -946,7 +951,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.getLocalName(node, /*allowComments*/ true), /*exclamationToken*/ undefined, /*type*/ undefined, - transformClassLikeDeclarationToExpression(node) + transformClassLikeDeclarationToExpression(node), ); setOriginalNode(variable, node); @@ -1032,7 +1037,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel))] : [], /*type*/ undefined, - transformClassBody(node, extendsClauseElement) + transformClassBody(node, extendsClauseElement), ); // To preserve the behavior of the old emitter, we explicitly indent @@ -1056,8 +1061,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*typeArguments*/ undefined, extendsClauseElement ? [Debug.checkDefined(visitNode(extendsClauseElement.expression, visitor, isExpression))] - : [] - ) + : [], + ), ); addSyntheticLeadingComment(result, SyntaxKind.MultiLineCommentTrivia, "* @class "); return result; @@ -1111,10 +1116,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile statements.push( setTextRange( factory.createExpressionStatement( - emitHelpers().createExtendsHelper(factory.getInternalName(node)) + emitHelpers().createExtendsHelper(factory.getInternalName(node)), ), - /*location*/ extendsClauseElement - ) + /*location*/ extendsClauseElement, + ), ); } } @@ -1139,7 +1144,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ undefined, - transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) + transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), ); setTextRange(constructorFunction, constructor || node); @@ -1198,7 +1203,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile statementOffset: number, superPath: readonly number[], superPathDepth: number, - constructor: ConstructorDeclaration & { body: FunctionBody }, + constructor: ConstructorDeclaration & { body: FunctionBody; }, isDerivedClass: boolean, hasSynthesizedSuper: boolean, isFirstStatement: boolean, @@ -1237,7 +1242,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile constructor, isDerivedClass, hasSynthesizedSuper, - isFirstStatement); + isFirstStatement, + ); const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); @@ -1246,7 +1252,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile superStatement, factory.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock))); + visitNode(superStatement.finallyBlock, visitor, isBlock), + )); } else { const superCall = superStatement && getSuperCallFromStatement(superStatement); @@ -1261,9 +1268,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile } if (isDerivedClass || superCallExpression) { - if (superCallExpression && + if ( + superCallExpression && superStatementIndex === statementsIn.length - 1 && - !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis)) { + !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis) + ) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -1384,7 +1393,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile * @param hasSynthesizedSuper A value indicating whether the constructor starts with a * synthesized `super` call. */ - function transformConstructorBody(constructor: ConstructorDeclaration & { body: FunctionBody } | undefined, node: ClassDeclaration | ClassExpression, extendsClauseElement: ExpressionWithTypeArguments | undefined, hasSynthesizedSuper: boolean) { + function transformConstructorBody(constructor: ConstructorDeclaration & { body: FunctionBody; } | undefined, node: ClassDeclaration | ClassExpression, extendsClauseElement: ExpressionWithTypeArguments | undefined, hasSynthesizedSuper: boolean) { // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword; @@ -1429,7 +1438,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile constructor, isDerivedClass, hasSynthesizedSuper, - /*isFirstStatement*/ true // NOTE: this will be recalculated inside of transformConstructorBodyWorker + /*isFirstStatement*/ true, // NOTE: this will be recalculated inside of transformConstructorBodyWorker ); // Add parameter defaults at the beginning of the output, with prologue statements @@ -1447,12 +1456,12 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createNodeArray( [ ...prologue, - ...statements - ] + ...statements, + ], ), - /*location*/ constructor.body.statements + /*location*/ constructor.body.statements, ), - /*multiLine*/ true + /*multiLine*/ true, ); setTextRange(body, constructor.body); @@ -1497,15 +1506,15 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createLogicalAnd( factory.createStrictInequality( factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), - factory.createNull() + factory.createNull(), ), factory.createFunctionApplyCall( factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), createActualThis(), factory.createIdentifier("arguments"), - ) + ), ), - createActualThis() + createActualThis(), ); } @@ -1530,11 +1539,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined + /*initializer*/ undefined, ), - /*location*/ node + /*location*/ node, ), - /*original*/ node + /*original*/ node, ); } else if (node.initializer) { @@ -1547,11 +1556,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile node.name, /*questionToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined + /*initializer*/ undefined, ), - /*location*/ node + /*location*/ node, ), - /*original*/ node + /*original*/ node, ); } else { @@ -1621,12 +1630,12 @@ export function transformES2015(context: TransformationContext): (x: SourceFile visitor, context, FlattenLevel.All, - factory.getGeneratedNameForNode(parameter) - ) - ) + factory.getGeneratedNameForNode(parameter), + ), + ), ), - EmitFlags.CustomPrologue - ) + EmitFlags.CustomPrologue, + ), ); return true; } @@ -1637,11 +1646,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createExpressionStatement( factory.createAssignment( factory.getGeneratedNameForNode(parameter), - Debug.checkDefined(visitNode(initializer, visitor, isExpression)) - ) + Debug.checkDefined(visitNode(initializer, visitor, isExpression)), + ), ), - EmitFlags.CustomPrologue - ) + EmitFlags.CustomPrologue, + ), ); return true; } @@ -1669,18 +1678,18 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createAssignment( // TODO(rbuckton): Does this need to be parented? setEmitFlags(setParent(setTextRange(factory.cloneNode(name), name), name.parent), EmitFlags.NoSourceMap), - setEmitFlags(initializer, EmitFlags.NoSourceMap | getEmitFlags(initializer) | EmitFlags.NoComments) + setEmitFlags(initializer, EmitFlags.NoSourceMap | getEmitFlags(initializer) | EmitFlags.NoComments), ), - parameter + parameter, ), - EmitFlags.NoComments - ) - ) + EmitFlags.NoComments, + ), + ), ]), - parameter + parameter, ), - EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments - ) + EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments, + ), ); startOnNewLine(statement); @@ -1738,14 +1747,14 @@ export function transformES2015(context: TransformationContext): (x: SourceFile declarationName, /*exclamationToken*/ undefined, /*type*/ undefined, - factory.createArrayLiteralExpression([]) - ) - ]) + factory.createArrayLiteralExpression([]), + ), + ]), ), - /*location*/ parameter + /*location*/ parameter, ), - EmitFlags.CustomPrologue - ) + EmitFlags.CustomPrologue, + ), ); // for (var _i = restIndex; _i < arguments.length; _i++) { @@ -1754,16 +1763,16 @@ export function transformES2015(context: TransformationContext): (x: SourceFile const forStatement = factory.createForStatement( setTextRange( factory.createVariableDeclarationList([ - factory.createVariableDeclaration(temp, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(restIndex)) + factory.createVariableDeclaration(temp, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(restIndex)), ]), - parameter + parameter, ), setTextRange( factory.createLessThan( temp, - factory.createPropertyAccessExpression(factory.createIdentifier("arguments"), "length") + factory.createPropertyAccessExpression(factory.createIdentifier("arguments"), "length"), ), - parameter + parameter, ), setTextRange(factory.createPostfixIncrement(temp), parameter), factory.createBlock([ @@ -1775,15 +1784,15 @@ export function transformES2015(context: TransformationContext): (x: SourceFile expressionName, restIndex === 0 ? temp - : factory.createSubtract(temp, factory.createNumericLiteral(restIndex)) + : factory.createSubtract(temp, factory.createNumericLiteral(restIndex)), ), - factory.createElementAccessExpression(factory.createIdentifier("arguments"), temp) - ) + factory.createElementAccessExpression(factory.createIdentifier("arguments"), temp), + ), ), - /*location*/ parameter - ) - ) - ]) + /*location*/ parameter, + ), + ), + ]), ); setEmitFlags(forStatement, EmitFlags.CustomPrologue); @@ -1799,12 +1808,12 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*modifiers*/ undefined, factory.createVariableDeclarationList( flattenDestructuringBinding(parameter, visitor, context, FlattenLevel.All, expressionName), - ) + ), ), - parameter + parameter, ), - EmitFlags.CustomPrologue - ) + EmitFlags.CustomPrologue, + ), ); } @@ -1839,8 +1848,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createBinaryExpression( factory.createThis(), SyntaxKind.EqualsToken, - superExpression - ) + superExpression, + ), ); statements.push(assignSuperExpression); setCommentRange(assignSuperExpression, getOriginalNode(superExpression).parent); @@ -1855,9 +1864,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createUniqueName("_this", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), /*exclamationToken*/ undefined, /*type*/ undefined, - initializer - ) - ]) + initializer, + ), + ]), ); setEmitFlags(captureThisStatement, EmitFlags.NoComments | EmitFlags.CustomPrologue); setSourceMapRange(captureThisStatement, node); @@ -1884,7 +1893,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile // should be relatively safe to use. newTarget = factory.createPropertyAccessExpression( setEmitFlags(factory.createThis(), EmitFlags.NoSubstitution), - "constructor" + "constructor", ); break; @@ -1898,16 +1907,16 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createBinaryExpression( setEmitFlags(factory.createThis(), EmitFlags.NoSubstitution), SyntaxKind.InstanceOfKeyword, - factory.getLocalName(node) - ) + factory.getLocalName(node), + ), ), /*questionToken*/ undefined, factory.createPropertyAccessExpression( setEmitFlags(factory.createThis(), EmitFlags.NoSubstitution), - "constructor" + "constructor", ), /*colonToken*/ undefined, - factory.createVoidZero() + factory.createVoidZero(), ); break; @@ -1922,9 +1931,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createUniqueName("_newTarget", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), /*exclamationToken*/ undefined, /*type*/ undefined, - newTarget - ) - ]) + newTarget, + ), + ]), ); setEmitFlags(captureNewTargetStatement, EmitFlags.NoComments | EmitFlags.CustomPrologue); @@ -2079,7 +2088,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile properties.push( factory.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory.createFalse() : factory.createTrue()), - factory.createPropertyAssignment("configurable", factory.createTrue()) + factory.createPropertyAssignment("configurable", factory.createTrue()), ); const call = factory.createCallExpression( @@ -2088,8 +2097,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile [ target, propertyName, - factory.createObjectLiteralExpression(properties, /*multiLine*/ true) - ] + factory.createObjectLiteralExpression(properties, /*multiLine*/ true), + ], ); if (startsOnNewLine) { startOnNewLine(call); @@ -2118,7 +2127,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - transformFunctionBody(node) + transformFunctionBody(node), ); setTextRange(func, node); setOriginalNode(func, node); @@ -2159,7 +2168,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, parameters, /*type*/ undefined, - body + body, ); } @@ -2188,7 +2197,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, parameters, /*type*/ undefined, - body + body, ); } @@ -2222,11 +2231,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, parameters, /*type*/ undefined, - body + body, ), - location + location, ), - /*original*/ node + /*original*/ node, ); } @@ -2378,14 +2387,15 @@ export function transformES2015(context: TransformationContext): (x: SourceFile visitor, context, FlattenLevel.All, - !expressionResultIsUnused); + !expressionResultIsUnused, + ); } if (node.operatorToken.kind === SyntaxKind.CommaToken) { return factory.updateBinaryExpression( node, Debug.checkDefined(visitNode(node.left, visitorWithUnusedExpressionResult, isExpression)), node.operatorToken, - Debug.checkDefined(visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, isExpression)) + Debug.checkDefined(visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, isExpression)), ); } return visitEachChild(node, visitor, context); @@ -2434,7 +2444,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile decl, visitor, context, - FlattenLevel.All + FlattenLevel.All, ); } else { @@ -2472,9 +2482,13 @@ export function transformES2015(context: TransformationContext): (x: SourceFile enableSubstitutionsForBlockScopedBindings(); } - const declarations = visitNodes(node.declarations, node.flags & NodeFlags.Let - ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration, isVariableDeclaration); + const declarations = visitNodes( + node.declarations, + node.flags & NodeFlags.Let + ? visitVariableDeclarationInLetDeclarationList + : visitVariableDeclaration, + isVariableDeclaration, + ); const declarationList = factory.createVariableDeclarationList(declarations); setOriginalNode(declarationList, node); @@ -2483,8 +2497,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & TransformFlags.ContainsBindingPattern - && (isBindingPattern(node.declarations[0].name) || isBindingPattern(last(node.declarations).name))) { + if ( + node.transformFlags & TransformFlags.ContainsBindingPattern + && (isBindingPattern(node.declarations[0].name) || isBindingPattern(last(node.declarations).name)) + ) { setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -2554,14 +2570,12 @@ export function transformES2015(context: TransformationContext): (x: SourceFile const flags = resolver.getNodeCheckFlags(node); const isCapturedInFunction = flags & NodeCheckFlags.CapturedBlockScopedBinding; const isDeclaredInLoop = flags & NodeCheckFlags.BlockScopedBindingInLoop; - const emittedAsTopLevel = - (hierarchyFacts & HierarchyFacts.TopLevel) !== 0 + const emittedAsTopLevel = (hierarchyFacts & HierarchyFacts.TopLevel) !== 0 || (isCapturedInFunction && isDeclaredInLoop && (hierarchyFacts & HierarchyFacts.IterationStatementBlock) !== 0); - const emitExplicitInitializer = - !emittedAsTopLevel + const emitExplicitInitializer = !emittedAsTopLevel && (hierarchyFacts & HierarchyFacts.ForInOrForOfStatement) === 0 && (!resolver.isDeclarationWithCollidingName(node) || (isDeclaredInLoop @@ -2607,7 +2621,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile context, FlattenLevel.All, /*rval*/ undefined, - (ancestorFacts & HierarchyFacts.ExportedVariableStatement) !== 0 + (ancestorFacts & HierarchyFacts.ExportedVariableStatement) !== 0, ); } else { @@ -2662,7 +2676,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile HierarchyFacts.DoOrWhileStatementExcludes, HierarchyFacts.DoOrWhileStatementIncludes, node, - outermostLabeledStatement); + outermostLabeledStatement, + ); } function visitForStatement(node: ForStatement, outermostLabeledStatement: LabeledStatement | undefined) { @@ -2670,7 +2685,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile HierarchyFacts.ForStatementExcludes, HierarchyFacts.ForStatementIncludes, node, - outermostLabeledStatement); + outermostLabeledStatement, + ); } function visitEachChildOfForStatement(node: ForStatement) { @@ -2679,7 +2695,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), - Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory.liftToBlock)) + Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory.liftToBlock)), ); } @@ -2688,7 +2704,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile HierarchyFacts.ForInOrForOfStatementExcludes, HierarchyFacts.ForInOrForOfStatementIncludes, node, - outermostLabeledStatement); + outermostLabeledStatement, + ); } function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult { @@ -2697,7 +2714,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile HierarchyFacts.ForInOrForOfStatementIncludes, node, outermostLabeledStatement, - compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray); + compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray, + ); } function convertForOfStatementHead(node: ForOfStatement, boundValue: Expression, convertedLoopBodyStatements: Statement[] | undefined) { @@ -2717,7 +2735,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile visitor, context, FlattenLevel.All, - boundValue + boundValue, ); const declarationList = setTextRange(factory.createVariableDeclarationList(declarations), node.initializer); @@ -2730,8 +2748,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile statements.push( factory.createVariableStatement( /*modifiers*/ undefined, - declarationList - ) + declarationList, + ), ); } else { @@ -2748,16 +2766,16 @@ export function transformES2015(context: TransformationContext): (x: SourceFile firstOriginalDeclaration ? firstOriginalDeclaration.name : factory.createTempVariable(/*recordTempVariable*/ undefined), /*exclamationToken*/ undefined, /*type*/ undefined, - boundValue - ) + boundValue, + ), ]), - moveRangePos(initializer, -1) + moveRangePos(initializer, -1), ), - initializer - ) + initializer, + ), ), - moveRangeEnd(initializer, -1) - ) + moveRangeEnd(initializer, -1), + ), ); } } @@ -2794,9 +2812,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile return setEmitFlags( factory.createBlock( factory.createNodeArray(statements), - /*multiLine*/ true + /*multiLine*/ true, ), - EmitFlags.NoSourceMap | EmitFlags.NoTokenSourceMaps + EmitFlags.NoSourceMap | EmitFlags.NoTokenSourceMaps, ); } @@ -2842,27 +2860,27 @@ export function transformES2015(context: TransformationContext): (x: SourceFile setTextRange( factory.createVariableDeclarationList([ setTextRange(factory.createVariableDeclaration(counter, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(0)), moveRangePos(node.expression, -1)), - setTextRange(factory.createVariableDeclaration(rhsReference, /*exclamationToken*/ undefined, /*type*/ undefined, expression), node.expression) + setTextRange(factory.createVariableDeclaration(rhsReference, /*exclamationToken*/ undefined, /*type*/ undefined, expression), node.expression), ]), - node.expression + node.expression, ), - EmitFlags.NoHoisting + EmitFlags.NoHoisting, ), /*condition*/ setTextRange( factory.createLessThan( counter, - factory.createPropertyAccessExpression(rhsReference, "length") + factory.createPropertyAccessExpression(rhsReference, "length"), ), - node.expression + node.expression, ), /*incrementor*/ setTextRange(factory.createPostfixIncrement(counter), node.expression), /*statement*/ convertForOfStatementHead( node, factory.createElementAccessExpression(rhsReference, counter), - convertedLoopBodyStatements - ) + convertedLoopBodyStatements, + ), ), - /*location*/ node + /*location*/ node, ); // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. @@ -2897,23 +2915,23 @@ export function transformES2015(context: TransformationContext): (x: SourceFile setTextRange( factory.createVariableDeclarationList([ setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), - factory.createVariableDeclaration(result, /*exclamationToken*/ undefined, /*type*/ undefined, next) + factory.createVariableDeclaration(result, /*exclamationToken*/ undefined, /*type*/ undefined, next), ]), - node.expression + node.expression, ), - EmitFlags.NoHoisting + EmitFlags.NoHoisting, ), /*condition*/ factory.createLogicalNot(factory.createPropertyAccessExpression(result, "done")), /*incrementor*/ factory.createAssignment(result, next), /*statement*/ convertForOfStatementHead( node, factory.createPropertyAccessExpression(result, "value"), - convertedLoopBodyStatements - ) + convertedLoopBodyStatements, + ), ), - /*location*/ node + /*location*/ node, ), - EmitFlags.NoTokenTrailingSourceMaps + EmitFlags.NoTokenTrailingSourceMaps, ); return factory.createTryStatement( @@ -2921,23 +2939,24 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.restoreEnclosingLabel( forStatement, outermostLabeledStatement, - convertedLoopState && resetLabel - ) + convertedLoopState && resetLabel, + ), ]), - factory.createCatchClause(factory.createVariableDeclaration(catchVariable), + factory.createCatchClause( + factory.createVariableDeclaration(catchVariable), setEmitFlags( factory.createBlock([ factory.createExpressionStatement( factory.createAssignment( errorRecord, factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("error", catchVariable) - ]) - ) - ) + factory.createPropertyAssignment("error", catchVariable), + ]), + ), + ), ]), - EmitFlags.SingleLine - ) + EmitFlags.SingleLine, + ), ), factory.createBlock([ factory.createTryStatement( @@ -2948,19 +2967,19 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createLogicalAnd( result, factory.createLogicalNot( - factory.createPropertyAccessExpression(result, "done") - ) + factory.createPropertyAccessExpression(result, "done"), + ), ), factory.createAssignment( returnMethod, - factory.createPropertyAccessExpression(iterator, "return") - ) + factory.createPropertyAccessExpression(iterator, "return"), + ), ), factory.createExpressionStatement( - factory.createFunctionCallCall(returnMethod, iterator, []) - ) + factory.createFunctionCallCall(returnMethod, iterator, []), + ), ), - EmitFlags.SingleLine + EmitFlags.SingleLine, ), ]), /*catchClause*/ undefined, @@ -2970,16 +2989,16 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createIfStatement( errorRecord, factory.createThrowStatement( - factory.createPropertyAccessExpression(errorRecord, "error") - ) + factory.createPropertyAccessExpression(errorRecord, "error"), + ), ), - EmitFlags.SingleLine - ) + EmitFlags.SingleLine, + ), ]), - EmitFlags.SingleLine - ) - ) - ]) + EmitFlags.SingleLine, + ), + ), + ]), ); } @@ -2996,9 +3015,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile let numInitialProperties = -1, hasComputed = false; for (let i = 0; i < properties.length; i++) { const property = properties[i]; - if ((property.transformFlags & TransformFlags.ContainsYield && - hierarchyFacts & HierarchyFacts.AsyncFunctionBody) - || (hasComputed = Debug.checkDefined(property.name).kind === SyntaxKind.ComputedPropertyName)) { + if ( + (property.transformFlags & TransformFlags.ContainsYield && + hierarchyFacts & HierarchyFacts.AsyncFunctionBody) + || (hasComputed = Debug.checkDefined(property.name).kind === SyntaxKind.ComputedPropertyName) + ) { numInitialProperties = i; break; } @@ -3019,10 +3040,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile setEmitFlags( factory.createObjectLiteralExpression( visitNodes(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), - node.multiLine + node.multiLine, ), - hasComputed ? EmitFlags.Indented : 0 - ) + hasComputed ? EmitFlags.Indented : 0, + ), ); if (node.multiLine) { @@ -3115,7 +3136,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile : factory.restoreEnclosingLabel( isForStatement(node) ? visitEachChildOfForStatement(node) : visitEachChild(node, visitor, context), outermostLabeledStatement, - convertedLoopState && resetLabel); + convertedLoopState && resetLabel, + ); if (convertedLoopState) { convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; @@ -3164,12 +3186,18 @@ export function transformES2015(context: TransformationContext): (x: SourceFile function convertIterationStatementCore(node: IterationStatement, initializerFunction: IterationStatementPartFunction | undefined, convertedLoopBody: Statement) { switch (node.kind) { - case SyntaxKind.ForStatement: return convertForStatement(node as ForStatement, initializerFunction, convertedLoopBody); - case SyntaxKind.ForInStatement: return convertForInStatement(node as ForInStatement, convertedLoopBody); - case SyntaxKind.ForOfStatement: return convertForOfStatement(node as ForOfStatement, convertedLoopBody); - case SyntaxKind.DoStatement: return convertDoStatement(node as DoStatement, convertedLoopBody); - case SyntaxKind.WhileStatement: return convertWhileStatement(node as WhileStatement, convertedLoopBody); - default: return Debug.failBadSyntaxKind(node, "IterationStatement expected"); + case SyntaxKind.ForStatement: + return convertForStatement(node as ForStatement, initializerFunction, convertedLoopBody); + case SyntaxKind.ForInStatement: + return convertForInStatement(node as ForInStatement, convertedLoopBody); + case SyntaxKind.ForOfStatement: + return convertForOfStatement(node as ForOfStatement, convertedLoopBody); + case SyntaxKind.DoStatement: + return convertDoStatement(node as DoStatement, convertedLoopBody); + case SyntaxKind.WhileStatement: + return convertWhileStatement(node as WhileStatement, convertedLoopBody); + default: + return Debug.failBadSyntaxKind(node, "IterationStatement expected"); } } @@ -3181,7 +3209,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitorWithUnusedExpressionResult, isForInitializer), visitNode(shouldConvertCondition ? undefined : node.condition, visitor, isExpression), visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitorWithUnusedExpressionResult, isExpression), - convertedLoopBody + convertedLoopBody, ); } @@ -3191,7 +3219,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*awaitModifier*/ undefined, Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - convertedLoopBody); + convertedLoopBody, + ); } function convertForInStatement(node: ForInStatement, convertedLoopBody: Statement) { @@ -3199,21 +3228,24 @@ export function transformES2015(context: TransformationContext): (x: SourceFile node, Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - convertedLoopBody); + convertedLoopBody, + ); } function convertDoStatement(node: DoStatement, convertedLoopBody: Statement) { return factory.updateDoStatement( node, convertedLoopBody, - Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + ); } function convertWhileStatement(node: WhileStatement, convertedLoopBody: Statement) { return factory.updateWhileStatement( node, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - convertedLoopBody); + convertedLoopBody, + ); } function createConvertedLoopState(node: IterationStatement) { @@ -3281,8 +3313,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile state.argumentsName, /*exclamationToken*/ undefined, /*type*/ undefined, - factory.createIdentifier("arguments") - ) + factory.createIdentifier("arguments"), + ), ); } } @@ -3303,8 +3335,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile state.thisName, /*exclamationToken*/ undefined, /*type*/ undefined, - factory.createIdentifier("this") - ) + factory.createIdentifier("this"), + ), ); } } @@ -3347,7 +3379,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile if (extraVariableDeclarations) { statements.push(factory.createVariableStatement( /*modifiers*/ undefined, - factory.createVariableDeclarationList(extraVariableDeclarations) + factory.createVariableDeclarationList(extraVariableDeclarations), )); } } @@ -3421,15 +3453,15 @@ export function transformES2015(context: TransformationContext): (x: SourceFile Debug.checkDefined(visitNode( factory.createBlock(statements, /*multiLine*/ true), visitor, - isBlock - )) + isBlock, + )), ), - emitFlags - ) - ) + emitFlags, + ), + ), ]), - EmitFlags.NoHoisting - ) + EmitFlags.NoHoisting, + ), ); const part = factory.createVariableDeclarationList(map(currentState.loopOutParameters, createOutVariable)); @@ -3493,20 +3525,20 @@ export function transformES2015(context: TransformationContext): (x: SourceFile statements.push(factory.createIfStatement( currentState.conditionVariable, factory.createExpressionStatement(Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression))), - factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue())) + factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue())), )); } else { statements.push(factory.createIfStatement( factory.createLogicalNot(currentState.conditionVariable), - factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue())) + factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue())), )); } if (shouldConvertConditionOfForStatement(node)) { statements.push(factory.createIfStatement( factory.createPrefixUnaryExpression(SyntaxKind.ExclamationToken, Debug.checkDefined(visitNode(node.condition, visitor, isExpression))), - Debug.checkDefined(visitNode(factory.createBreakStatement(), visitor, isStatement)) + Debug.checkDefined(visitNode(factory.createBreakStatement(), visitor, isStatement)), )); } } @@ -3546,34 +3578,33 @@ export function transformES2015(context: TransformationContext): (x: SourceFile // _loop_1(i); // } - const functionDeclaration = - factory.createVariableStatement( - /*modifiers*/ undefined, - setEmitFlags( - factory.createVariableDeclarationList( - [ - factory.createVariableDeclaration( - functionName, - /*exclamationToken*/ undefined, - /*type*/ undefined, - setEmitFlags( - factory.createFunctionExpression( - /*modifiers*/ undefined, - containsYield ? factory.createToken(SyntaxKind.AsteriskToken) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - currentState.loopParameters, - /*type*/ undefined, - loopBody - ), - emitFlags - ) - ) - ] - ), - EmitFlags.NoHoisting - ) - ); + const functionDeclaration = factory.createVariableStatement( + /*modifiers*/ undefined, + setEmitFlags( + factory.createVariableDeclarationList( + [ + factory.createVariableDeclaration( + functionName, + /*exclamationToken*/ undefined, + /*type*/ undefined, + setEmitFlags( + factory.createFunctionExpression( + /*modifiers*/ undefined, + containsYield ? factory.createToken(SyntaxKind.AsteriskToken) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + currentState.loopParameters, + /*type*/ undefined, + loopBody, + ), + emitFlags, + ), + ), + ], + ), + EmitFlags.NoHoisting, + ), + ); const part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); return { functionName, containsYield, functionDeclaration, part }; @@ -3598,20 +3629,18 @@ export function transformES2015(context: TransformationContext): (x: SourceFile const callResult = containsYield ? factory.createYieldExpression( factory.createToken(SyntaxKind.AsteriskToken), - setEmitFlags(call, EmitFlags.Iterator) + setEmitFlags(call, EmitFlags.Iterator), ) : call; return factory.createExpressionStatement(callResult); } function generateCallToConvertedLoop(loopFunctionExpressionName: Identifier, state: ConvertedLoopState, outerState: ConvertedLoopState | undefined, containsYield: boolean): Statement[] { - const statements: Statement[] = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; // NOTE: if loop uses only 'continue' it still will be emitted as simple loop - const isSimpleLoop = - !(state.nonLocalJumps! & ~Jump.Continue) && + const isSimpleLoop = !(state.nonLocalJumps! & ~Jump.Continue) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; @@ -3619,7 +3648,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile const callResult = containsYield ? factory.createYieldExpression( factory.createToken(SyntaxKind.AsteriskToken), - setEmitFlags(call, EmitFlags.Iterator) + setEmitFlags(call, EmitFlags.Iterator), ) : call; if (isSimpleLoop) { @@ -3631,8 +3660,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile const stateVariable = factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList( - [factory.createVariableDeclaration(loopResultName, /*exclamationToken*/ undefined, /*type*/ undefined, callResult)] - ) + [factory.createVariableDeclaration(loopResultName, /*exclamationToken*/ undefined, /*type*/ undefined, callResult)], + ), ); statements.push(stateVariable); copyOutParameters(state.loopOutParameters, LoopOutParameterFlags.Body, CopyDirection.ToOriginal, statements); @@ -3649,8 +3678,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile statements.push( factory.createIfStatement( factory.createTypeCheck(loopResultName, "object"), - returnStatement - ) + returnStatement, + ), ); } @@ -3659,10 +3688,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createIfStatement( factory.createStrictEquality( loopResultName, - factory.createStringLiteral("break") + factory.createStringLiteral("break"), ), - factory.createBreakStatement() - ) + factory.createBreakStatement(), + ), ); } @@ -3673,8 +3702,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile statements.push( factory.createSwitchStatement( loopResultName, - factory.createCaseBlock(caseClauses) - ) + factory.createCaseBlock(caseClauses), + ), ); } } @@ -3739,8 +3768,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile if (container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { flags |= LoopOutParameterFlags.Initializer; } - if (container.condition && resolver.isBindingCapturedByNode(container.condition, decl) || - container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl)) { + if ( + container.condition && resolver.isBindingCapturedByNode(container.condition, decl) || + container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl) + ) { flags |= LoopOutParameterFlags.Body; } } @@ -3804,9 +3835,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile createMemberAccessForPropertyName( factory, receiver, - Debug.checkDefined(visitNode(property.name, visitor, isPropertyName)) + Debug.checkDefined(visitNode(property.name, visitor, isPropertyName)), ), - Debug.checkDefined(visitNode(property.initializer, visitor, isExpression)) + Debug.checkDefined(visitNode(property.initializer, visitor, isExpression)), ); setTextRange(expression, property); if (startsOnNewLine) { @@ -3827,9 +3858,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile createMemberAccessForPropertyName( factory, receiver, - Debug.checkDefined(visitNode(property.name, visitor, isPropertyName)) + Debug.checkDefined(visitNode(property.name, visitor, isPropertyName)), ), - factory.cloneNode(property.name) + factory.cloneNode(property.name), ); setTextRange(expression, property); if (startsOnNewLine) { @@ -3850,9 +3881,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile createMemberAccessForPropertyName( factory, receiver, - Debug.checkDefined(visitNode(method.name, visitor, isPropertyName)) + Debug.checkDefined(visitNode(method.name, visitor, isPropertyName)), ), - transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container) + transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container), ); setTextRange(expression, method); if (startsOnNewLine) { @@ -3874,7 +3905,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile visitor, context, FlattenLevel.All, - temp + temp, ); const list = factory.createVariableDeclarationList(vars); setTextRange(list, node.variableDeclaration); @@ -3910,9 +3941,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile return setTextRange( factory.createPropertyAssignment( node.name, - functionExpression + functionExpression, ), - /*location*/ node + /*location*/ node, ); } @@ -3949,9 +3980,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile return setTextRange( factory.createPropertyAssignment( node.name, - visitIdentifier(factory.cloneNode(node.name)) + visitIdentifier(factory.cloneNode(node.name)), ), - /*location*/ node + /*location*/ node, ); } @@ -3993,9 +4024,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile } const expression = skipOuterExpressions(node.expression); - if (expression.kind === SyntaxKind.SuperKeyword || + if ( + expression.kind === SyntaxKind.SuperKeyword || isSuperProperty(expression) || - some(node.arguments, isSpreadElement)) { + some(node.arguments, isSpreadElement) + ) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } @@ -4003,7 +4036,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile node, Debug.checkDefined(visitNode(node.expression, callExpressionVisitor, isExpression)), /*typeArguments*/ undefined, - visitNodes(node.arguments, visitor, isExpression) + visitNodes(node.arguments, visitor, isExpression), ); } @@ -4109,9 +4142,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createExpressionStatement( factory.createAssignment( aliasAssignment.left, - cast(variable.name, isIdentifier) - ) - ) + cast(variable.name, isIdentifier), + ), + ), ); } @@ -4137,8 +4170,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile // of the inner wrapper if its expression is not trivially an Identifier. const returnStatement = tryCast(elementAt(funcStatements, classBodyEnd), isReturnStatement); for (const statement of remainingStatements) { - if (isReturnStatement(statement) && returnStatement?.expression && - !isIdentifier(returnStatement.expression)) { + if ( + isReturnStatement(statement) && returnStatement?.expression && + !isIdentifier(returnStatement.expression) + ) { statements.push(returnStatement); } else { @@ -4152,11 +4187,16 @@ export function transformES2015(context: TransformationContext): (x: SourceFile // Recreate any outer parentheses or partially-emitted expressions to preserve source map // and comment locations. - return factory.restoreOuterExpressions(node.expression, - factory.restoreOuterExpressions(variable.initializer, - factory.restoreOuterExpressions(aliasAssignment && aliasAssignment.right, - factory.updateCallExpression(call, - factory.restoreOuterExpressions(call.expression, + return factory.restoreOuterExpressions( + node.expression, + factory.restoreOuterExpressions( + variable.initializer, + factory.restoreOuterExpressions( + aliasAssignment && aliasAssignment.right, + factory.updateCallExpression( + call, + factory.restoreOuterExpressions( + call.expression, factory.updateFunctionExpression( func, /*modifiers*/ undefined, @@ -4167,15 +4207,15 @@ export function transformES2015(context: TransformationContext): (x: SourceFile /*type*/ undefined, factory.updateBlock( func.body, - statements - ) - ) + statements, + ), + ), ), /*typeArguments*/ undefined, - call.arguments - ) - ) - ) + call.arguments, + ), + ), + ), ); } @@ -4186,10 +4226,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile function visitCallExpressionWithPotentialCapturedThisAssignment(node: CallExpression, assignToCapturedThis: boolean): CallExpression | BinaryExpression { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & TransformFlags.ContainsRestOrSpread || + if ( + node.transformFlags & TransformFlags.ContainsRestOrSpread || node.expression.kind === SyntaxKind.SuperKeyword || - isSuperProperty(skipOuterExpressions(node.expression))) { - + isSuperProperty(skipOuterExpressions(node.expression)) + ) { const { target, thisArg } = factory.createCallBinding(node.expression, hoistVariableDeclaration); if (node.expression.kind === SyntaxKind.SuperKeyword) { setEmitFlags(thisArg, EmitFlags.NoSubstitution); @@ -4214,7 +4255,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile resultingCall = factory.createFunctionApplyCall( Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), node.expression.kind === SyntaxKind.SuperKeyword ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), - transformAndSpreadElements(node.arguments, /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false) + transformAndSpreadElements(node.arguments, /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false), ); } else { @@ -4231,18 +4272,17 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createFunctionCallCall( Debug.checkDefined(visitNode(target, callExpressionVisitor, isExpression)), node.expression.kind === SyntaxKind.SuperKeyword ? thisArg : Debug.checkDefined(visitNode(thisArg, visitor, isExpression)), - visitNodes(node.arguments, visitor, isExpression) + visitNodes(node.arguments, visitor, isExpression), ), - node + node, ); } if (node.expression.kind === SyntaxKind.SuperKeyword) { - const initializer = - factory.createLogicalOr( - resultingCall, - createActualThis() - ); + const initializer = factory.createLogicalOr( + resultingCall, + createActualThis(), + ); resultingCall = assignToCapturedThis ? factory.createAssignment(factory.createUniqueName("_this", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), initializer) : initializer; @@ -4272,10 +4312,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile factory.createFunctionApplyCall( Debug.checkDefined(visitNode(target, visitor, isExpression)), thisArg, - transformAndSpreadElements(factory.createNodeArray([factory.createVoidZero(), ...node.arguments!]), /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false) + transformAndSpreadElements(factory.createNodeArray([factory.createVoidZero(), ...node.arguments!]), /*isArgumentList*/ true, /*multiLine*/ false, /*hasTrailingComma*/ false), ), /*typeArguments*/ undefined, - [] + [], ); } return visitEachChild(node, visitor, context); @@ -4329,9 +4369,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile // As we visit each element, we return one of two functions to use as the "key": // - `visitSpanOfSpreads` for one or more contiguous `...` spread expressions, i.e. `...a, ...b` in `[1, 2, ...a, ...b]` // - `visitSpanOfNonSpreads` for one or more contiguous non-spread elements, i.e. `1, 2`, in `[1, 2, ...a, ...b]` - spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) => - visitPartition(partition, multiLine, hasTrailingComma && end === numElements) - ) + spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) => visitPartition(partition, multiLine, hasTrailingComma && end === numElements)), ); if (segments.length === 1) { @@ -4340,17 +4378,18 @@ export function transformES2015(context: TransformationContext): (x: SourceFile // a CallExpression or NewExpression. When using `--downlevelIteration`, we need // to coerce this into an array for use with `apply`, so we will use the code path // that follows instead. - if (isArgumentList && !compilerOptions.downlevelIteration + if ( + isArgumentList && !compilerOptions.downlevelIteration || isPackedArrayLiteral(firstSegment.expression) // see NOTE (above) - || isCallToHelper(firstSegment.expression, "___spreadArray" as __String)) { + || isCallToHelper(firstSegment.expression, "___spreadArray" as __String) + ) { return firstSegment.expression; } } const helpers = emitHelpers(); const startsWithSpread = segments[0].kind !== SpreadSegmentKind.None; - let expression: Expression = - startsWithSpread ? factory.createArrayLiteralExpression() : + let expression: Expression = startsWithSpread ? factory.createArrayLiteralExpression() : segments[0].expression; for (let i = startsWithSpread ? 0 : 1; i < segments.length; i++) { const segment = segments[i]; @@ -4358,7 +4397,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile expression = helpers.createSpreadArrayHelper( expression, segment.expression, - segment.kind === SpreadSegmentKind.UnpackedSpread && !isArgumentList); + segment.kind === SpreadSegmentKind.UnpackedSpread && !isArgumentList, + ); } return expression; } @@ -4395,7 +4435,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile function visitSpanOfNonSpreads(chunk: Expression[], multiLine: boolean, hasTrailingComma: boolean): SpreadSegment { const expression = factory.createArrayLiteralExpression( visitNodes(factory.createNodeArray(chunk, hasTrailingComma), visitor, isExpression), - multiLine); + multiLine, + ); // We do not pack non-spread segments, this is so that `[1, , ...[2, , 3], , 4]` is properly downleveled to // `[1, , 2, undefined, 3, , 4]`. See the NOTE in `transformAndSpreadElements` @@ -4451,7 +4492,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile visitor, currentSourceFile, recordTaggedTemplateString, - ProcessLevel.All + ProcessLevel.All, ); } @@ -4484,9 +4525,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile */ function visitSuperKeyword(isExpressionOfCall: boolean): LeftHandSideExpression { return hierarchyFacts & HierarchyFacts.NonStaticClassElement - && !isExpressionOfCall - ? factory.createPropertyAccessExpression(factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), "prototype") - : factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + && !isExpressionOfCall + ? factory.createPropertyAccessExpression(factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), "prototype") + : factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); } function visitMetaProperty(node: MetaProperty) { @@ -4511,7 +4552,8 @@ export function transformES2015(context: TransformationContext): (x: SourceFile HierarchyFacts.FunctionExcludes, getEmitFlags(node) & EmitFlags.CapturesThis ? HierarchyFacts.FunctionIncludes | HierarchyFacts.CapturesThis - : HierarchyFacts.FunctionIncludes); + : HierarchyFacts.FunctionIncludes, + ); previousOnEmitNode(hint, node, emitCallback); exitSubtree(ancestorFacts, HierarchyFacts.None, HierarchyFacts.None); return; @@ -4666,8 +4708,10 @@ export function transformES2015(context: TransformationContext): (x: SourceFile * @param node The ThisKeyword node. */ function substituteThisKeyword(node: PrimaryExpression): PrimaryExpression { - if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis - && hierarchyFacts & HierarchyFacts.CapturesThis) { + if ( + enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis + && hierarchyFacts & HierarchyFacts.CapturesThis + ) { return setTextRange(factory.createUniqueName("_this", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), node); } return node; diff --git a/src/compiler/transformers/es2016.ts b/src/compiler/transformers/es2016.ts index 33df5b94f0d0b..39d3e05a27d65 100644 --- a/src/compiler/transformers/es2016.ts +++ b/src/compiler/transformers/es2016.ts @@ -21,7 +21,7 @@ import { export function transformES2016(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { const { factory, - hoistVariableDeclaration + hoistVariableDeclaration, } = context; return chainBundle(context, transformSourceFile); @@ -69,16 +69,16 @@ export function transformES2016(context: TransformationContext): (x: SourceFile target = setTextRange( factory.createElementAccessExpression( setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), - setTextRange(factory.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression) + setTextRange(factory.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression), ), - left + left, ); value = setTextRange( factory.createElementAccessExpression( expressionTemp, - argumentExpressionTemp + argumentExpressionTemp, ), - left + left, ); } else if (isPropertyAccessExpression(left)) { @@ -87,16 +87,16 @@ export function transformES2016(context: TransformationContext): (x: SourceFile target = setTextRange( factory.createPropertyAccessExpression( setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), - left.name + left.name, ), - left + left, ); value = setTextRange( factory.createPropertyAccessExpression( expressionTemp, - left.name + left.name, ), - left + left, ); } else { @@ -107,9 +107,9 @@ export function transformES2016(context: TransformationContext): (x: SourceFile return setTextRange( factory.createAssignment( target, - setTextRange(factory.createGlobalMethodCall("Math", "pow", [value, right]), node) + setTextRange(factory.createGlobalMethodCall("Math", "pow", [value, right]), node), ), - node + node, ); } diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 1c1a2e9f45f23..d30b25e2a4580 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -102,13 +102,13 @@ type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclarat const enum ES2017SubstitutionFlags { /** Enables substitutions for async methods with `super` calls. */ - AsyncMethodsWithSuper = 1 << 0 + AsyncMethodsWithSuper = 1 << 0, } const enum ContextFlags { None = 0, NonTopLevel = 1 << 0, - HasLexicalThis = 1 << 1 + HasLexicalThis = 1 << 1, } /** @internal */ @@ -118,7 +118,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile getEmitHelperFactory: emitHelpers, resumeLexicalEnvironment, endLexicalEnvironment, - hoistVariableDeclaration + hoistVariableDeclaration, } = context; const resolver = context.getEmitResolver(); @@ -327,8 +327,8 @@ export function transformES2017(context: TransformationContext): (x: SourceFile isVariableDeclarationListWithCollidingName(node.initializer) ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)! : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, asyncBodyVisitor, context) + Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + visitIterationBody(node.statement, asyncBodyVisitor, context), ); } @@ -340,7 +340,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)! : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, asyncBodyVisitor, context) + visitIterationBody(node.statement, asyncBodyVisitor, context), ); } @@ -353,7 +353,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile : visitNode(node.initializer, visitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), - visitIterationBody(node.statement, asyncBodyVisitor, context) + visitIterationBody(node.statement, asyncBodyVisitor, context), ); } @@ -373,11 +373,11 @@ export function transformES2017(context: TransformationContext): (x: SourceFile setTextRange( factory.createYieldExpression( /*asteriskToken*/ undefined, - visitNode(node.expression, visitor, isExpression) + visitNode(node.expression, visitor, isExpression), ), - node + node, ), - node + node, ); } @@ -386,7 +386,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile node, visitNodes(node.modifiers, visitor, isModifier), visitParameterList(node.parameters, visitor, context), - transformMethodBody(node) + transformMethodBody(node), ); } @@ -410,7 +410,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile /*type*/ undefined, getFunctionFlags(node) & FunctionFlags.Async ? transformAsyncFunctionBody(node) - : transformMethodBody(node) + : transformMethodBody(node), ); } @@ -421,7 +421,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile node.name, visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - transformMethodBody(node) + transformMethodBody(node), ); } @@ -431,7 +431,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile visitNodes(node.modifiers, visitor, isModifierLike), node.name, visitParameterList(node.parameters, visitor, context), - transformMethodBody(node) + transformMethodBody(node), ); } @@ -454,7 +454,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile /*type*/ undefined, getFunctionFlags(node) & FunctionFlags.Async ? transformAsyncFunctionBody(node) - : visitFunctionBody(node.body, visitor, context) + : visitFunctionBody(node.body, visitor, context), ); } @@ -477,7 +477,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile /*type*/ undefined, getFunctionFlags(node) & FunctionFlags.Async ? transformAsyncFunctionBody(node) - : visitFunctionBody(node.body, visitor, context) + : visitFunctionBody(node.body, visitor, context), ); } @@ -558,9 +558,9 @@ export function transformES2017(context: TransformationContext): (x: SourceFile const converted = setSourceMapRange( factory.createAssignment( factory.converters.convertToAssignmentElementTarget(node.name), - node.initializer! + node.initializer!, ), - node + node, ); return Debug.checkDefined(visitNode(converted, visitor, isExpression)); } @@ -663,9 +663,9 @@ export function transformES2017(context: TransformationContext): (x: SourceFile inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, - transformAsyncFunctionBodyWorker(node.body as Block, statementOffset) - ) - ) + transformAsyncFunctionBodyWorker(node.body as Block, statementOffset), + ), + ), ); insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); @@ -703,7 +703,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, - transformAsyncFunctionBodyWorker(node.body) + transformAsyncFunctionBodyWorker(node.body), ); const declarations = endLexicalEnvironment(); @@ -737,8 +737,10 @@ export function transformES2017(context: TransformationContext): (x: SourceFile const typeName = type && getEntityNameFromTypeNode(type); if (typeName && isEntityName(typeName)) { const serializationKind = resolver.getTypeReferenceSerializationKind(typeName); - if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === TypeReferenceSerializationKind.Unknown) { + if ( + serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === TypeReferenceSerializationKind.Unknown + ) { return typeName; } } @@ -830,8 +832,9 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return setTextRange( factory.createPropertyAccessExpression( factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), - node.name), - node + node.name, + ), + node, ); } return node; @@ -841,7 +844,7 @@ export function transformES2017(context: TransformationContext): (x: SourceFile if (node.expression.kind === SyntaxKind.SuperKeyword) { return createSuperElementAccessInAsyncMethod( node.argumentExpression, - node + node, ); } return node; @@ -858,8 +861,8 @@ export function transformES2017(context: TransformationContext): (x: SourceFile /*typeArguments*/ undefined, [ factory.createThis(), - ...node.arguments - ] + ...node.arguments, + ], ); } return node; @@ -881,11 +884,11 @@ export function transformES2017(context: TransformationContext): (x: SourceFile factory.createCallExpression( factory.createUniqueName("_superIndex", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), /*typeArguments*/ undefined, - [argumentExpression] + [argumentExpression], ), - "value" + "value", ), - location + location, ); } else { @@ -893,9 +896,9 @@ export function transformES2017(context: TransformationContext): (x: SourceFile factory.createCallExpression( factory.createUniqueName("_superIndex", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), /*typeArguments*/ undefined, - [argumentExpression] + [argumentExpression], ), - location + location, ); } } @@ -919,20 +922,20 @@ export function createSuperAccessVariableStatement(factory: NodeFactory, resolve factory.createArrowFunction( /*modifiers*/ undefined, /*typeParameters*/ undefined, - /* parameters */[], + /* parameters */ [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, setEmitFlags( factory.createPropertyAccessExpression( setEmitFlags( factory.createSuper(), - EmitFlags.NoSubstitution + EmitFlags.NoSubstitution, ), - name + name, ), - EmitFlags.NoSubstitution - ) - ) + EmitFlags.NoSubstitution, + ), + ), )); if (hasBinding) { getterAndSetter.push( @@ -941,15 +944,15 @@ export function createSuperAccessVariableStatement(factory: NodeFactory, resolve factory.createArrowFunction( /*modifiers*/ undefined, /*typeParameters*/ undefined, - /* parameters */[ + /* parameters */ [ factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "v", /*questionToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined - ) + /*initializer*/ undefined, + ), ], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, @@ -958,23 +961,23 @@ export function createSuperAccessVariableStatement(factory: NodeFactory, resolve factory.createPropertyAccessExpression( setEmitFlags( factory.createSuper(), - EmitFlags.NoSubstitution + EmitFlags.NoSubstitution, ), - name + name, ), - EmitFlags.NoSubstitution + EmitFlags.NoSubstitution, ), - factory.createIdentifier("v") - ) - ) - ) + factory.createIdentifier("v"), + ), + ), + ), ); } accessors.push( factory.createPropertyAssignment( name, factory.createObjectLiteralExpression(getterAndSetter), - ) + ), ); }); return factory.createVariableStatement( @@ -988,15 +991,17 @@ export function createSuperAccessVariableStatement(factory: NodeFactory, resolve factory.createCallExpression( factory.createPropertyAccessExpression( factory.createIdentifier("Object"), - "create" + "create", ), /*typeArguments*/ undefined, [ factory.createNull(), - factory.createObjectLiteralExpression(accessors, /*multiLine*/ true) - ] - ) - ) + factory.createObjectLiteralExpression(accessors, /*multiLine*/ true), + ], + ), + ), ], - NodeFlags.Const)); + NodeFlags.Const, + ), + ); } diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts index 00ca8babafec4..e04d1c679e848 100644 --- a/src/compiler/transformers/es2018.ts +++ b/src/compiler/transformers/es2018.ts @@ -114,7 +114,7 @@ import { const enum ESNextSubstitutionFlags { /** Enables substitutions for async methods with `super` calls. */ - AsyncMethodsWithSuper = 1 << 0 + AsyncMethodsWithSuper = 1 << 0, } // Facts we track as we traverse the tree @@ -156,7 +156,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile getEmitHelperFactory: emitHelpers, resumeLexicalEnvironment, endLexicalEnvironment, - hoistVariableDeclaration + hoistVariableDeclaration, } = context; const resolver = context.getEmitResolver(); @@ -215,7 +215,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile function recordTaggedTemplateString(temp: Identifier) { taggedTemplateStringDeclarations = append( taggedTemplateStringDeclarations, - factory.createVariableDeclaration(temp)); + factory.createVariableDeclaration(temp), + ); } function transformSourceFile(node: SourceFile) { @@ -297,7 +298,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitDefault, node, HierarchyFacts.IterationStatementExcludes, - HierarchyFacts.IterationStatementIncludes); + HierarchyFacts.IterationStatementIncludes, + ); case SyntaxKind.ForOfStatement: return visitForOfStatement(node as ForOfStatement, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ForStatement: @@ -305,7 +307,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitForStatement, node as ForStatement, HierarchyFacts.IterationStatementExcludes, - HierarchyFacts.IterationStatementIncludes); + HierarchyFacts.IterationStatementIncludes, + ); case SyntaxKind.VoidExpression: return visitVoidExpression(node as VoidExpression); case SyntaxKind.Constructor: @@ -313,43 +316,50 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitConstructorDeclaration, node as ConstructorDeclaration, HierarchyFacts.ClassOrFunctionExcludes, - HierarchyFacts.ClassOrFunctionIncludes); + HierarchyFacts.ClassOrFunctionIncludes, + ); case SyntaxKind.MethodDeclaration: return doWithHierarchyFacts( visitMethodDeclaration, node as MethodDeclaration, HierarchyFacts.ClassOrFunctionExcludes, - HierarchyFacts.ClassOrFunctionIncludes); + HierarchyFacts.ClassOrFunctionIncludes, + ); case SyntaxKind.GetAccessor: return doWithHierarchyFacts( visitGetAccessorDeclaration, node as GetAccessorDeclaration, HierarchyFacts.ClassOrFunctionExcludes, - HierarchyFacts.ClassOrFunctionIncludes); + HierarchyFacts.ClassOrFunctionIncludes, + ); case SyntaxKind.SetAccessor: return doWithHierarchyFacts( visitSetAccessorDeclaration, node as SetAccessorDeclaration, HierarchyFacts.ClassOrFunctionExcludes, - HierarchyFacts.ClassOrFunctionIncludes); + HierarchyFacts.ClassOrFunctionIncludes, + ); case SyntaxKind.FunctionDeclaration: return doWithHierarchyFacts( visitFunctionDeclaration, node as FunctionDeclaration, HierarchyFacts.ClassOrFunctionExcludes, - HierarchyFacts.ClassOrFunctionIncludes); + HierarchyFacts.ClassOrFunctionIncludes, + ); case SyntaxKind.FunctionExpression: return doWithHierarchyFacts( visitFunctionExpression, node as FunctionExpression, HierarchyFacts.ClassOrFunctionExcludes, - HierarchyFacts.ClassOrFunctionIncludes); + HierarchyFacts.ClassOrFunctionIncludes, + ); case SyntaxKind.ArrowFunction: return doWithHierarchyFacts( visitArrowFunction, node as ArrowFunction, HierarchyFacts.ArrowFunctionExcludes, - HierarchyFacts.ArrowFunctionIncludes); + HierarchyFacts.ArrowFunctionIncludes, + ); case SyntaxKind.Parameter: return visitParameter(node as ParameterDeclaration); case SyntaxKind.ExpressionStatement: @@ -374,7 +384,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitDefault, node, HierarchyFacts.ClassOrFunctionExcludes, - HierarchyFacts.ClassOrFunctionIncludes); + HierarchyFacts.ClassOrFunctionIncludes, + ); default: return visitEachChild(node, visitor, context); } @@ -385,9 +396,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return setOriginalNode( setTextRange( factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(visitNode(node.expression, visitor, isExpression))), - /*location*/ node + /*location*/ node, ), - node + node, ); } return visitEachChild(node, visitor, context); @@ -410,17 +421,17 @@ export function transformES2018(context: TransformationContext): (x: SourceFile emitHelpers().createAsyncDelegatorHelper( setTextRange( emitHelpers().createAsyncValuesHelper(expression), - expression - ) + expression, + ), ), - expression - ) - ) - ) + expression, + ), + ), + ), ), - node + node, ), - node + node, ); } @@ -431,12 +442,12 @@ export function transformES2018(context: TransformationContext): (x: SourceFile createDownlevelAwait( node.expression ? visitNode(node.expression, visitor, isExpression) - : factory.createVoidZero() - ) + : factory.createVoidZero(), + ), ), - node + node, ), - node + node, ); } @@ -445,9 +456,12 @@ export function transformES2018(context: TransformationContext): (x: SourceFile function visitReturnStatement(node: ReturnStatement) { if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { - return factory.updateReturnStatement(node, createDownlevelAwait( - node.expression ? visitNode(node.expression, visitor, isExpression) : factory.createVoidZero() - )); + return factory.updateReturnStatement( + node, + createDownlevelAwait( + node.expression ? visitNode(node.expression, visitor, isExpression) : factory.createVoidZero(), + ), + ); } return visitEachChild(node, visitor, context); @@ -477,9 +491,12 @@ export function transformES2018(context: TransformationContext): (x: SourceFile objects.push(visitNode(target, visitor, isExpression)); } else { - chunkObject = append(chunkObject, e.kind === SyntaxKind.PropertyAssignment - ? factory.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) - : visitNode(e, visitor, isObjectLiteralElementLike)); + chunkObject = append( + chunkObject, + e.kind === SyntaxKind.PropertyAssignment + ? factory.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) + : visitNode(e, visitor, isObjectLiteralElementLike), + ); } } if (chunkObject) { @@ -547,13 +564,16 @@ export function transformES2018(context: TransformationContext): (x: SourceFile HierarchyFacts.SourceFileExcludes, isEffectiveStrictModeSourceFile(node, compilerOptions) ? HierarchyFacts.StrictModeSourceFileIncludes : - HierarchyFacts.SourceFileIncludes); + HierarchyFacts.SourceFileIncludes, + ); exportedVariableStatement = false; const visited = visitEachChild(node, visitor, context); - const statement = concatenate(visited.statements, taggedTemplateStringDeclarations && [ - factory.createVariableStatement(/*modifiers*/ undefined, - factory.createVariableDeclarationList(taggedTemplateStringDeclarations)) - ]); + const statement = concatenate( + visited.statements, + taggedTemplateStringDeclarations && [ + factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations)), + ], + ); const result = factory.updateSourceFile(visited, setTextRange(factory.createNodeArray(statement), node.statements)); exitSubtree(ancestorFacts); return result; @@ -566,7 +586,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitor, currentSourceFile, recordTaggedTemplateString, - ProcessLevel.LiftRestriction + ProcessLevel.LiftRestriction, ); } @@ -584,7 +604,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitor, context, FlattenLevel.ObjectRest, - !expressionResultIsUnused + !expressionResultIsUnused, ); } if (node.operatorToken.kind === SyntaxKind.CommaToken) { @@ -592,7 +612,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile node, visitNode(node.left, visitorWithUnusedExpressionResult, isExpression), node.operatorToken, - visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, isExpression) + visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, isExpression), ); } return visitEachChild(node, visitor, context); @@ -620,9 +640,11 @@ export function transformES2018(context: TransformationContext): (x: SourceFile } function visitCatchClause(node: CatchClause) { - if (node.variableDeclaration && + if ( + node.variableDeclaration && isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { + node.variableDeclaration.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread + ) { const name = factory.getGeneratedNameForNode(node.variableDeclaration.name); const updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); const visitedBindings = flattenDestructuringBinding(updatedDecl, visitor, context, FlattenLevel.ObjectRest); @@ -636,7 +658,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return factory.updateCatchClause( node, factory.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined), - block); + block, + ); } return visitEachChild(node, visitor, context); } @@ -677,7 +700,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile context, FlattenLevel.ObjectRest, /*rval*/ undefined, - exportedVariableStatement + exportedVariableStatement, ); } return visitEachChild(node, visitor, context); @@ -689,7 +712,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), - visitIterationBody(node.statement, visitor, context) + visitIterationBody(node.statement, visitor, context), ); } @@ -704,8 +727,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile */ function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult { const ancestorFacts = enterSubtree(HierarchyFacts.IterationStatementExcludes, HierarchyFacts.IterationStatementIncludes); - if (node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread || - isAssignmentPattern(node.initializer) && containsObjectRestOrSpread(node.initializer)) { + if ( + node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread || + isAssignmentPattern(node.initializer) && containsObjectRestOrSpread(node.initializer) + ) { node = transformForOfStatementWithObjectRest(node); } const result = node.awaitModifier ? @@ -738,20 +763,20 @@ export function transformES2018(context: TransformationContext): (x: SourceFile setTextRange( factory.createVariableDeclarationList( [ - setTextRange(factory.createVariableDeclaration(temp), node.initializer) + setTextRange(factory.createVariableDeclaration(temp), node.initializer), ], - NodeFlags.Let + NodeFlags.Let, ), - node.initializer + node.initializer, ), node.expression, setTextRange( factory.createBlock( setTextRange(factory.createNodeArray(statements), statementsLocation), - /*multiLine*/ true + /*multiLine*/ true, ), - bodyLocation - ) + bodyLocation, + ), ); } return node; @@ -786,9 +811,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return setTextRange( factory.createBlock( setTextRange(factory.createNodeArray(statements), statementsLocation), - /*multiLine*/ true + /*multiLine*/ true, ), - bodyLocation + bodyLocation, ); } @@ -829,23 +854,23 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.createVariableDeclarationList([ factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()), setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), - factory.createVariableDeclaration(result) + factory.createVariableDeclaration(result), ]), - node.expression + node.expression, ), - EmitFlags.NoHoisting + EmitFlags.NoHoisting, ), /*condition*/ factory.inlineExpressions([ factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createAssignment(done, getDone), - factory.createLogicalNot(done) + factory.createLogicalNot(done), ]), /*incrementor*/ factory.createAssignment(nonUserCode, factory.createTrue()), - /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode) + /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode), ), - /*location*/ node + /*location*/ node, ), - EmitFlags.NoTokenTrailingSourceMaps + EmitFlags.NoTokenTrailingSourceMaps, ); setOriginalNode(forStatement, node); @@ -853,8 +878,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.createBlock([ factory.restoreEnclosingLabel( forStatement, - outermostLabeledStatement - ) + outermostLabeledStatement, + ), ]), factory.createCatchClause( factory.createVariableDeclaration(catchVariable), @@ -864,13 +889,13 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.createAssignment( errorRecord, factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("error", catchVariable) - ]) - ) - ) + factory.createPropertyAssignment("error", catchVariable), + ]), + ), + ), ]), - EmitFlags.SingleLine - ) + EmitFlags.SingleLine, + ), ), factory.createBlock([ factory.createTryStatement( @@ -884,13 +909,13 @@ export function transformES2018(context: TransformationContext): (x: SourceFile ), factory.createAssignment( returnMethod, - factory.createPropertyAccessExpression(iterator, "return") - ) + factory.createPropertyAccessExpression(iterator, "return"), + ), ), - factory.createExpressionStatement(createDownlevelAwait(callReturn)) + factory.createExpressionStatement(createDownlevelAwait(callReturn)), ), - EmitFlags.SingleLine - ) + EmitFlags.SingleLine, + ), ]), /*catchClause*/ undefined, /*finallyBlock*/ setEmitFlags( @@ -899,16 +924,16 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.createIfStatement( errorRecord, factory.createThrowStatement( - factory.createPropertyAccessExpression(errorRecord, "error") - ) + factory.createPropertyAccessExpression(errorRecord, "error"), + ), ), - EmitFlags.SingleLine - ) + EmitFlags.SingleLine, + ), ]), - EmitFlags.SingleLine - ) - ) - ]) + EmitFlags.SingleLine, + ), + ), + ]), ); } @@ -926,7 +951,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, /*questionToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined + /*initializer*/ undefined, ); } if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { @@ -939,7 +964,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression), ); } return visitEachChild(node, visitor, context); @@ -967,7 +992,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile node, node.modifiers, visitParameterList(node.parameters, parameterVisitor, context), - transformFunctionBody(node) + transformFunctionBody(node), ); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -985,7 +1010,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitNode(node.name, visitor, isPropertyName), visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, - transformFunctionBody(node) + transformFunctionBody(node), ); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -1002,7 +1027,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile node.modifiers, visitNode(node.name, visitor, isPropertyName), visitParameterList(node.parameters, parameterVisitor, context), - transformFunctionBody(node) + transformFunctionBody(node), ); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -1029,7 +1054,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*type*/ undefined, enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator ? transformAsyncGeneratorFunctionBody(node) - : transformFunctionBody(node) + : transformFunctionBody(node), ); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -1055,7 +1080,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*type*/ undefined, enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator ? transformAsyncGeneratorFunctionBody(node) - : transformFunctionBody(node) + : transformFunctionBody(node), ); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -1100,7 +1125,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*type*/ undefined, enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator ? transformAsyncGeneratorFunctionBody(node) - : transformFunctionBody(node) + : transformFunctionBody(node), ); enclosingFunctionFlags = savedEnclosingFunctionFlags; parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; @@ -1129,11 +1154,11 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*type*/ undefined, factory.updateBlock( node.body!, - visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset) - ) + visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset), + ), ), - !!(hierarchyFacts & HierarchyFacts.HasLexicalThis) - ) + !!(hierarchyFacts & HierarchyFacts.HasLexicalThis), + ), ); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -1205,7 +1230,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile visitor, context, FlattenLevel.All, - factory.getGeneratedNameForNode(parameter)); + factory.getGeneratedNameForNode(parameter), + ); if (some(declarations)) { const declarationList = factory.createVariableDeclarationList(declarations); const statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList); @@ -1362,8 +1388,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return setTextRange( factory.createPropertyAccessExpression( factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), - node.name), - node + node.name, + ), + node, ); } return node; @@ -1373,7 +1400,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile if (node.expression.kind === SyntaxKind.SuperKeyword) { return createSuperElementAccessInAsyncMethod( node.argumentExpression, - node + node, ); } return node; @@ -1390,8 +1417,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*typeArguments*/ undefined, [ factory.createThis(), - ...node.arguments - ] + ...node.arguments, + ], ); } return node; @@ -1413,11 +1440,11 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.createCallExpression( factory.createIdentifier("_superIndex"), /*typeArguments*/ undefined, - [argumentExpression] + [argumentExpression], ), - "value" + "value", ), - location + location, ); } else { @@ -1425,9 +1452,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.createCallExpression( factory.createIdentifier("_superIndex"), /*typeArguments*/ undefined, - [argumentExpression] + [argumentExpression], ), - location + location, ); } } diff --git a/src/compiler/transformers/es2019.ts b/src/compiler/transformers/es2019.ts index 0bd2be45422a4..0435e4c352707 100644 --- a/src/compiler/transformers/es2019.ts +++ b/src/compiler/transformers/es2019.ts @@ -43,7 +43,7 @@ export function transformES2019(context: TransformationContext): (x: SourceFile return factory.updateCatchClause( node, factory.createVariableDeclaration(factory.createTempVariable(/*recordTempVariable*/ undefined)), - visitNode(node.block, visitor, isBlock) + visitNode(node.block, visitor, isBlock), ); } return visitEachChild(node, visitor, context); diff --git a/src/compiler/transformers/es2020.ts b/src/compiler/transformers/es2020.ts index b030dca03ce5c..c3eb99351fde9 100644 --- a/src/compiler/transformers/es2020.ts +++ b/src/compiler/transformers/es2020.ts @@ -151,11 +151,15 @@ export function transformES2020(context: TransformationContext): (x: SourceFile function visitNonOptionalExpression(node: Expression, captureThisArg: boolean, isDelete: boolean): Expression { switch (node.kind) { - case SyntaxKind.ParenthesizedExpression: return visitNonOptionalParenthesizedExpression(node as ParenthesizedExpression, captureThisArg, isDelete); + case SyntaxKind.ParenthesizedExpression: + return visitNonOptionalParenthesizedExpression(node as ParenthesizedExpression, captureThisArg, isDelete); case SyntaxKind.PropertyAccessExpression: - case SyntaxKind.ElementAccessExpression: return visitNonOptionalPropertyOrElementAccessExpression(node as AccessExpression, captureThisArg, isDelete); - case SyntaxKind.CallExpression: return visitNonOptionalCallExpression(node as CallExpression, captureThisArg); - default: return visitNode(node, visitor, isExpression); + case SyntaxKind.ElementAccessExpression: + return visitNonOptionalPropertyOrElementAccessExpression(node as AccessExpression, captureThisArg, isDelete); + case SyntaxKind.CallExpression: + return visitNonOptionalCallExpression(node as CallExpression, captureThisArg); + default: + return visitNode(node, visitor, isExpression); } } @@ -198,14 +202,14 @@ export function transformES2020(context: TransformationContext): (x: SourceFile rightExpression = factory.createFunctionCallCall( rightExpression, leftThisArg.kind === SyntaxKind.SuperKeyword ? factory.createThis() : leftThisArg, - visitNodes(segment.arguments, visitor, isExpression) + visitNodes(segment.arguments, visitor, isExpression), ); } else { rightExpression = factory.createCallExpression( rightExpression, /*typeArguments*/ undefined, - visitNodes(segment.arguments, visitor, isExpression) + visitNodes(segment.arguments, visitor, isExpression), ); } break; @@ -225,14 +229,14 @@ export function transformES2020(context: TransformationContext): (x: SourceFile factory.createBinaryExpression( left, factory.createToken(invert ? SyntaxKind.EqualsEqualsEqualsToken : SyntaxKind.ExclamationEqualsEqualsToken), - factory.createNull() + factory.createNull(), ), factory.createToken(invert ? SyntaxKind.BarBarToken : SyntaxKind.AmpersandAmpersandToken), factory.createBinaryExpression( right, factory.createToken(invert ? SyntaxKind.EqualsEqualsEqualsToken : SyntaxKind.ExclamationEqualsEqualsToken), - factory.createVoidZero() - ) + factory.createVoidZero(), + ), ); } @@ -243,13 +247,16 @@ export function transformES2020(context: TransformationContext): (x: SourceFile right = factory.createTempVariable(hoistVariableDeclaration); left = factory.createAssignment(right, left); } - return setTextRange(factory.createConditionalExpression( - createNotNullCondition(left, right), - /*questionToken*/ undefined, - right, - /*colonToken*/ undefined, - visitNode(node.right, visitor, isExpression), - ), node); + return setTextRange( + factory.createConditionalExpression( + createNotNullCondition(left, right), + /*questionToken*/ undefined, + right, + /*colonToken*/ undefined, + visitNode(node.right, visitor, isExpression), + ), + node, + ); } function visitDeleteExpression(node: DeleteExpression) { diff --git a/src/compiler/transformers/es2021.ts b/src/compiler/transformers/es2021.ts index b2fbd0fbe71b2..08ab7af2a239b 100644 --- a/src/compiler/transformers/es2021.ts +++ b/src/compiler/transformers/es2021.ts @@ -25,7 +25,7 @@ import { export function transformES2021(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { const { hoistVariableDeclaration, - factory + factory, } = context; return chainBundle(context, transformSourceFile); @@ -60,17 +60,17 @@ export function transformES2021(context: TransformationContext): (x: SourceFile factory.createTempVariable(hoistVariableDeclaration); const propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory.createAssignment( propertyAccessTarget, - left.expression + left.expression, ); if (isPropertyAccessExpression(left)) { assignmentTarget = factory.createPropertyAccessExpression( propertyAccessTarget, - left.name + left.name, ); left = factory.createPropertyAccessExpression( propertyAccessTargetAssignment, - left.name + left.name, ); } else { @@ -80,14 +80,14 @@ export function transformES2021(context: TransformationContext): (x: SourceFile assignmentTarget = factory.createElementAccessExpression( propertyAccessTarget, - elementAccessArgument + elementAccessArgument, ); left = factory.createElementAccessExpression( propertyAccessTargetAssignment, elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory.createAssignment( elementAccessArgument, - left.argumentExpression - ) + left.argumentExpression, + ), ); } } @@ -98,9 +98,9 @@ export function transformES2021(context: TransformationContext): (x: SourceFile factory.createParenthesizedExpression( factory.createAssignment( assignmentTarget, - right - ) - ) + right, + ), + ), ); } } diff --git a/src/compiler/transformers/esDecorators.ts b/src/compiler/transformers/esDecorators.ts index 3ed8995d32d17..a356421c191ae 100644 --- a/src/compiler/transformers/esDecorators.ts +++ b/src/compiler/transformers/esDecorators.ts @@ -186,7 +186,7 @@ import { visitNodes, Visitor, VisitResult, - WrappedExpression + WrappedExpression, } from "../_namespaces/ts"; // Class/Decorator evaluation order, as it pertains to this transformer: @@ -278,8 +278,7 @@ type LexicalEnvironmentStackEntry = | ClassLexicalEnvironmentStackEntry | ClassElementLexicalEnvironmentStackEntry | OtherLexicalEnvironmentStackEntry - | PropertyNameLexicalEnvironmentStackEntry - ; + | PropertyNameLexicalEnvironmentStackEntry; /** @internal */ export function transformESDecorators(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { @@ -536,8 +535,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } function getHelperVariableName(node: ClassLikeDeclaration | ClassElement) { - let declarationName = - node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name) : + let declarationName = node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name) : node.name && isPrivateIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name).slice(1) : node.name && isStringLiteral(node.name) && isIdentifierText(node.name.text, ScriptTarget.ESNext) ? node.name.text : isClassLike(node) ? "class" : "member"; @@ -560,9 +558,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc name, /*exclamationToken*/ undefined, /*type*/ undefined, - initializer + initializer, ), - ], NodeFlags.Let) + ], NodeFlags.Let), ); } @@ -593,7 +591,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } else if (isPropertyDeclaration(member)) { if (hasStaticModifier(member)) { - hasStaticInitializers ||= (!!member.initializer || hasDecorators(member)); + hasStaticInitializers ||= !!member.initializer || hasDecorators(member); } else { hasNonAmbientInstanceFields ||= !isAmbientPropertyDeclaration(member); @@ -605,11 +603,13 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } // exit early if possible - if (staticExtraInitializersName && + if ( + staticExtraInitializersName && instanceExtraInitializersName && hasStaticInitializers && hasNonAmbientInstanceFields && - hasStaticPrivateClassElements) { + hasStaticPrivateClassElements + ) { break; } } @@ -658,9 +658,12 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // We do not mark _classThis as FileLevel if it may be reused by class private fields, which requires the // ability access the captured `_classThis` of outer scopes. const needsUniqueClassThis = some(node.members, member => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); - classInfo.classThis = factory.createUniqueName("_classThis", needsUniqueClassThis ? - GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes : - GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + classInfo.classThis = factory.createUniqueName( + "_classThis", + needsUniqueClassThis ? + GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes : + GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel, + ); classDefinitionStatements.push( createLet(classInfo.classDecoratorsName, factory.createArrayLiteralExpression(classDecorators)), createLet(classInfo.classDescriptorName), @@ -681,15 +684,14 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc if (extendsExpression) { classInfo.classSuper = factory.createUniqueName("_classSuper", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); - // Ensure we do not give the class or function an assigned name due to the variable by prefixing it - // with `0, `. + // Ensure we do not give the class or function an assigned name due to the variable by prefixing it + // with `0, `. const unwrapped = skipOuterExpressions(extendsExpression); - const safeExtendsExpression = - isClassExpression(unwrapped) && !unwrapped.name || - isFunctionExpression(unwrapped) && !unwrapped.name || - isArrowFunction(unwrapped) ? - factory.createComma(factory.createNumericLiteral(0), extendsExpression) : - extendsExpression; + const safeExtendsExpression = isClassExpression(unwrapped) && !unwrapped.name || + isFunctionExpression(unwrapped) && !unwrapped.name || + isArrowFunction(unwrapped) ? + factory.createComma(factory.createNumericLiteral(0), extendsExpression) : + extendsExpression; classDefinitionStatements.push(createLet(classInfo.classSuper, safeExtendsExpression)); const updatedExtendsElement = factory.updateExpressionWithTypeArguments(extendsElement, classInfo.classSuper, /*typeArguments*/ undefined); const updatedExtendsClause = factory.updateHeritageClause(extendsClause, [updatedExtendsElement]); @@ -771,14 +773,14 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // Used in steps 5, 7, and 11 if (classInfo.staticExtraInitializersName) { classDefinitionStatements.push( - createLet(classInfo.staticExtraInitializersName, factory.createArrayLiteralExpression()) + createLet(classInfo.staticExtraInitializersName, factory.createArrayLiteralExpression()), ); } // Used in steps 6, 8, and during construction if (classInfo.instanceExtraInitializersName) { classDefinitionStatements.push( - createLet(classInfo.instanceExtraInitializersName, factory.createArrayLiteralExpression()) + createLet(classInfo.instanceExtraInitializersName, factory.createArrayLiteralExpression()), ); } @@ -841,7 +843,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc classInfo.classDecoratorsName, { kind: "class", name: classNameReference, metadata: classInfo.metadataReference }, factory.createNull(), - classInfo.classExtraInitializersName + classInfo.classExtraInitializersName, ); const esDecorateStatement = factory.createExpressionStatement(esDecorateHelper); setSourceMapRange(esDecorateStatement, moveRangePastDecorators(node)); @@ -1104,9 +1106,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc factory.createExpressionStatement( emitHelpers().createRunInitializersHelper( factory.createThis(), - classInfo.instanceExtraInitializersName - ) - ) + classInfo.instanceExtraInitializersName, + ), + ), ); return statements; @@ -1126,7 +1128,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /*statementOffset*/ 0, superPath, superPathDepth + 1, - initializerStatements); + initializerStatements, + ); const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); @@ -1135,7 +1138,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc superStatement, factory.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock))); + visitNode(superStatement.finallyBlock, visitor, isBlock), + )); } else { addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); @@ -1190,7 +1194,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc >( member: TNode, classInfo: ClassInfo | undefined, - createDescriptor?: (node: TNode & { readonly name: PrivateIdentifier }, modifiers: ModifiersArray | undefined) => Expression + createDescriptor?: (node: TNode & { readonly name: PrivateIdentifier; }, modifiers: ModifiersArray | undefined) => Expression, ) { let referencedName: Expression | undefined; let name: PropertyName | undefined; @@ -1225,19 +1229,17 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // 6. Non-static non-field (method/getter/setter/auto-accessor) element decorators are applied // 7. Static field (excl. auto-accessor) element decorators are applied // 8. Non-static field (excl. auto-accessor) element decorators are applied - const statements = - isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? - isStatic(member) ? - classInfo.staticNonFieldDecorationStatements ??= [] : - classInfo.nonStaticNonFieldDecorationStatements ??= [] : + const statements = isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? + isStatic(member) ? + classInfo.staticNonFieldDecorationStatements ??= [] : + classInfo.nonStaticNonFieldDecorationStatements ??= [] : isPropertyDeclaration(member) && !isAutoAccessorPropertyDeclaration(member) ? - isStatic(member) ? - classInfo.staticFieldDecorationStatements ??= [] : - classInfo.nonStaticFieldDecorationStatements ??= [] : + isStatic(member) ? + classInfo.staticFieldDecorationStatements ??= [] : + classInfo.nonStaticFieldDecorationStatements ??= [] : Debug.fail(); - const kind = - isGetAccessorDeclaration(member) ? "getter" : + const kind = isGetAccessorDeclaration(member) ? "getter" : isSetAccessorDeclaration(member) ? "setter" : isMethodDeclaration(member) ? "method" : isAutoAccessorPropertyDeclaration(member) ? "accessor" : @@ -1274,7 +1276,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // 2. If _kind_ is ~field~, ~method~, ~accessor~, or ~getter~, then ... get: isPropertyDeclaration(member) || isGetAccessorDeclaration(member) || isMethodDeclaration(member), // 3. If _kind_ is ~field~, ~accessor~, or ~setter~, then ... - set: isPropertyDeclaration(member) || isSetAccessorDeclaration(member) + set: isPropertyDeclaration(member) || isSetAccessorDeclaration(member), }, metadata: classInfo.metadataReference, }; @@ -1334,7 +1336,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc memberDecoratorsName, context, initializersName, - extraInitializers); + extraInitializers, + ); const esDecorateStatement = factory.createExpressionStatement(esDecorateExpression); setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); statements.push(esDecorateStatement); @@ -1451,7 +1454,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc initializer = emitHelpers().createRunInitializersHelper( thisArg ?? factory.createThis(), initializersName, - initializer ?? factory.createVoidZero()); + initializer ?? factory.createVoidZero(), + ); } if (!isStatic(node) && classInfo?.instanceExtraInitializersName && !classInfo?.hasInjectedInstanceInitializers) { @@ -1461,9 +1465,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc initializer = factory.createParenthesizedExpression(factory.createComma( emitHelpers().createRunInitializersHelper( factory.createThis(), - classInfo.instanceExtraInitializersName + classInfo.instanceExtraInitializersName, ), - initializer + initializer, )); } @@ -1475,7 +1479,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc if (some(declarations)) { initializer = factory.createImmediatelyInvokedArrowFunction([ ...declarations, - factory.createReturnStatement(initializer) + factory.createReturnStatement(initializer), ]); } @@ -1625,7 +1629,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc visitNode(node.name, visitor, isBindingName), /*questionToken*/ undefined, /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression), ); if (updated !== node) { @@ -1659,7 +1663,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, visitor, context) + visitIterationBody(node.statement, visitor, context), ); } @@ -1707,8 +1711,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } if (isSuperProperty(node.left) && classThis && classSuper) { - let setterName = - isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : + let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : isIdentifier(node.left.name) ? factory.createStringLiteralFromNode(node.left.name) : undefined; if (setterName) { @@ -1727,14 +1730,15 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc const superPropertyGet = factory.createReflectGetCall( classSuper, getterName, - classThis); + classThis, + ); setOriginalNode(superPropertyGet, node.left); setTextRange(superPropertyGet, node.left); expression = factory.createBinaryExpression( superPropertyGet, getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), - expression + expression, ); setTextRange(expression, node); } @@ -1749,7 +1753,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc classSuper, setterName, expression, - classThis + classThis, ); setOriginalNode(expression, node); setTextRange(expression, node); @@ -1774,12 +1778,13 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } function visitPreOrPostfixUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression, discarded: boolean) { - if (node.operator === SyntaxKind.PlusPlusToken || - node.operator === SyntaxKind.MinusMinusToken) { + if ( + node.operator === SyntaxKind.PlusPlusToken || + node.operator === SyntaxKind.MinusMinusToken + ) { const operand = skipParentheses(node.operand); if (isSuperProperty(operand) && classThis && classSuper) { - let setterName = - isElementAccessExpression(operand) ? visitNode(operand.argumentExpression, visitor, isExpression) : + let setterName = isElementAccessExpression(operand) ? visitNode(operand.argumentExpression, visitor, isExpression) : isIdentifier(operand.name) ? factory.createStringLiteralFromNode(operand.name) : undefined; if (setterName) { @@ -1944,8 +1949,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } if (isSuperProperty(node) && classThis && classSuper) { - const propertyName = - isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : + const propertyName = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : isIdentifier(node.name) ? factory.createStringLiteralFromNode(node.name) : undefined; if (propertyName) { @@ -1957,7 +1961,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc propertyName, paramName, classThis, - ) + ), ); setOriginalNode(expression, node); setTextRange(expression, node); @@ -2171,7 +2175,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /*typeParameters*/ undefined, parameters, /*type*/ undefined, - body ?? factory.createBlock([]) + body ?? factory.createBlock([]), ); setOriginalNode(func, original); setSourceMapRange(func, moveRangePastDecorators(original)); @@ -2199,7 +2203,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc node.asteriskToken, "value", visitNodes(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock)) + visitNode(node.body, visitor, isBlock), + ), ]); } @@ -2215,7 +2220,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /*asteriskToken*/ undefined, "get", [], - visitNode(node.body, visitor, isBlock)) + visitNode(node.body, visitor, isBlock), + ), ]); } @@ -2231,7 +2237,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /*asteriskToken*/ undefined, "set", visitNodes(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock)) + visitNode(node.body, visitor, isBlock), + ), ]); } @@ -2256,10 +2263,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc factory.createReturnStatement( factory.createPropertyAccessExpression( factory.createThis(), - factory.getGeneratedPrivateNameForNode(node.name) - ) - ) - ]) + factory.getGeneratedPrivateNameForNode(node.name), + ), + ), + ]), ), createDescriptorMethod( node, @@ -2270,20 +2277,20 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc [factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - "value" + "value", )], factory.createBlock([ factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression( factory.createThis(), - factory.getGeneratedPrivateNameForNode(node.name) + factory.getGeneratedPrivateNameForNode(node.name), ), - factory.createIdentifier("value") - ) - ) - ]) - ) + factory.createIdentifier("value"), + ), + ), + ]), + ), ]); } @@ -2305,10 +2312,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc factory.createReturnStatement( factory.createPropertyAccessExpression( descriptorName, - factory.createIdentifier("value") - ) - ) - ]) + factory.createIdentifier("value"), + ), + ), + ]), ); } @@ -2331,13 +2338,13 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc factory.createFunctionCallCall( factory.createPropertyAccessExpression( descriptorName, - factory.createIdentifier("get") + factory.createIdentifier("get"), ), factory.createThis(), - [] - ) - ) - ]) + [], + ), + ), + ]), ); } @@ -2356,20 +2363,20 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc [factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - "value" + "value", )], factory.createBlock([ factory.createReturnStatement( factory.createFunctionCallCall( factory.createPropertyAccessExpression( descriptorName, - factory.createIdentifier("set") + factory.createIdentifier("set"), ), factory.createThis(), - [factory.createIdentifier("value")] - ) - ) - ]) + [factory.createIdentifier("value")], + ), + ), + ]), ); } function createMetadata(name: Identifier, classSuper: Identifier | undefined) { @@ -2386,7 +2393,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc factory.createCallExpression( factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "create"), /*typeArguments*/ undefined, - [classSuper ? createSymbolMetadataReference(classSuper) : factory.createNull()] + [classSuper ? createSymbolMetadataReference(classSuper) : factory.createNull()], ), factory.createToken(SyntaxKind.ColonToken), factory.createVoidZero(), @@ -2399,7 +2406,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc const defineProperty = factory.createObjectDefinePropertyCall( target, factory.createPropertyAccessExpression(factory.createIdentifier("Symbol"), "metadata"), - factory.createPropertyDescriptor({ configurable: true, writable: true, enumerable: true, value }, /*singleLine*/ true) + factory.createPropertyDescriptor({ configurable: true, writable: true, enumerable: true, value }, /*singleLine*/ true), ); return setEmitFlags( factory.createIfStatement(value, factory.createExpressionStatement(defineProperty)), @@ -2414,7 +2421,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc factory.createPropertyAccessExpression(factory.createIdentifier("Symbol"), "metadata"), ), SyntaxKind.QuestionQuestionToken, - factory.createNull() + factory.createNull(), ); } } diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index d20cdd511d9ba..04b79d250eaad 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -60,7 +60,7 @@ import { visitEachChild, visitNode, visitNodes, - VisitResult + VisitResult, } from "../_namespaces/ts"; const enum UsingKind { @@ -197,11 +197,14 @@ export function transformESNext(context: TransformationContext): (x: SourceFile // add `export {}` declarations for any hoisted bindings. if (exportBindings.size) { - append(topLevelStatements, factory.createExportDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - factory.createNamedExports(arrayFrom(exportBindings.values())) - )); + append( + topLevelStatements, + factory.createExportDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createNamedExports(arrayFrom(exportBindings.values())), + ), + ); } addRange(topLevelStatements, endLexicalEnvironment()); @@ -210,8 +213,8 @@ export function transformESNext(context: TransformationContext): (x: SourceFile factory.createModifiersFromModifierFlags(ModifierFlags.Export), factory.createVariableDeclarationList( exportVars, - NodeFlags.Let - ) + NodeFlags.Let, + ), )); } addRange(topLevelStatements, createDownlevelUsingStatements(bodyStatements, envBinding, usingKind === UsingKind.Async)); @@ -220,7 +223,7 @@ export function transformESNext(context: TransformationContext): (x: SourceFile topLevelStatements.push(factory.createExportAssignment( /*modifiers*/ undefined, /*isExportEquals*/ true, - exportEqualsBinding + exportEqualsBinding, )); } @@ -243,8 +246,8 @@ export function transformESNext(context: TransformationContext): (x: SourceFile transformUsingDeclarations(node.statements, prologueCount, node.statements.length, envBinding, /*topLevelStatements*/ undefined), envBinding, usingKind === UsingKind.Async, - ) - ] + ), + ], ); } return visitEachChild(node, visitor, context); @@ -272,11 +275,11 @@ export function transformESNext(context: TransformationContext): (x: SourceFile /*initializer*/ undefined, node.condition, node.incrementor, - node.statement - ) + node.statement, + ), ]), visitor, - isStatement + isStatement, ); } @@ -314,21 +317,21 @@ export function transformESNext(context: TransformationContext): (x: SourceFile node, node.awaitModifier, factory.createVariableDeclarationList([ - factory.createVariableDeclaration(temp) + factory.createVariableDeclaration(temp), ], NodeFlags.Const), node.expression, isBlock(node.statement) ? factory.updateBlock(node.statement, [ usingVarStatement, - ...node.statement.statements + ...node.statement.statements, ]) : factory.createBlock([ usingVarStatement, - node.statement - ], /*multiLine*/ true) + node.statement, + ], /*multiLine*/ true), ), visitor, - isStatement + isStatement, ); } return visitEachChild(node, visitor, context); @@ -340,13 +343,13 @@ export function transformESNext(context: TransformationContext): (x: SourceFile return factory.updateCaseClause( node, visitNode(node.expression, visitor, isExpression), - transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ undefined) + transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ undefined), ); } else { return factory.updateDefaultClause( node, - transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ undefined) + transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ undefined), ); } } @@ -388,9 +391,9 @@ export function transformESNext(context: TransformationContext): (x: SourceFile visitNode(node.expression, visitor, isExpression), factory.updateCaseBlock( node.caseBlock, - node.caseBlock.clauses.map(clause => visitCaseOrDefaultClause(clause, envBinding)) - ) - ) + node.caseBlock.clauses.map(clause => visitCaseOrDefaultClause(clause, envBinding)), + ), + ), ], envBinding, usingKind === UsingKind.Async, @@ -433,8 +436,8 @@ export function transformESNext(context: TransformationContext): (x: SourceFile emitHelpers().createAddDisposableResourceHelper( envBinding, initializer, - usingKind === UsingKind.Async - ) + usingKind === UsingKind.Async, + ), )); } @@ -738,7 +741,7 @@ export function transformESNext(context: TransformationContext): (x: SourceFile const envObject = factory.createObjectLiteralExpression([ factory.createPropertyAssignment("stack", factory.createArrayLiteralExpression()), factory.createPropertyAssignment("error", factory.createVoidZero()), - factory.createPropertyAssignment("hasError", factory.createFalse()) + factory.createPropertyAssignment("hasError", factory.createFalse()), ]); const envVar = factory.createVariableDeclaration(envBinding, /*exclamationToken*/ undefined, /*type*/ undefined, envObject); const envVarList = factory.createVariableDeclarationList([envVar], NodeFlags.Const); @@ -784,14 +787,16 @@ export function transformESNext(context: TransformationContext): (x: SourceFile factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression(envBinding, "error"), - bodyCatchBinding) + bodyCatchBinding, + ), ), factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression(envBinding, "hasError"), - factory.createTrue()) + factory.createTrue(), + ), ), - ], /*multiLine*/ true) + ], /*multiLine*/ true), ); let finallyBlock: Block; @@ -805,18 +810,18 @@ export function transformESNext(context: TransformationContext): (x: SourceFile result, /*exclamationToken*/ undefined, /*type*/ undefined, - emitHelpers().createDisposeResourcesHelper(envBinding) - ) - ], NodeFlags.Const) + emitHelpers().createDisposeResourcesHelper(envBinding), + ), + ], NodeFlags.Const), ), - factory.createIfStatement(result, factory.createExpressionStatement(factory.createAwaitExpression(result))) + factory.createIfStatement(result, factory.createExpressionStatement(factory.createAwaitExpression(result))), ], /*multiLine*/ true); } else { finallyBlock = factory.createBlock([ factory.createExpressionStatement( - emitHelpers().createDisposeResourcesHelper(envBinding) - ) + emitHelpers().createDisposeResourcesHelper(envBinding), + ), ], /*multiLine*/ true); } @@ -836,7 +841,7 @@ function countPrologueStatements(statements: readonly Statement[]) { return 0; } -function isUsingVariableDeclarationList(node: Node): node is VariableDeclarationList & { _usingBrand: any } { +function isUsingVariableDeclarationList(node: Node): node is VariableDeclarationList & { _usingBrand: any; } { return isVariableDeclarationList(node) && getUsingKindOfVariableDeclarationList(node) !== UsingKind.None; } diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 0439defa66437..775075a6e8f6f 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -218,6 +218,7 @@ import { type Label = number; +// dprint-ignore const enum OpCode { Nop, // No operation, used to force a new case in the state machine Statement, // A regular javascript statement @@ -229,7 +230,7 @@ const enum OpCode { YieldStar, // A completion instruction for the `yield*` keyword (not implemented, but reserved for future use) Return, // A completion instruction for the `return` keyword Throw, // A completion instruction for the `throw` keyword - Endfinally // Marks the end of a `finally` block + Endfinally, // Marks the end of a `finally` block } type OperationArguments = [Label] | [Label, Expression] | [Statement] | [Expression | undefined] | [Expression, Expression]; @@ -246,7 +247,7 @@ const enum CodeBlockKind { With, Switch, Loop, - Labeled + Labeled, } // the state for a generated code exception block @@ -254,11 +255,11 @@ const enum ExceptionBlockState { Try, Catch, Finally, - Done + Done, } // A generated code block -type CodeBlock = | ExceptionBlock | LabeledBlock | SwitchBlock | LoopBlock | WithBlock; +type CodeBlock = ExceptionBlock | LabeledBlock | SwitchBlock | LoopBlock | WithBlock; // a generated exception block, used for 'try' statements interface ExceptionBlock { @@ -316,12 +317,18 @@ const enum Instruction { function getInstructionName(instruction: Instruction): string { switch (instruction) { - case Instruction.Return: return "return"; - case Instruction.Break: return "break"; - case Instruction.Yield: return "yield"; - case Instruction.YieldStar: return "yield*"; - case Instruction.Endfinally: return "endfinally"; - default: return undefined!; // TODO: GH#18217 + case Instruction.Return: + return "return"; + case Instruction.Break: + return "break"; + case Instruction.Yield: + return "yield"; + case Instruction.YieldStar: + return "yield*"; + case Instruction.Endfinally: + return "endfinally"; + default: + return undefined!; // TODO: GH#18217 } } @@ -333,7 +340,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF resumeLexicalEnvironment, endLexicalEnvironment, hoistFunctionDeclaration, - hoistVariableDeclaration + hoistVariableDeclaration, } = context; const compilerOptions = context.getCompilerOptions(); @@ -397,7 +404,6 @@ export function transformGenerators(context: TransformationContext): (x: SourceF return node; } - const visited = visitEachChild(node, visitor, context); addEmitHelpers(visited, context.readEmitHelpers()); return visited; @@ -555,11 +561,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF /*typeParameters*/ undefined, visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - transformGeneratorFunctionBody(node.body!) + transformGeneratorFunctionBody(node.body!), ), - /*location*/ node + /*location*/ node, ), - node + node, ); } else { @@ -604,11 +610,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF /*typeParameters*/ undefined, visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - transformGeneratorFunctionBody(node.body) + transformGeneratorFunctionBody(node.body), ), - /*location*/ node + /*location*/ node, ), - node + node, ); } else { @@ -740,10 +746,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF return setSourceMapRange( factory.createExpressionStatement( factory.inlineExpressions( - map(variables, transformInitializedVariable) - ) + map(variables, transformInitializedVariable), + ), ), - node + node, ); } } @@ -792,7 +798,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF target = factory.updatePropertyAccessExpression( left as PropertyAccessExpression, cacheExpression(Debug.checkDefined(visitNode((left as PropertyAccessExpression).expression, visitor, isLeftHandSideExpression))), - (left as PropertyAccessExpression).name + (left as PropertyAccessExpression).name, ); break; @@ -808,10 +814,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .mark resumeLabel // _a[_b] = %sent%; - target = factory.updateElementAccessExpression(left as ElementAccessExpression, - cacheExpression(Debug.checkDefined(visitNode((left as ElementAccessExpression).expression, visitor, isLeftHandSideExpression))), - cacheExpression(Debug.checkDefined(visitNode((left as ElementAccessExpression).argumentExpression, visitor, isExpression))) - ); + target = factory.updateElementAccessExpression(left as ElementAccessExpression, cacheExpression(Debug.checkDefined(visitNode((left as ElementAccessExpression).expression, visitor, isLeftHandSideExpression))), cacheExpression(Debug.checkDefined(visitNode((left as ElementAccessExpression).argumentExpression, visitor, isExpression)))); break; default: @@ -828,12 +831,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createBinaryExpression( cacheExpression(target), getNonAssignmentOperatorForCompoundAssignment(operator), - Debug.checkDefined(visitNode(right, visitor, isExpression)) + Debug.checkDefined(visitNode(right, visitor, isExpression)), ), - node - ) + node, + ), ), - node + node, ); } else { @@ -862,10 +865,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .yield resumeLabel // _a + %sent% + c() - return factory.updateBinaryExpression(node, - cacheExpression(Debug.checkDefined(visitNode(node.left, visitor, isExpression))), - node.operatorToken, - Debug.checkDefined(visitNode(node.right, visitor, isExpression))); + return factory.updateBinaryExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.left, visitor, isExpression))), node.operatorToken, Debug.checkDefined(visitNode(node.right, visitor, isExpression))); } return visitEachChild(node, visitor, context); @@ -1087,12 +1087,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF if (numInitialElements > 0) { temp = declareLocal(); const initialElements = visitNodes(elements, visitor, isExpression, 0, numInitialElements); - emitAssignment(temp, + emitAssignment( + temp, factory.createArrayLiteralExpression( leadingElement ? [leadingElement, ...initialElements] - : initialElements - ) + : initialElements, + ), ); leadingElement = undefined; } @@ -1102,7 +1103,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)]) : setTextRange( factory.createArrayLiteralExpression(leadingElement ? [leadingElement, ...expressions] : expressions, multiLine), - location + location, ); function reduceElement(expressions: Expression[], element: Expression) { @@ -1117,12 +1118,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF hasAssignedTemp ? factory.createArrayConcatCall( temp, - [factory.createArrayLiteralExpression(expressions, multiLine)] + [factory.createArrayLiteralExpression(expressions, multiLine)], ) : factory.createArrayLiteralExpression( leadingElement ? [leadingElement, ...expressions] : expressions, - multiLine - ) + multiLine, + ), ); leadingElement = undefined; expressions = []; @@ -1157,11 +1158,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF const numInitialProperties = countInitialNodesWithoutYield(properties); const temp = declareLocal(); - emitAssignment(temp, + emitAssignment( + temp, factory.createObjectLiteralExpression( visitNodes(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), - multiLine - ) + multiLine, + ), ); const expressions = reduceLeft(properties, reduceProperty, [] as Expression[], numInitialProperties); @@ -1204,9 +1206,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .mark resumeLabel // a = _a[%sent%] - return factory.updateElementAccessExpression(node, - cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression))), - Debug.checkDefined(visitNode(node.argumentExpression, visitor, isExpression))); + return factory.updateElementAccessExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression))), Debug.checkDefined(visitNode(node.argumentExpression, visitor, isExpression))); } return visitEachChild(node, visitor, context); @@ -1230,11 +1230,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createFunctionApplyCall( cacheExpression(Debug.checkDefined(visitNode(target, visitor, isLeftHandSideExpression))), thisArg, - visitElements(node.arguments) + visitElements(node.arguments), ), - node + node, ), - node + node, ); } @@ -1263,15 +1263,15 @@ export function transformGenerators(context: TransformationContext): (x: SourceF thisArg, visitElements( node.arguments!, - /*leadingElement*/ factory.createVoidZero() - ) + /*leadingElement*/ factory.createVoidZero(), + ), ), /*typeArguments*/ undefined, - [] + [], ), - node + node, ), - node + node, ); } return visitEachChild(node, visitor, context); @@ -1388,9 +1388,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF return setSourceMapRange( factory.createAssignment( setSourceMapRange(factory.cloneNode(node.name) as Identifier, node.name), - Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)) + Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)), ), - node + node, ); } @@ -1547,10 +1547,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF emitStatement( setTextRange( factory.createExpressionStatement( - Debug.checkDefined(visitNode(initializer, visitor, isExpression)) + Debug.checkDefined(visitNode(initializer, visitor, isExpression)), ), - initializer - ) + initializer, + ), ); } } @@ -1567,10 +1567,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF emitStatement( setTextRange( factory.createExpressionStatement( - Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression)) + Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression)), ), - node.incrementor - ) + node.incrementor, + ), ); } emitBreak(conditionLabel); @@ -1593,13 +1593,14 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } const variables = getInitializedVariables(initializer); - node = factory.updateForStatement(node, + node = factory.updateForStatement( + node, variables.length > 0 ? factory.inlineExpressions(map(variables, transformInitializedVariable)) : undefined, visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), - visitIterationBody(node.statement, visitor, context) + visitIterationBody(node.statement, visitor, context), ); } else { @@ -1656,10 +1657,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createCallExpression( factory.createPropertyAccessExpression(keysArray, "push"), /*typeArguments*/ undefined, - [key] - ) - ) - ) + [key], + ), + ), + ), ); emitAssignment(keysIndex, factory.createNumericLiteral(0)); @@ -1725,11 +1726,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF hoistVariableDeclaration(variable.name as Identifier); } - node = factory.updateForInStatement(node, - initializer.declarations[0].name as Identifier, - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), - Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory.liftToBlock)) - ); + node = factory.updateForInStatement(node, initializer.declarations[0].name as Identifier, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory.liftToBlock))); } else { node = visitEachChild(node, visitor, context); @@ -1789,14 +1786,14 @@ export function transformGenerators(context: TransformationContext): (x: SourceF function transformAndEmitReturnStatement(node: ReturnStatement): void { emitReturn( visitNode(node.expression, visitor, isExpression), - /*location*/ node + /*location*/ node, ); } function visitReturnStatement(node: ReturnStatement) { return createInlineReturn( visitNode(node.expression, visitor, isExpression), - /*location*/ node + /*location*/ node, ); } @@ -1889,9 +1886,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createCaseClause( Debug.checkDefined(visitNode(clause.expression, visitor, isExpression)), [ - createInlineBreak(clauseLabels[i], /*location*/ clause.expression) - ] - ) + createInlineBreak(clauseLabels[i], /*location*/ clause.expression), + ], + ), ); } else { @@ -1982,7 +1979,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // TODO(rbuckton): `expression` should be required on `throw`. emitThrow( Debug.checkDefined(visitNode(node.expression ?? factory.createVoidZero(), visitor, isExpression)), - /*location*/ node + /*location*/ node, ); } @@ -2192,7 +2189,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF kind: CodeBlockKind.With, expression, startLabel, - endLabel + endLabel, }); } @@ -2216,7 +2213,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF kind: CodeBlockKind.Exception, state: ExceptionBlockState.Try, startLabel, - endLabel + endLabel, }); emitNop(); return endLabel; @@ -2313,7 +2310,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF kind: CodeBlockKind.Loop, isScript: true, breakLabel: -1, - continueLabel: -1 + continueLabel: -1, }); } @@ -2352,13 +2349,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF /** * Begins a code block that supports `break` statements that are defined in the source * tree and not from generated code. - * */ function beginScriptSwitchBlock(): void { beginBlock({ kind: CodeBlockKind.Switch, isScript: true, - breakLabel: -1 + breakLabel: -1, }); } @@ -2394,7 +2390,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF kind: CodeBlockKind.Labeled, isScript: true, labelText, - breakLabel: -1 + breakLabel: -1, }); } @@ -2404,7 +2400,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF kind: CodeBlockKind.Labeled, isScript: false, labelText, - breakLabel + breakLabel, }); } @@ -2563,10 +2559,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createReturnStatement( factory.createArrayLiteralExpression([ createInstruction(Instruction.Break), - createLabel(label) - ]) + createLabel(label), + ]), ), - location + location, ); } @@ -2579,12 +2575,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF function createInlineReturn(expression?: Expression, location?: TextRange): ReturnStatement { return setTextRange( factory.createReturnStatement( - factory.createArrayLiteralExpression(expression - ? [createInstruction(Instruction.Return), expression] - : [createInstruction(Instruction.Return)] - ) + factory.createArrayLiteralExpression( + expression + ? [createInstruction(Instruction.Return), expression] + : [createInstruction(Instruction.Return)], + ), ), - location + location, ); } @@ -2596,9 +2593,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createCallExpression( factory.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ undefined, - [] + [], ), - location + location, ); } @@ -2766,11 +2763,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF /*type*/ undefined, factory.createBlock( buildResult, - /*multiLine*/ buildResult.length > 0 - ) + /*multiLine*/ buildResult.length > 0, + ), ), - EmitFlags.ReuseTempVariableScope - ) + EmitFlags.ReuseTempVariableScope, + ), ); } @@ -2899,11 +2896,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF createLabel(startLabel), createLabel(catchLabel), createLabel(finallyLabel), - createLabel(endLabel) - ]) - ] - ) - ) + createLabel(endLabel), + ]), + ], + ), + ), ); currentExceptionBlock = undefined; @@ -2916,9 +2913,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression(state, "label"), - factory.createNumericLiteral(labelNumber + 1) - ) - ) + factory.createNumericLiteral(labelNumber + 1), + ), + ), ); } } @@ -2926,8 +2923,8 @@ export function transformGenerators(context: TransformationContext): (x: SourceF clauses.push( factory.createCaseClause( factory.createNumericLiteral(labelNumber), - statements || [] - ) + statements || [], + ), ); statements = undefined; @@ -3016,7 +3013,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF withBlockStack!.pop(); } break; - // default: do nothing + // default: do nothing } } } @@ -3125,15 +3122,16 @@ export function transformGenerators(context: TransformationContext): (x: SourceF setEmitFlags( setTextRange( factory.createReturnStatement( - factory.createArrayLiteralExpression(expression - ? [createInstruction(Instruction.Return), expression] - : [createInstruction(Instruction.Return)] - ) + factory.createArrayLiteralExpression( + expression + ? [createInstruction(Instruction.Return), expression] + : [createInstruction(Instruction.Return)], + ), ), - operationLocation + operationLocation, ), - EmitFlags.NoTokenSourceMaps - ) + EmitFlags.NoTokenSourceMaps, + ), ); } @@ -3151,13 +3149,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createReturnStatement( factory.createArrayLiteralExpression([ createInstruction(Instruction.Break), - createLabel(label) - ]) + createLabel(label), + ]), ), - operationLocation + operationLocation, ), - EmitFlags.NoTokenSourceMaps - ) + EmitFlags.NoTokenSourceMaps, + ), ); } @@ -3178,16 +3176,16 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createReturnStatement( factory.createArrayLiteralExpression([ createInstruction(Instruction.Break), - createLabel(label) - ]) + createLabel(label), + ]), ), - operationLocation + operationLocation, ), - EmitFlags.NoTokenSourceMaps - ) + EmitFlags.NoTokenSourceMaps, + ), ), - EmitFlags.SingleLine - ) + EmitFlags.SingleLine, + ), ); } @@ -3208,16 +3206,16 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createReturnStatement( factory.createArrayLiteralExpression([ createInstruction(Instruction.Break), - createLabel(label) - ]) + createLabel(label), + ]), ), - operationLocation + operationLocation, ), - EmitFlags.NoTokenSourceMaps - ) + EmitFlags.NoTokenSourceMaps, + ), ), - EmitFlags.SingleLine - ) + EmitFlags.SingleLine, + ), ); } @@ -3236,13 +3234,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createArrayLiteralExpression( expression ? [createInstruction(Instruction.Yield), expression] - : [createInstruction(Instruction.Yield)] - ) + : [createInstruction(Instruction.Yield)], + ), ), - operationLocation + operationLocation, ), - EmitFlags.NoTokenSourceMaps - ) + EmitFlags.NoTokenSourceMaps, + ), ); } @@ -3260,13 +3258,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createReturnStatement( factory.createArrayLiteralExpression([ createInstruction(Instruction.YieldStar), - expression - ]) + expression, + ]), ), - operationLocation + operationLocation, ), - EmitFlags.NoTokenSourceMaps - ) + EmitFlags.NoTokenSourceMaps, + ), ); } @@ -3278,9 +3276,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF writeStatement( factory.createReturnStatement( factory.createArrayLiteralExpression([ - createInstruction(Instruction.Endfinally) - ]) - ) + createInstruction(Instruction.Endfinally), + ]), + ), ); } } diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index fe3ccc883f718..d0e191d537ad0 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -107,7 +107,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B return currentFileState.filenameDeclaration.name; } const declaration = factory.createVariableDeclaration(factory.createUniqueName("_jsxFileName", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), /*exclamationToken*/ undefined, /*type*/ undefined, factory.createStringLiteral(currentSourceFile.fileName)); - currentFileState.filenameDeclaration = declaration as VariableDeclaration & { name: Identifier }; + currentFileState.filenameDeclaration = declaration as VariableDeclaration & { name: Identifier; }; return currentFileState.filenameDeclaration.name; } @@ -176,14 +176,17 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B } else if (isExternalOrCommonJsModule(node)) { // Add `require` statement - const requireStatement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - factory.createObjectBindingPattern(arrayFrom(importSpecifiersMap.values(), s => factory.createBindingElement(/*dotDotDotToken*/ undefined, s.propertyName, s.name))), - /*exclamationToken*/ undefined, - /*type*/ undefined, - factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, [factory.createStringLiteral(importSource)]) - ) - ], NodeFlags.Const)); + const requireStatement = factory.createVariableStatement( + /*modifiers*/ undefined, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + factory.createObjectBindingPattern(arrayFrom(importSpecifiersMap.values(), s => factory.createBindingElement(/*dotDotDotToken*/ undefined, s.propertyName, s.name))), + /*exclamationToken*/ undefined, + /*type*/ undefined, + factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, [factory.createStringLiteral(importSource)]), + ), + ], NodeFlags.Const), + ); setParentRecursive(requireStatement, /*incremental*/ false); statements = insertStatementAfterCustomPrologue(statements.slice(), requireStatement); } @@ -250,8 +253,10 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B } function hasProto(obj: ObjectLiteralExpression) { - return obj.properties.some(p => isPropertyAssignment(p) && - (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__")); + return obj.properties.some(p => + isPropertyAssignment(p) && + (isIdentifier(p.name) && idText(p.name) === "__proto__" || isStringLiteral(p.name) && p.name.text === "__proto__") + ); } /** @@ -317,7 +322,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B keyAttr, children || emptyArray, isChild, - location + location, ); } @@ -327,11 +332,10 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B keyAttr: JsxAttribute | undefined, children: readonly JsxChild[], isChild: boolean, - location: TextRange + location: TextRange, ) { const nonWhitespaceChildren = getSemanticJsxChildren(children); - const isStaticChildren = - length(nonWhitespaceChildren) > 1 || !!(nonWhitespaceChildren[0] as JsxExpression)?.dotDotDotToken; + const isStaticChildren = length(nonWhitespaceChildren) > 1 || !!(nonWhitespaceChildren[0] as JsxExpression)?.dotDotDotToken; const args: Expression[] = [tagName, objectProperties]; // function jsx(type, config, maybeKey) {} // "maybeKey" is optional. It is acceptable to use "_jsx" without a third argument @@ -352,7 +356,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B args.push(factory.createObjectLiteralExpression([ factory.createPropertyAssignment("fileName", getCurrentFileNameExpression()), factory.createPropertyAssignment("lineNumber", factory.createNumericLiteral(lineCol.line + 1)), - factory.createPropertyAssignment("columnNumber", factory.createNumericLiteral(lineCol.character + 1)) + factory.createPropertyAssignment("columnNumber", factory.createNumericLiteral(lineCol.character + 1)), ])); // __self development flag args.push(factory.createThis()); @@ -361,7 +365,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B const element = setTextRange( factory.createCallExpression(getJsxFactoryCallee(isStaticChildren), /*typeArguments*/ undefined, args), - location + location, ); if (isChild) { @@ -382,7 +386,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace!, // TODO: GH#18217 - node + node, ) : getImplicitImportForName("createElement"); @@ -392,7 +396,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B tagName, objectProperties, mapDefined(children, transformJsxChildToExpression), - location + location, ); if (isChild) { @@ -416,7 +420,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B /*keyAttr*/ undefined, children, isChild, - location + location, ); } @@ -428,7 +432,7 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B compilerOptions.reactNamespace!, // TODO: GH#18217 mapDefined(children, transformJsxChildToExpression), node, - location + location, ); if (isChild) { @@ -445,22 +449,21 @@ export function transformJsx(context: TransformationContext): (x: SourceFile | B return factory.createSpreadAssignment(Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); } - function transformJsxAttributesToObjectProps(attrs: readonly(JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) { + function transformJsxAttributesToObjectProps(attrs: readonly (JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) { const target = getEmitScriptTarget(compilerOptions); return target && target >= ScriptTarget.ES2018 ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) : transformJsxAttributesToExpression(attrs, children); } - function transformJsxAttributesToProps(attrs: readonly(JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) { - const props = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => - flatten(map(attrs, attr => isSpread ? transformJsxSpreadAttributeToProps(attr as JsxSpreadAttribute) : transformJsxAttributeToObjectLiteralElement(attr as JsxAttribute))))); + function transformJsxAttributesToProps(attrs: readonly (JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) { + const props = flatten(spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => flatten(map(attrs, attr => isSpread ? transformJsxSpreadAttributeToProps(attr as JsxSpreadAttribute) : transformJsxAttributeToObjectLiteralElement(attr as JsxAttribute))))); if (children) { props.push(children); } return props; } - function transformJsxAttributesToExpression(attrs: readonly(JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) { + function transformJsxAttributesToExpression(attrs: readonly (JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) { const expressions: Expression[] = []; let properties: ObjectLiteralElementLike[] = []; @@ -926,5 +929,5 @@ const entities = new Map(Object.entries({ spades: 0x2660, clubs: 0x2663, hearts: 0x2665, - diams: 0x2666 + diams: 0x2666, })); diff --git a/src/compiler/transformers/legacyDecorators.ts b/src/compiler/transformers/legacyDecorators.ts index d8ff2bcf72bb4..0039c44f499c4 100644 --- a/src/compiler/transformers/legacyDecorators.ts +++ b/src/compiler/transformers/legacyDecorators.ts @@ -185,12 +185,15 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ false); addClassElementDecorationStatements(decorationStatements, node, /*isStatic*/ true); if (hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node)) { - members = setTextRange(factory.createNodeArray([ - ...members, - factory.createClassStaticBlockDeclaration( - factory.createBlock(decorationStatements, /*multiLine*/ true) - ) - ]), members); + members = setTextRange( + factory.createNodeArray([ + ...members, + factory.createClassStaticBlockDeclaration( + factory.createBlock(decorationStatements, /*multiLine*/ true), + ), + ]), + members, + ); decorationStatements = undefined; } return { decorationStatements, members }; @@ -220,7 +223,7 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S name, /*typeParameters*/ undefined, heritageClauses, - members + members, ); return addRange([updated], decorationStatements); @@ -341,23 +344,25 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S // If we're emitting to ES2022 or later then we need to reassign the class alias before // static initializers are evaluated. - const assignClassAliasInStaticBlock = - languageVersion >= ScriptTarget.ES2022 && + const assignClassAliasInStaticBlock = languageVersion >= ScriptTarget.ES2022 && !!classAlias && some(members, member => isPropertyDeclaration(member) && hasSyntacticModifier(member, ModifierFlags.Static) || isClassStaticBlockDeclaration(member)); if (assignClassAliasInStaticBlock) { - members = setTextRange(factory.createNodeArray([ - factory.createClassStaticBlockDeclaration( - factory.createBlock([ - factory.createExpressionStatement( - factory.createAssignment(classAlias, factory.createThis()) - ) - ]) - ), - ...members - ]), members); + members = setTextRange( + factory.createNodeArray([ + factory.createClassStaticBlockDeclaration( + factory.createBlock([ + factory.createExpressionStatement( + factory.createAssignment(classAlias, factory.createThis()), + ), + ]), + ), + ...members, + ]), + members, + ); } const classExpression = factory.createClassExpression( @@ -365,7 +370,8 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S name && isGeneratedIdentifier(name) ? undefined : name, /*typeParameters*/ undefined, heritageClauses, - members); + members, + ); setOriginalNode(classExpression, node); setTextRange(classExpression, location); @@ -408,7 +414,7 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S node.name, /*typeParameters*/ undefined, visitNodes(node.heritageClauses, visitor, isHeritageClause), - visitNodes(node.members, visitor, isClassElement) + visitNodes(node.members, visitor, isClassElement), ); } @@ -417,7 +423,8 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S node, visitNodes(node.modifiers, modifierVisitor, isModifier), visitNodes(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock)); + visitNode(node.body, visitor, isBlock), + ); } function finishClassElement(updated: ClassElement, original: ClassElement) { @@ -431,38 +438,47 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S } function visitMethodDeclaration(node: MethodDeclaration) { - return finishClassElement(factory.updateMethodDeclaration( + return finishClassElement( + factory.updateMethodDeclaration( + node, + visitNodes(node.modifiers, modifierVisitor, isModifier), + node.asteriskToken, + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + /*questionToken*/ undefined, + /*typeParameters*/ undefined, + visitNodes(node.parameters, visitor, isParameter), + /*type*/ undefined, + visitNode(node.body, visitor, isBlock), + ), node, - visitNodes(node.modifiers, modifierVisitor, isModifier), - node.asteriskToken, - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - /*questionToken*/ undefined, - /*typeParameters*/ undefined, - visitNodes(node.parameters, visitor, isParameter), - /*type*/ undefined, - visitNode(node.body, visitor, isBlock) - ), node); + ); } function visitGetAccessorDeclaration(node: GetAccessorDeclaration) { - return finishClassElement(factory.updateGetAccessorDeclaration( + return finishClassElement( + factory.updateGetAccessorDeclaration( + node, + visitNodes(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + visitNodes(node.parameters, visitor, isParameter), + /*type*/ undefined, + visitNode(node.body, visitor, isBlock), + ), node, - visitNodes(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - visitNodes(node.parameters, visitor, isParameter), - /*type*/ undefined, - visitNode(node.body, visitor, isBlock) - ), node); + ); } function visitSetAccessorDeclaration(node: SetAccessorDeclaration) { - return finishClassElement(factory.updateSetAccessorDeclaration( + return finishClassElement( + factory.updateSetAccessorDeclaration( + node, + visitNodes(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + visitNodes(node.parameters, visitor, isParameter), + visitNode(node.body, visitor, isBlock), + ), node, - visitNodes(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - visitNodes(node.parameters, visitor, isParameter), - visitNode(node.body, visitor, isBlock) - ), node); + ); } function visitPropertyDeclaration(node: PropertyDeclaration) { @@ -470,14 +486,17 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S return undefined; } - return finishClassElement(factory.updatePropertyDeclaration( + return finishClassElement( + factory.updatePropertyDeclaration( + node, + visitNodes(node.modifiers, modifierVisitor, isModifier), + Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + visitNode(node.initializer, visitor, isExpression), + ), node, - visitNodes(node.modifiers, modifierVisitor, isModifier), - Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression) - ), node); + ); } function visitParameterDeclaration(node: ParameterDeclaration) { @@ -488,7 +507,7 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), /*questionToken*/ undefined, /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression), ); if (updated !== node) { // While we emit the source map for the node after skipping decorators and modifiers, @@ -627,7 +646,6 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? factory.createVoidZero() - // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. // We have this extra argument here so that we can inject an explicit property descriptor at a later date. : factory.createNull() @@ -637,7 +655,7 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S decoratorExpressions, prefix, memberName, - descriptor + descriptor, ); setEmitFlags(helper, EmitFlags.NoComments); @@ -705,7 +723,8 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S for (const decorator of decorators) { const helper = emitHelpers().createParamHelper( transformDecorator(decorator), - parameterOffset); + parameterOffset, + ); setTextRange(helper, decorator.expression); setEmitFlags(helper, EmitFlags.NoComments); expressions.push(helper); @@ -827,4 +846,3 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S return undefined; } } - diff --git a/src/compiler/transformers/module/esnextAnd2015.ts b/src/compiler/transformers/module/esnextAnd2015.ts index 879544063f9f0..9e41ffc75de04 100644 --- a/src/compiler/transformers/module/esnextAnd2015.ts +++ b/src/compiler/transformers/module/esnextAnd2015.ts @@ -110,7 +110,8 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); return factory.updateSourceFile( node, - setTextRange(factory.createNodeArray(statements), node.statements)); + setTextRange(factory.createNodeArray(statements), node.statements), + ); } else { return visitEachChild(node, visitor, context); @@ -127,7 +128,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S case SyntaxKind.ExportAssignment: return visitExportAssignment(node as ExportAssignment); case SyntaxKind.ExportDeclaration: - const exportDecl = (node as ExportDeclaration); + const exportDecl = node as ExportDeclaration; return visitExportDeclaration(exportDecl); } @@ -139,7 +140,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S * * @param importNode The declaration to import. */ - function createRequireCall(importNode: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) { + function createRequireCall(importNode: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) { const moduleName = getExternalModuleNameLiteral(factory, importNode, Debug.checkDefined(currentSourceFile), host, resolver, compilerOptions); const args: Expression[] = []; if (moduleName) { @@ -154,10 +155,10 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamedImports([ - factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("createRequire"), createRequireName) - ]) + factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("createRequire"), createRequireName), + ]), ), - factory.createStringLiteral("module") + factory.createStringLiteral("module"), ); const requireHelperName = factory.createUniqueName("__require", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); const requireStatement = factory.createVariableStatement( @@ -169,15 +170,14 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S /*exclamationToken*/ undefined, /*type*/ undefined, factory.createCallExpression(factory.cloneNode(createRequireName), /*typeArguments*/ undefined, [ - factory.createPropertyAccessExpression(factory.createMetaProperty(SyntaxKind.ImportKeyword, factory.createIdentifier("meta")), factory.createIdentifier("url")) - ]) - ) + factory.createPropertyAccessExpression(factory.createMetaProperty(SyntaxKind.ImportKeyword, factory.createIdentifier("meta")), factory.createIdentifier("url")), + ]), + ), ], - /*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None - ) + /*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None, + ), ); importRequireStatements = [importStatement, requireStatement]; - } const name = importRequireStatements[1].declarationList.declarations[0].name; @@ -194,7 +194,8 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements: Statement[] | undefined; - statements = append(statements, + statements = append( + statements, setOriginalNode( setTextRange( factory.createVariableStatement( @@ -205,15 +206,16 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S factory.cloneNode(node.name), /*exclamationToken*/ undefined, /*type*/ undefined, - createRequireCall(node) - ) + createRequireCall(node), + ), ], - /*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None - ) + /*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None, + ), ), - node), - node - ) + node, + ), + node, + ), ); statements = appendExportsOfImportEqualsDeclaration(statements, node); @@ -223,11 +225,14 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S function appendExportsOfImportEqualsDeclaration(statements: Statement[] | undefined, node: ImportEqualsDeclaration) { if (hasSyntacticModifier(node, ModifierFlags.Export)) { - statements = append(statements, factory.createExportDeclaration( - /*modifiers*/ undefined, - node.isTypeOnly, - factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, idText(node.name))]) - )); + statements = append( + statements, + factory.createExportDeclaration( + /*modifiers*/ undefined, + node.isTypeOnly, + factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, idText(node.name))]), + ), + ); } return statements; } @@ -256,11 +261,11 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S /*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport( - synthName - ) + synthName, + ), ), node.moduleSpecifier, - node.assertClause + node.assertClause, ); setOriginalNode(importDecl, node.exportClause); diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index b6339fcc15a90..6b60336995975 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -173,9 +173,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile function getTransformModuleDelegate(moduleKind: ModuleKind): (node: SourceFile) => SourceFile { switch (moduleKind) { - case ModuleKind.AMD: return transformAMDModule; - case ModuleKind.UMD: return transformUMDModule; - default: return transformCommonJSModule; + case ModuleKind.AMD: + return transformAMDModule; + case ModuleKind.UMD: + return transformUMDModule; + default: + return transformCommonJSModule; } } @@ -184,7 +187,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile getEmitHelperFactory: emitHelpers, startLexicalEnvironment, endLexicalEnvironment, - hoistVariableDeclaration + hoistVariableDeclaration, } = context; const compilerOptions = context.getCompilerOptions(); @@ -218,10 +221,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile * @param node The SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (node.isDeclarationFile || + if ( + node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & TransformFlags.ContainsDynamicImport || - (isJsonSourceFile(node) && hasJsonModuleEmitEnabled(compilerOptions) && outFile(compilerOptions)))) { + (isJsonSourceFile(node) && hasJsonModuleEmitEnabled(compilerOptions) && outFile(compilerOptions))) + ) { return node; } @@ -238,7 +243,6 @@ export function transformModule(context: TransformationContext): (x: SourceFile return updated; } - function shouldEmitUnderscoreUnderscoreESModule() { if (!currentModuleInfo.exportEquals && isExternalModule(currentSourceFile)) { return true; @@ -263,16 +267,16 @@ export function transformModule(context: TransformationContext): (x: SourceFile } if (length(currentModuleInfo.exportedNames)) { const chunkSize = 50; - for (let i=0; i factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(idText(nextId))), prev), - factory.createVoidZero() as Expression - ) - ) + factory.createVoidZero() as Expression, + ), + ), ); } } @@ -323,7 +327,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile // Create an updated SourceFile: // // define(mofactory.updateSourceFile", "module2"], function ... - const updated = factory.updateSourceFile(node, + const updated = factory.updateSourceFile( + node, setTextRange( factory.createNodeArray([ factory.createExpressionStatement( @@ -337,12 +342,14 @@ export function transformModule(context: TransformationContext): (x: SourceFile // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - factory.createArrayLiteralExpression(jsonSourceFile ? emptyArray : [ - factory.createStringLiteral("require"), - factory.createStringLiteral("exports"), - ...aliasedModuleNames, - ...unaliasedModuleNames - ]), + factory.createArrayLiteralExpression( + jsonSourceFile ? emptyArray : [ + factory.createStringLiteral("require"), + factory.createStringLiteral("exports"), + ...aliasedModuleNames, + ...unaliasedModuleNames, + ], + ), // Add the module body function argument: // @@ -357,17 +364,17 @@ export function transformModule(context: TransformationContext): (x: SourceFile [ factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports"), - ...importAliasNames + ...importAliasNames, ], /*type*/ undefined, - transformAsynchronousModuleBody(node) - ) - ] - ) - ) + transformAsynchronousModuleBody(node), + ), + ], + ), + ), ]), - /*location*/ node.statements - ) + /*location*/ node.statements, + ), ); addEmitHelpers(updated, context.readEmitHelpers()); @@ -395,7 +402,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.createIfStatement( factory.createLogicalAnd( factory.createTypeCheck(factory.createIdentifier("module"), "object"), - factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object") + factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object"), ), factory.createBlock([ factory.createVariableStatement( @@ -410,32 +417,32 @@ export function transformModule(context: TransformationContext): (x: SourceFile /*typeArguments*/ undefined, [ factory.createIdentifier("require"), - factory.createIdentifier("exports") - ] - ) - ) - ] + factory.createIdentifier("exports"), + ], + ), + ), + ], ), setEmitFlags( factory.createIfStatement( factory.createStrictInequality( factory.createIdentifier("v"), - factory.createIdentifier("undefined") + factory.createIdentifier("undefined"), ), factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), - factory.createIdentifier("v") - ) - ) + factory.createIdentifier("v"), + ), + ), ), - EmitFlags.SingleLine - ) + EmitFlags.SingleLine, + ), ]), factory.createIfStatement( factory.createLogicalAnd( factory.createTypeCheck(factory.createIdentifier("define"), "function"), - factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd") + factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd"), ), factory.createBlock([ factory.createExpressionStatement( @@ -449,20 +456,20 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.createStringLiteral("require"), factory.createStringLiteral("exports"), ...aliasedModuleNames, - ...unaliasedModuleNames + ...unaliasedModuleNames, ]), - factory.createIdentifier("factory") - ] - ) - ) - ]) - ) - ) + factory.createIdentifier("factory"), + ], + ), + ), + ]), + ), + ), ], - /*multiLine*/ true + /*multiLine*/ true, ), - /*location*/ undefined - ) + /*location*/ undefined, + ), ); // Create an updated SourceFile: @@ -497,17 +504,17 @@ export function transformModule(context: TransformationContext): (x: SourceFile [ factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports"), - ...importAliasNames + ...importAliasNames, ], /*type*/ undefined, - transformAsynchronousModuleBody(node) - ) - ] - ) - ) + transformAsynchronousModuleBody(node), + ), + ], + ), + ), ]), - /*location*/ node.statements - ) + /*location*/ node.statements, + ), ); addEmitHelpers(updated, context.readEmitHelpers()); @@ -644,10 +651,10 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.createAssignment( factory.createPropertyAccessExpression( factory.createIdentifier("module"), - "exports" + "exports", ), - expressionResult - ) + expressionResult, + ), ); setTextRange(statement, currentModuleInfo.exportEquals); @@ -817,7 +824,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: return false; - default: Debug.assertNever(elem, "Unhandled object member kind"); + default: + Debug.assertNever(elem, "Unhandled object member kind"); } } } @@ -847,9 +855,11 @@ export function transformModule(context: TransformationContext): (x: SourceFile } function visitForStatement(node: ForStatement, isTopLevel: boolean) { - if (isTopLevel && node.initializer && + if ( + isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && - !(node.initializer.flags & NodeFlags.BlockScoped)) { + !(node.initializer.flags & NodeFlags.BlockScoped) + ) { const exportStatements = appendExportsOfVariableDeclarationList(/*statements*/ undefined, node.initializer, /*isForInOrOfInitializer*/ false); if (exportStatements) { const statements: Statement[] = []; @@ -870,7 +880,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) + visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context), ); } @@ -896,7 +906,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) + visitIterationBody(node.statement, topLevelNestedVisitor, context), ); } @@ -923,7 +933,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile node.awaitModifier, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) + visitIterationBody(node.statement, topLevelNestedVisitor, context), ); } @@ -936,7 +946,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile return factory.updateDoStatement( node, visitIterationBody(node.statement, topLevelNestedVisitor, context), - visitNode(node.expression, visitor, isExpression) + visitNode(node.expression, visitor, isExpression), ); } @@ -949,7 +959,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile return factory.updateWhileStatement( node, visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) + visitIterationBody(node.statement, topLevelNestedVisitor, context), ); } @@ -962,7 +972,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile return factory.updateLabeledStatement( node, node.label, - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory.liftToBlock)) + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory.liftToBlock)), ); } @@ -975,7 +985,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile return factory.updateWithStatement( node, visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory.liftToBlock)) + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory.liftToBlock)), ); } @@ -989,7 +999,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory.liftToBlock)), - visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory.liftToBlock) + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory.liftToBlock), ); } @@ -1002,7 +1012,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile return factory.updateSwitchStatement( node, visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) + Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)), ); } @@ -1014,7 +1024,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile function visitCaseBlock(node: CaseBlock): CaseBlock { return factory.updateCaseBlock( node, - visitNodes(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) + visitNodes(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause), ); } @@ -1027,7 +1037,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile return factory.updateCaseClause( node, visitNode(node.expression, visitor, isExpression), - visitNodes(node.statements, topLevelNestedVisitor, isStatement) + visitNodes(node.statements, topLevelNestedVisitor, isStatement), ); } @@ -1058,7 +1068,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile return factory.updateCatchClause( node, node.variableDeclaration, - Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) + Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)), ); } @@ -1075,7 +1085,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile function visitExpressionStatement(node: ExpressionStatement) { return factory.updateExpressionStatement( node, - visitNode(node.expression, discardedValueVisitor, isExpression) + visitNode(node.expression, discardedValueVisitor, isExpression), ); } @@ -1097,11 +1107,13 @@ export function transformModule(context: TransformationContext): (x: SourceFile // - We do not transform identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only transform identifiers that are exported at the top level. - if ((node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) + if ( + (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) - && !isDeclarationNameOfEnumOrNamespace(node.operand)) { + && !isDeclarationNameOfEnumOrNamespace(node.operand) + ) { const exportedNames = getExports(node.operand); if (exportedNames) { let temp: Identifier | undefined; @@ -1179,18 +1191,21 @@ export function transformModule(context: TransformationContext): (x: SourceFile /*questionToken*/ undefined, /*whenTrue*/ createImportCallExpressionCommonJS(arg), /*colonToken*/ undefined, - /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis) + /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis), ); } else { const temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression( - /*condition*/ factory.createIdentifier("__syncRequire"), - /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(temp, /*isInlineable*/ true), - /*colonToken*/ undefined, - /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis) - )); + return factory.createComma( + factory.createAssignment(temp, arg), + factory.createConditionalExpression( + /*condition*/ factory.createIdentifier("__syncRequire"), + /*questionToken*/ undefined, + /*whenTrue*/ createImportCallExpressionCommonJS(temp, /*isInlineable*/ true), + /*colonToken*/ undefined, + /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis), + ), + ); } } @@ -1205,16 +1220,16 @@ export function transformModule(context: TransformationContext): (x: SourceFile const reject = factory.createUniqueName("reject"); const parameters = [ factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), - factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject), ]; const body = factory.createBlock([ factory.createExpressionStatement( factory.createCallExpression( factory.createIdentifier("require"), /*typeArguments*/ undefined, - [factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject] - ) - ) + [factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject], + ), + ), ]); let func: FunctionExpression | ArrowFunction; @@ -1225,7 +1240,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile parameters, /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, - body); + body, + ); } else { func = factory.createFunctionExpression( @@ -1235,7 +1251,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, parameters, /*type*/ undefined, - body); + body, + ); // if there is a lexical 'this' in the import call arguments, ensure we indicate // that this new function expression indicates it captures 'this' so that the @@ -1268,18 +1285,18 @@ export function transformModule(context: TransformationContext): (x: SourceFile /*argumentsArray*/ needSyncEval ? languageVersion >= ScriptTarget.ES2015 ? [ - factory.createTemplateExpression(factory.createTemplateHead(""), [ - factory.createTemplateSpan(arg, factory.createTemplateTail("")), - ]), - ] + factory.createTemplateExpression(factory.createTemplateHead(""), [ + factory.createTemplateSpan(arg, factory.createTemplateTail("")), + ]), + ] : [ - factory.createCallExpression( - factory.createPropertyAccessExpression(factory.createStringLiteral(""), "concat"), - /*typeArguments*/ undefined, - [arg] - ), - ] - : [] + factory.createCallExpression( + factory.createPropertyAccessExpression(factory.createStringLiteral(""), "concat"), + /*typeArguments*/ undefined, + [arg], + ), + ] + : [], ); let requireCall: Expression = factory.createCallExpression( @@ -1296,7 +1313,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - /*name*/ "s"), + /*name*/ "s", + ), ] : []; @@ -1308,7 +1326,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile /*parameters*/ parameters, /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, - requireCall); + requireCall, + ); } else { func = factory.createFunctionExpression( @@ -1318,7 +1337,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, /*parameters*/ parameters, /*type*/ undefined, - factory.createBlock([factory.createReturnStatement(requireCall)])); + factory.createBlock([factory.createReturnStatement(requireCall)]), + ); } const downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); @@ -1371,8 +1391,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.cloneNode(namespaceDeclaration.name), /*exclamationToken*/ undefined, /*type*/ undefined, - getHelperExpressionForImport(node, createRequireCall(node)) - ) + getHelperExpressionForImport(node, createRequireCall(node)), + ), ); } else { @@ -1385,8 +1405,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.getGeneratedNameForNode(node), /*exclamationToken*/ undefined, /*type*/ undefined, - getHelperExpressionForImport(node, createRequireCall(node)) - ) + getHelperExpressionForImport(node, createRequireCall(node)), + ), ); if (namespaceDeclaration && isDefaultImport(node)) { @@ -1395,31 +1415,34 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.cloneNode(namespaceDeclaration.name), /*exclamationToken*/ undefined, /*type*/ undefined, - factory.getGeneratedNameForNode(node) - ) + factory.getGeneratedNameForNode(node), + ), ); } } - statements = append(statements, + statements = append( + statements, setOriginalNode( setTextRange( factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList( variables, - languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None - ) + languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None, + ), ), - /*location*/ node), - /*original*/ node - ) + /*location*/ node, + ), + /*original*/ node, + ), ); } } else if (namespaceDeclaration && isDefaultImport(node)) { // import d, * as n from "mod"; - statements = append(statements, + statements = append( + statements, factory.createVariableStatement( /*modifiers*/ undefined, factory.createVariableDeclarationList( @@ -1430,15 +1453,16 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.cloneNode(namespaceDeclaration.name), /*exclamationToken*/ undefined, /*type*/ undefined, - factory.getGeneratedNameForNode(node) + factory.getGeneratedNameForNode(node), ), - /*location*/ node), - /*original*/ node - ) + /*location*/ node, + ), + /*original*/ node, + ), ], - languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None - ) - ) + languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None, + ), + ), ); } @@ -1472,22 +1496,25 @@ export function transformModule(context: TransformationContext): (x: SourceFile let statements: Statement[] | undefined; if (moduleKind !== ModuleKind.AMD) { if (hasSyntacticModifier(node, ModifierFlags.Export)) { - statements = append(statements, + statements = append( + statements, setOriginalNode( setTextRange( factory.createExpressionStatement( createExportExpression( node.name, - createRequireCall(node) - ) + createRequireCall(node), + ), ), - node), - node - ) + node, + ), + node, + ), ); } else { - statements = append(statements, + statements = append( + statements, setOriginalNode( setTextRange( factory.createVariableStatement( @@ -1498,29 +1525,32 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.cloneNode(node.name), /*exclamationToken*/ undefined, /*type*/ undefined, - createRequireCall(node) - ) + createRequireCall(node), + ), ], - /*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None - ) + /*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None, + ), ), - node), - node - ) + node, + ), + node, + ), ); } } else { if (hasSyntacticModifier(node, ModifierFlags.Export)) { - statements = append(statements, + statements = append( + statements, setOriginalNode( setTextRange( factory.createExpressionStatement( - createExportExpression(factory.getExportName(node), factory.getLocalName(node)) + createExportExpression(factory.getExportName(node), factory.getLocalName(node)), ), - node), - node - ) + node, + ), + node, + ), ); } } @@ -1557,13 +1587,14 @@ export function transformModule(context: TransformationContext): (x: SourceFile generatedName, /*exclamationToken*/ undefined, /*type*/ undefined, - createRequireCall(node) - ) - ]) + createRequireCall(node), + ), + ]), ), - /*location*/ node), - /* original */ node - ) + /*location*/ node, + ), + /* original */ node, + ), ); } for (const specifier of node.exportClause.elements) { @@ -1572,30 +1603,32 @@ export function transformModule(context: TransformationContext): (x: SourceFile setOriginalNode( setTextRange( factory.createExpressionStatement( - emitHelpers().createCreateBindingHelper(generatedName, factory.createStringLiteralFromNode(specifier.propertyName || specifier.name), specifier.propertyName ? factory.createStringLiteralFromNode(specifier.name) : undefined) + emitHelpers().createCreateBindingHelper(generatedName, factory.createStringLiteralFromNode(specifier.propertyName || specifier.name), specifier.propertyName ? factory.createStringLiteralFromNode(specifier.name) : undefined), ), - specifier), - specifier - ) + specifier, + ), + specifier, + ), ); } else { - const exportNeedsImportDefault = - !!getESModuleInterop(compilerOptions) && + const exportNeedsImportDefault = !!getESModuleInterop(compilerOptions) && !(getInternalEmitFlags(node) & InternalEmitFlags.NeverApplyImportHelper) && idText(specifier.propertyName || specifier.name) === "default"; const exportedValue = factory.createPropertyAccessExpression( exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, - specifier.propertyName || specifier.name); + specifier.propertyName || specifier.name, + ); statements.push( setOriginalNode( setTextRange( factory.createExpressionStatement( - createExportExpression(factory.getExportName(specifier), exportedValue, /*location*/ undefined, /*liveBinding*/ true) + createExportExpression(factory.getExportName(specifier), exportedValue, /*location*/ undefined, /*liveBinding*/ true), ), - specifier), - specifier - ) + specifier, + ), + specifier, + ), ); } } @@ -1612,16 +1645,19 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.createExpressionStatement( createExportExpression( factory.cloneNode(node.exportClause.name), - getHelperExpressionForExport(node, moduleKind !== ModuleKind.AMD ? - createRequireCall(node) : - isExportNamespaceAsDefaultDeclaration(node) ? generatedName : - factory.createIdentifier(idText(node.exportClause.name))) - ) + getHelperExpressionForExport( + node, + moduleKind !== ModuleKind.AMD ? + createRequireCall(node) : + isExportNamespaceAsDefaultDeclaration(node) ? generatedName : + factory.createIdentifier(idText(node.exportClause.name)), + ), + ), ), - node + node, ), - node - ) + node, + ), ); return singleOrMany(statements); @@ -1631,10 +1667,11 @@ export function transformModule(context: TransformationContext): (x: SourceFile return setOriginalNode( setTextRange( factory.createExpressionStatement( - emitHelpers().createExportStarHelper(moduleKind !== ModuleKind.AMD ? createRequireCall(node) : generatedName) + emitHelpers().createExportStarHelper(moduleKind !== ModuleKind.AMD ? createRequireCall(node) : generatedName), ), - node), - node + node, + ), + node, ); } } @@ -1660,7 +1697,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult { let statements: Statement[] | undefined; if (hasSyntacticModifier(node, ModifierFlags.Export)) { - statements = append(statements, + statements = append( + statements, setOriginalNode( setTextRange( factory.createFunctionDeclaration( @@ -1670,12 +1708,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, visitNodes(node.parameters, visitor, isParameter), /*type*/ undefined, - visitEachChild(node.body, visitor, context) + visitEachChild(node.body, visitor, context), ), - /*location*/ node + /*location*/ node, ), - /*original*/ node - ) + /*original*/ node, + ), ); } else { @@ -1694,7 +1732,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile function visitClassDeclaration(node: ClassDeclaration): VisitResult { let statements: Statement[] | undefined; if (hasSyntacticModifier(node, ModifierFlags.Export)) { - statements = append(statements, + statements = append( + statements, setOriginalNode( setTextRange( factory.createClassDeclaration( @@ -1702,12 +1741,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, visitNodes(node.heritageClauses, visitor, isHeritageClause), - visitNodes(node.members, visitor, isClassElement) + visitNodes(node.members, visitor, isClassElement), ), - node + node, ), - node - ) + node, + ), ); } else { @@ -1753,7 +1792,9 @@ export function transformModule(context: TransformationContext): (x: SourceFile /*type*/ undefined, createExportExpression( variable.name, - visitNode(variable.initializer, visitor, isExpression))); + visitNode(variable.initializer, visitor, isExpression), + ), + ); variables = append(variables, updatedVariable); } else { @@ -1766,17 +1807,17 @@ export function transformModule(context: TransformationContext): (x: SourceFile setTextRange( factory.createPropertyAccessExpression( factory.createIdentifier("exports"), - variable.name + variable.name, ), - /*location*/ variable.name + /*location*/ variable.name, ), - factory.createIdentifier(getTextOfIdentifierOrLiteral(variable.name)) + factory.createIdentifier(getTextOfIdentifierOrLiteral(variable.name)), ); const updatedVariable = factory.createVariableDeclaration( variable.name, variable.exclamationToken, variable.type, - visitNode(variable.initializer, visitor, isExpression) + visitNode(variable.initializer, visitor, isExpression), ); variables = append(variables, updatedVariable); @@ -1838,7 +1879,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile context, FlattenLevel.All, /*needsValue*/ false, - createAllExportExpressions + createAllExportExpressions, ); } else { @@ -1846,11 +1887,11 @@ export function transformModule(context: TransformationContext): (x: SourceFile setTextRange( factory.createPropertyAccessExpression( factory.createIdentifier("exports"), - node.name + node.name, ), - /*location*/ node.name + /*location*/ node.name, ), - node.initializer ? visitNode(node.initializer, visitor, isExpression) : factory.createVoidZero() + node.initializer ? visitNode(node.initializer, visitor, isExpression) : factory.createVoidZero(), ); } } @@ -2049,8 +2090,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile statement = factory.createExpressionStatement( createExportExpression( factory.createIdentifier("__esModule"), - factory.createTrue() - ) + factory.createTrue(), + ), ); } else { @@ -2062,10 +2103,10 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.createIdentifier("exports"), factory.createStringLiteral("__esModule"), factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("value", factory.createTrue()) - ]) - ] - ) + factory.createPropertyAssignment("value", factory.createTrue()), + ]), + ], + ), ); } setEmitFlags(statement, EmitFlags.CustomPrologue); @@ -2102,7 +2143,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile liveBinding && languageVersion !== ScriptTarget.ES3 ? factory.createCallExpression( factory.createPropertyAccessExpression( factory.createIdentifier("Object"), - "defineProperty" + "defineProperty", ), /*typeArguments*/ undefined, [ @@ -2110,25 +2151,28 @@ export function transformModule(context: TransformationContext): (x: SourceFile factory.createStringLiteralFromNode(name), factory.createObjectLiteralExpression([ factory.createPropertyAssignment("enumerable", factory.createTrue()), - factory.createPropertyAssignment("get", factory.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - /*parameters*/ [], - /*type*/ undefined, - factory.createBlock([factory.createReturnStatement(value)]) - )) - ]) - ] + factory.createPropertyAssignment( + "get", + factory.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, + factory.createBlock([factory.createReturnStatement(value)]), + ), + ), + ]), + ], ) : factory.createAssignment( factory.createPropertyAccessExpression( factory.createIdentifier("exports"), - factory.cloneNode(name) + factory.cloneNode(name), ), - value + value, ), - location + location, ); } @@ -2251,14 +2295,9 @@ export function transformModule(context: TransformationContext): (x: SourceFile noSubstitution[getNodeId(expression)] = true; if (!isIdentifier(expression) && !(getEmitFlags(node.expression) & EmitFlags.HelperName)) { return addInternalEmitFlags( - factory.updateCallExpression(node, - expression, - /*typeArguments*/ undefined, - node.arguments - ), - InternalEmitFlags.IndirectCall + factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, node.arguments), + InternalEmitFlags.IndirectCall, ); - } } return node; @@ -2270,12 +2309,8 @@ export function transformModule(context: TransformationContext): (x: SourceFile noSubstitution[getNodeId(tag)] = true; if (!isIdentifier(tag) && !(getEmitFlags(node.tag) & EmitFlags.HelperName)) { return addInternalEmitFlags( - factory.updateTaggedTemplateExpression(node, - tag, - /*typeArguments*/ undefined, - node.template - ), - InternalEmitFlags.IndirectCall + factory.updateTaggedTemplateExpression(node, tag, /*typeArguments*/ undefined, node.template), + InternalEmitFlags.IndirectCall, ); } } @@ -2302,9 +2337,9 @@ export function transformModule(context: TransformationContext): (x: SourceFile return setTextRange( factory.createPropertyAccessExpression( factory.createIdentifier("exports"), - factory.cloneNode(node) + factory.cloneNode(node), ), - /*location*/ node + /*location*/ node, ); } const importDeclaration = resolver.getReferencedImportDeclaration(node); @@ -2313,9 +2348,9 @@ export function transformModule(context: TransformationContext): (x: SourceFile return setTextRange( factory.createPropertyAccessExpression( factory.getGeneratedNameForNode(importDeclaration.parent), - factory.createIdentifier("default") + factory.createIdentifier("default"), ), - /*location*/ node + /*location*/ node, ); } else if (isImportSpecifier(importDeclaration)) { @@ -2323,9 +2358,9 @@ export function transformModule(context: TransformationContext): (x: SourceFile return setTextRange( factory.createPropertyAccessExpression( factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration), - factory.cloneNode(name) + factory.cloneNode(name), ), - /*location*/ node + /*location*/ node, ); } } @@ -2345,10 +2380,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile // - We do not substitute generated identifiers unless they are file-level reserved names. // - We do not substitute identifiers tagged with the LocalName flag. // - We only substitute identifiers that are exported at the top level. - if (isAssignmentOperator(node.operatorToken.kind) + if ( + isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) - && !isLocalName(node.left)) { + && !isLocalName(node.left) + ) { const exportedNames = getExports(node.left); if (exportedNames) { // For each additional export of the declaration, apply an export assignment. @@ -2414,5 +2451,5 @@ const dynamicImportUMDHelper: EmitHelper = { name: "typescript:dynamicimport-sync-require", scoped: true, text: ` - var __syncRequire = typeof module === "object" && typeof module.exports === "object";` + var __syncRequire = typeof module === "object" && typeof module.exports === "object";`, }; diff --git a/src/compiler/transformers/module/node.ts b/src/compiler/transformers/module/node.ts index 576c15fe6597e..7a36f5f8e86a0 100644 --- a/src/compiler/transformers/module/node.ts +++ b/src/compiler/transformers/module/node.ts @@ -71,7 +71,7 @@ export function transformNodeModule(context: TransformationContext) { return cjsOnEmitNode(hint, node, emitCallback); } - function getModuleTransformForFile(file: SourceFile): (typeof esmTransform) { + function getModuleTransformForFile(file: SourceFile): typeof esmTransform { return file.impliedNodeFormat === ModuleKind.ESNext ? esmTransform : cjsTransform; } diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index b83bf5244a7f3..61ff103dac829 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -142,7 +142,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory, startLexicalEnvironment, endLexicalEnvironment, - hoistVariableDeclaration + hoistVariableDeclaration, } = context; const compilerOptions = context.getCompilerOptions(); @@ -219,10 +219,10 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc /*typeParameters*/ undefined, [ factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction), - factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject) + factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject), ], /*type*/ undefined, - moduleBodyBlock + moduleBodyBlock, ); // Write the call to `System.register` @@ -241,13 +241,15 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] - : [dependencies, moduleBodyFunction] - ) - ) + : [dependencies, moduleBodyFunction], + ), + ), ]), - node.statements - ) - ), EmitFlags.NoTrailingComments); + node.statements, + ), + ), + EmitFlags.NoTrailingComments, + ); if (!outFile(compilerOptions)) { moveEmitHelpers(updated, moduleBodyBlock, helper => !helper.scoped); @@ -288,7 +290,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc groupIndices.set(text, dependencyGroups.length); dependencyGroups.push({ name: externalModuleName, - externalImports: [externalImport] + externalImports: [externalImport], }); } } @@ -367,11 +369,11 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc /*type*/ undefined, factory.createLogicalAnd( contextObject, - factory.createPropertyAccessExpression(contextObject, "id") - ) - ) - ]) - ) + factory.createPropertyAccessExpression(contextObject, "id"), + ), + ), + ]), + ), ); // Visit the synthetic external helpers import declaration if present @@ -397,10 +399,9 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.createModifiersFromModifierFlags(ModifierFlags.Async) : undefined; const moduleObject = factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("setters", - createSettersArray(exportStarFunction, dependencyGroups) - ), - factory.createPropertyAssignment("execute", + factory.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), + factory.createPropertyAssignment( + "execute", factory.createFunctionExpression( modifiers, /*asteriskToken*/ undefined, @@ -408,9 +409,9 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, - factory.createBlock(executeStatements, /*multiLine*/ true) - ) - ) + factory.createBlock(executeStatements, /*multiLine*/ true), + ), + ), ], /*multiLine*/ true); statements.push(factory.createReturnStatement(moduleObject)); @@ -463,8 +464,8 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc exportedNames.push( factory.createPropertyAssignment( factory.createStringLiteralFromNode(exportedLocalName), - factory.createTrue() - ) + factory.createTrue(), + ), ); } } @@ -478,10 +479,10 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc exportedNamesStorageRef, /*exclamationToken*/ undefined, /*type*/ undefined, - factory.createObjectLiteralExpression(exportedNames, /*multiLine*/ true) - ) - ]) - ) + factory.createObjectLiteralExpression(exportedNames, /*multiLine*/ true), + ), + ]), + ), ); const exportStarFunction = createExportStarFunction(exportedNamesStorageRef); @@ -509,9 +510,9 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.createCallExpression( factory.createPropertyAccessExpression(localNames, "hasOwnProperty"), /*typeArguments*/ undefined, - [n] - ) - ) + [n], + ), + ), ); } @@ -530,13 +531,13 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc exports, /*exclamationToken*/ undefined, /*type*/ undefined, - factory.createObjectLiteralExpression([]) - ) - ]) + factory.createObjectLiteralExpression([]), + ), + ]), ), factory.createForInStatement( factory.createVariableDeclarationList([ - factory.createVariableDeclaration(n) + factory.createVariableDeclaration(n), ]), m, factory.createBlock([ @@ -546,22 +547,22 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.createExpressionStatement( factory.createAssignment( factory.createElementAccessExpression(exports, n), - factory.createElementAccessExpression(m, n) - ) - ) + factory.createElementAccessExpression(m, n), + ), + ), ), - EmitFlags.SingleLine - ) - ]) + EmitFlags.SingleLine, + ), + ]), ), factory.createExpressionStatement( factory.createCallExpression( exportFunction, /*typeArguments*/ undefined, - [exports] - ) - ) - ], /*multiLine*/ true) + [exports], + ), + ), + ], /*multiLine*/ true), ); } @@ -594,8 +595,8 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc // save import into the local statements.push( factory.createExpressionStatement( - factory.createAssignment(importVariableName, parameterName) - ) + factory.createAssignment(importVariableName, parameterName), + ), ); if (hasSyntacticModifier(entry, ModifierFlags.Export)) { statements.push( @@ -606,9 +607,9 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc [ factory.createStringLiteral(idText(importVariableName)), parameterName, - ] - ) - ) + ], + ), + ), ); } break; @@ -632,9 +633,9 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.createStringLiteral(idText(e.name)), factory.createElementAccessExpression( parameterName, - factory.createStringLiteral(idText(e.propertyName || e.name)) - ) - ) + factory.createStringLiteral(idText(e.propertyName || e.name)), + ), + ), ); } @@ -643,9 +644,9 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.createCallExpression( exportFunction, /*typeArguments*/ undefined, - [factory.createObjectLiteralExpression(properties, /*multiLine*/ true)] - ) - ) + [factory.createObjectLiteralExpression(properties, /*multiLine*/ true)], + ), + ), ); } else { @@ -656,10 +657,10 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc /*typeArguments*/ undefined, [ factory.createStringLiteral(idText(entry.exportClause.name)), - parameterName - ] - ) - ) + parameterName, + ], + ), + ), ); } } @@ -674,9 +675,9 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.createCallExpression( exportStarFunction, /*typeArguments*/ undefined, - [parameterName] - ) - ) + [parameterName], + ), + ), ); } break; @@ -691,8 +692,8 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, - factory.createBlock(statements, /*multiLine*/ true) - ) + factory.createBlock(statements, /*multiLine*/ true), + ), ); } @@ -780,7 +781,8 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc */ function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult { if (hasSyntacticModifier(node, ModifierFlags.Export)) { - hoistedStatements = append(hoistedStatements, + hoistedStatements = append( + hoistedStatements, factory.updateFunctionDeclaration( node, visitNodes(node.modifiers, modifierVisitor, isModifierLike), @@ -789,7 +791,9 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc /*typeParameters*/ undefined, visitNodes(node.parameters, visitor, isParameter), /*type*/ undefined, - visitNode(node.body, visitor, isBlock))); + visitNode(node.body, visitor, isBlock), + ), + ); } else { hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context)); @@ -812,7 +816,8 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = append(statements, + statements = append( + statements, setTextRange( factory.createExpressionStatement( factory.createAssignment( @@ -823,14 +828,14 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc node.name, /*typeParameters*/ undefined, visitNodes(node.heritageClauses, visitor, isHeritageClause), - visitNodes(node.members, visitor, isClassElement) + visitNodes(node.members, visitor, isClassElement), ), - node - ) - ) + node, + ), + ), ), - node - ) + node, + ), ); statements = appendExportsOfHoistedDeclaration(statements, node); @@ -861,13 +866,13 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.getGeneratedNameForNode(variable.name), /*exclamationToken*/ undefined, /*type*/ undefined, - transformInitializedVariable(variable, /*isExportedDeclaration*/ false) + transformInitializedVariable(variable, /*isExportedDeclaration*/ false), )); } const declarationList = factory.updateVariableDeclarationList( node.declarationList, - declarations + declarations, ); statements = append(statements, factory.updateVariableStatement(node, modifiers, declarationList)); } @@ -937,7 +942,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc context, FlattenLevel.All, /*needsValue*/ false, - createAssignment + createAssignment, ) : node.initializer ? createAssignment(node.name, visitNode(node.initializer, visitor, isExpression)) : node.name; } @@ -1281,7 +1286,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc visitNode(node.initializer, isTopLevel ? visitForInitializer : discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) + visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context), ); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; @@ -1301,7 +1306,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc node, visitForInitializer(node.initializer), visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) + visitIterationBody(node.statement, topLevelNestedVisitor, context), ); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; @@ -1322,7 +1327,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc node.awaitModifier, visitForInitializer(node.initializer), visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) + visitIterationBody(node.statement, topLevelNestedVisitor, context), ); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; @@ -1371,7 +1376,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc return factory.updateDoStatement( node, visitIterationBody(node.statement, topLevelNestedVisitor, context), - visitNode(node.expression, visitor, isExpression) + visitNode(node.expression, visitor, isExpression), ); } @@ -1384,7 +1389,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc return factory.updateWhileStatement( node, visitNode(node.expression, visitor, isExpression), - visitIterationBody(node.statement, topLevelNestedVisitor, context) + visitIterationBody(node.statement, topLevelNestedVisitor, context), ); } @@ -1397,7 +1402,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc return factory.updateLabeledStatement( node, node.label, - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory.liftToBlock)) + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory.liftToBlock)), ); } @@ -1410,7 +1415,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc return factory.updateWithStatement( node, visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory.liftToBlock)) + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory.liftToBlock)), ); } @@ -1424,7 +1429,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc node, visitNode(node.expression, visitor, isExpression), Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory.liftToBlock)), - visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory.liftToBlock) + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory.liftToBlock), ); } @@ -1437,7 +1442,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc return factory.updateSwitchStatement( node, visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) + Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)), ); } @@ -1452,7 +1457,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc node = factory.updateCaseBlock( node, - visitNodes(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) + visitNodes(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause), ); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; @@ -1468,7 +1473,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc return factory.updateCaseClause( node, visitNode(node.expression, visitor, isExpression), - visitNodes(node.statements, topLevelNestedVisitor, isStatement) + visitNodes(node.statements, topLevelNestedVisitor, isStatement), ); } @@ -1502,7 +1507,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc node = factory.updateCatchClause( node, node.variableDeclaration, - Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) + Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)), ); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; @@ -1606,10 +1611,10 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc return factory.createCallExpression( factory.createPropertyAccessExpression( contextObject, - factory.createIdentifier("import") + factory.createIdentifier("import"), ), /*typeArguments*/ undefined, - argument ? [argument] : [] + argument ? [argument] : [], ); } @@ -1625,7 +1630,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc visitor, context, FlattenLevel.All, - !valueIsDiscarded + !valueIsDiscarded, ); } @@ -1675,11 +1680,13 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc // - We do not transform identifiers that were originally the name of an enum or // namespace due to how they are transformed in TypeScript. // - We only transform identifiers that are exported at the top level. - if ((node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) + if ( + (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) - && !isDeclarationNameOfEnumOrNamespace(node.operand)) { + && !isDeclarationNameOfEnumOrNamespace(node.operand) + ) { const exportedNames = getExports(node.operand); if (exportedNames) { let temp: Identifier | undefined; @@ -1823,10 +1830,10 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.cloneNode(name), factory.createPropertyAccessExpression( factory.getGeneratedNameForNode(importDeclaration.parent), - factory.createIdentifier("default") - ) + factory.createIdentifier("default"), + ), ), - /*location*/ node + /*location*/ node, ); } else if (isImportSpecifier(importDeclaration)) { @@ -1835,10 +1842,10 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc factory.cloneNode(name), factory.createPropertyAccessExpression( factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration), - factory.cloneNode(importDeclaration.propertyName || importDeclaration.name) + factory.cloneNode(importDeclaration.propertyName || importDeclaration.name), ), ), - /*location*/ node + /*location*/ node, ); } } @@ -1892,18 +1899,18 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc return setTextRange( factory.createPropertyAccessExpression( factory.getGeneratedNameForNode(importDeclaration.parent), - factory.createIdentifier("default") + factory.createIdentifier("default"), ), - /*location*/ node + /*location*/ node, ); } else if (isImportSpecifier(importDeclaration)) { return setTextRange( factory.createPropertyAccessExpression( factory.getGeneratedNameForNode(importDeclaration.parent?.parent?.parent || importDeclaration), - factory.cloneNode(importDeclaration.propertyName || importDeclaration.name) + factory.cloneNode(importDeclaration.propertyName || importDeclaration.name), ), - /*location*/ node + /*location*/ node, ); } } @@ -1924,10 +1931,12 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc // - We do not substitute generated identifiers unless they are file-level reserved names. // - We do not substitute identifiers tagged with the LocalName flag. // - We only substitute identifiers that are exported at the top level. - if (isAssignmentOperator(node.operatorToken.kind) + if ( + isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) - && !isLocalName(node.left)) { + && !isLocalName(node.left) + ) { const exportedNames = getExports(node.left); if (exportedNames) { // For each additional export of the declaration, apply an export assignment. diff --git a/src/compiler/transformers/namedEvaluation.ts b/src/compiler/transformers/namedEvaluation.ts index 5af5d90781e63..34123cf560080 100644 --- a/src/compiler/transformers/namedEvaluation.ts +++ b/src/compiler/transformers/namedEvaluation.ts @@ -47,7 +47,7 @@ import { SyntaxKind, TransformationContext, VariableDeclaration, - WrappedExpression + WrappedExpression, } from "../_namespaces/ts"; /** @@ -56,8 +56,10 @@ import { */ export function getAssignedNameOfIdentifier(factory: NodeFactory, name: Identifier, expression: WrappedExpression): StringLiteral { const original = getOriginalNode(skipOuterExpressions(expression)); - if ((isClassDeclaration(original) || isFunctionDeclaration(original)) && - !original.name && hasSyntacticModifier(original, ModifierFlags.Default)) { + if ( + (isClassDeclaration(original) || isFunctionDeclaration(original)) && + !original.name && hasSyntacticModifier(original, ModifierFlags.Default) + ) { return factory.createStringLiteral("default"); } return factory.createStringLiteralFromNode(name); @@ -119,17 +121,18 @@ export function createClassNamedEvaluationHelperBlock(context: TransformationCon /** @internal */ export type ClassNamedEvaluationHelperBlock = ClassStaticBlockDeclaration & { readonly body: Block & { - readonly statements: NodeArray & readonly [ - ExpressionStatement & { - readonly expression: CallExpression & { - readonly expression: Identifier; - }; - } - ]; + readonly statements: + & NodeArray + & readonly [ + ExpressionStatement & { + readonly expression: CallExpression & { + readonly expression: Identifier; + }; + }, + ]; }; }; - /** * Gets whether a node is a `static {}` block containing only a single call to the `__setFunctionName` helper where that * call's second argument is the value stored in the `assignedName` property of the block's `EmitNode`. @@ -173,13 +176,13 @@ export function injectClassNamedEvaluationHelperBlockIfMissing>; export function injectClassNamedEvaluationHelperBlockIfMissing( context: TransformationContext, node: ClassLikeDeclaration, assignedName: Expression, - thisExpression?: Expression + thisExpression?: Expression, ) { // given: // @@ -217,14 +220,16 @@ export function injectClassNamedEvaluationHelperBlockIfMissing( node.name, node.typeParameters, node.heritageClauses, - members) : + members, + ) : factory.updateClassExpression( node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, - members); + members, + ); getOrCreateEmitNode(node).assignedName = assignedName; return node; @@ -264,7 +269,8 @@ function transformNamedEvaluationOfPropertyAssignment(context: TransformationCon return factory.updatePropertyAssignment( node, name, - initializer); + initializer, + ); } function transformNamedEvaluationOfShorthandAssignmentProperty(context: TransformationContext, node: NamedEvaluation & ShorthandPropertyAssignment, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { @@ -283,7 +289,8 @@ function transformNamedEvaluationOfShorthandAssignmentProperty(context: Transfor return factory.updateShorthandPropertyAssignment( node, node.name, - objectAssignmentInitializer); + objectAssignmentInitializer, + ); } function transformNamedEvaluationOfVariableDeclaration(context: TransformationContext, node: NamedEvaluation & VariableDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { @@ -310,7 +317,8 @@ function transformNamedEvaluationOfVariableDeclaration(context: TransformationCo node.name, node.exclamationToken, node.type, - initializer); + initializer, + ); } function transformNamedEvaluationOfParameterDeclaration(context: TransformationContext, node: NamedEvaluation & ParameterDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { @@ -341,7 +349,8 @@ function transformNamedEvaluationOfParameterDeclaration(context: TransformationC node.name, node.questionToken, node.type, - initializer); + initializer, + ); } function transformNamedEvaluationOfBindingElement(context: TransformationContext, node: NamedEvaluation & BindingElement, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { @@ -370,7 +379,8 @@ function transformNamedEvaluationOfBindingElement(context: TransformationContext node.dotDotDotToken, node.propertyName, node.name, - initializer); + initializer, + ); } function transformNamedEvaluationOfPropertyDeclaration(context: TransformationContext, node: NamedEvaluation & PropertyDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { @@ -390,7 +400,8 @@ function transformNamedEvaluationOfPropertyDeclaration(context: TransformationCo name, node.questionToken ?? node.exclamationToken, node.type, - initializer); + initializer, + ); } function transformNamedEvaluationOfAssignmentExpression(context: TransformationContext, node: NamedEvaluation & BinaryExpression, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { @@ -428,7 +439,8 @@ function transformNamedEvaluationOfAssignmentExpression(context: TransformationC node, node.left, node.operatorToken, - right); + right, + ); } function transformNamedEvaluationOfExportAssignment(context: TransformationContext, node: NamedEvaluation & ExportAssignment, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { @@ -448,7 +460,8 @@ function transformNamedEvaluationOfExportAssignment(context: TransformationConte return factory.updateExportAssignment( node, node.modifiers, - expression); + expression, + ); } /** diff --git a/src/compiler/transformers/taggedTemplate.ts b/src/compiler/transformers/taggedTemplate.ts index ca23140c0d448..a905dcb26ecb8 100644 --- a/src/compiler/transformers/taggedTemplate.ts +++ b/src/compiler/transformers/taggedTemplate.ts @@ -28,7 +28,7 @@ import { /** @internal */ export enum ProcessLevel { LiftRestriction, - All + All, } /** @internal */ @@ -38,8 +38,8 @@ export function processTaggedTemplateExpression( visitor: Visitor, currentSourceFile: SourceFile, recordTaggedTemplateString: (temp: Identifier) => void, - level: ProcessLevel): CallExpression | TaggedTemplateExpression { - + level: ProcessLevel, +): CallExpression | TaggedTemplateExpression { // Visit the tag expression const tag = visitNode(node.tag, visitor, isExpression); Debug.assert(tag); @@ -74,7 +74,8 @@ export function processTaggedTemplateExpression( const helperCall = context.getEmitHelperFactory().createTemplateObjectHelper( factory.createArrayLiteralExpression(cookedStrings), - factory.createArrayLiteralExpression(rawStrings)); + factory.createArrayLiteralExpression(rawStrings), + ); // Create a variable to cache the template object if we're in a module. // Do not do this in the global scope, as any variable we currently generate could conflict with @@ -86,7 +87,8 @@ export function processTaggedTemplateExpression( tempVar, factory.createAssignment( tempVar, - helperCall) + helperCall, + ), ); } else { @@ -111,8 +113,7 @@ function getRawLiteral(factory: NodeFactory, node: TemplateLiteralLikeNode, curr // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". let text = node.rawText; if (text === undefined) { - Debug.assertIsDefined(currentSourceFile, - "Template literal node is missing 'rawText' and does not have a source file. Possibly bad transform."); + Debug.assertIsDefined(currentSourceFile, "Template literal node is missing 'rawText' and does not have a source file. Possibly bad transform."); text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node); // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 04e56401f9dba..00eb218342e00 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -196,7 +196,7 @@ import { visitNode, visitNodes, visitParameterList, - VisitResult + VisitResult, } from "../_namespaces/ts"; /** @@ -208,7 +208,7 @@ const enum TypeScriptSubstitutionFlags { /** Enables substitutions for namespace exports. */ NamespaceExports = 1 << 1, /* Enables substitutions for unqualified enum members */ - NonQualifiedEnumMembers = 1 << 3 + NonQualifiedEnumMembers = 1 << 3, } const enum ClassFacts { @@ -286,12 +286,15 @@ export function transformTypeScript(context: TransformationContext) { } function transformBundle(node: Bundle) { - return factory.createBundle(node.sourceFiles.map(transformSourceFile), mapDefined(node.prepends, prepend => { - if (prepend.kind === SyntaxKind.InputFiles) { - return createUnparsedSourceFile(prepend, "js"); - } - return prepend; - })); + return factory.createBundle( + node.sourceFiles.map(transformSourceFile), + mapDefined(node.prepends, prepend => { + if (prepend.kind === SyntaxKind.InputFiles) { + return createUnparsedSourceFile(prepend, "js"); + } + return prepend; + }), + ); } /** @@ -465,11 +468,13 @@ export function transformTypeScript(context: TransformationContext) { * @param node The node to visit. */ function namespaceElementVisitorWorker(node: Node): VisitResult { - if (node.kind === SyntaxKind.ExportDeclaration || + if ( + node.kind === SyntaxKind.ExportDeclaration || node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportClause || (node.kind === SyntaxKind.ImportEqualsDeclaration && - (node as ImportEqualsDeclaration).moduleReference.kind === SyntaxKind.ExternalModuleReference)) { + (node as ImportEqualsDeclaration).moduleReference.kind === SyntaxKind.ExternalModuleReference) + ) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -641,7 +646,6 @@ export function transformTypeScript(context: TransformationContext) { case SyntaxKind.LiteralType: // TypeScript type nodes are elided. // falls through - case SyntaxKind.IndexSignature: // TypeScript index signatures are elided. return undefined; @@ -790,13 +794,14 @@ export function transformTypeScript(context: TransformationContext) { return factory.updateSourceFile( node, - visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); + visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict), + ); } function visitObjectLiteralExpression(node: ObjectLiteralExpression) { return factory.updateObjectLiteralExpression( node, - visitNodes(node.properties, getObjectLiteralElementVisitor(node), isObjectLiteralElementLike) + visitNodes(node.properties, getObjectLiteralElementVisitor(node), isObjectLiteralElementLike), ); } @@ -829,16 +834,18 @@ export function transformTypeScript(context: TransformationContext) { const promoteToIIFE = languageVersion <= ScriptTarget.ES5 && !!(facts & ClassFacts.MayNeedImmediatelyInvokedFunctionExpression); - if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && + if ( + !isClassLikeDeclarationWithTypeScriptSyntax(node) && !classOrConstructorParameterIsDecorated(legacyDecorators, node) && - !isExportOfNamespace(node)) { + !isExportOfNamespace(node) + ) { return factory.updateClassDeclaration( node, visitNodes(node.modifiers, modifierVisitor, isModifier), node.name, /*typeParameters*/ undefined, visitNodes(node.heritageClauses, visitor, isHeritageClause), - visitNodes(node.members, getClassElementVisitor(node), isClassElement) + visitNodes(node.members, getClassElementVisitor(node), isClassElement), ); } @@ -846,8 +853,7 @@ export function transformTypeScript(context: TransformationContext) { context.startLexicalEnvironment(); } - const moveModifiers = - promoteToIIFE || + const moveModifiers = promoteToIIFE || facts & ClassFacts.IsExportOfNamespace; // elide modifiers on the declaration if we are emitting an IIFE or the class is @@ -861,8 +867,7 @@ export function transformTypeScript(context: TransformationContext) { modifiers = injectClassTypeMetadata(modifiers, node); } - const needsName = - moveModifiers && !node.name || + const needsName = moveModifiers && !node.name || facts & ClassFacts.HasMemberDecorators || facts & ClassFacts.HasStaticInitializedProperties; @@ -879,7 +884,7 @@ export function transformTypeScript(context: TransformationContext) { name, /*typeParameters*/ undefined, visitNodes(node.heritageClauses, visitor, isHeritageClause), - transformClassMembers(node) + transformClassMembers(node), ); // To better align with the old emitter, we should not emit a trailing source map @@ -929,13 +934,13 @@ export function transformTypeScript(context: TransformationContext) { factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*exclamationToken*/ undefined, /*type*/ undefined, - iife + iife, ); setOriginalNode(varDecl, node); const varStatement = factory.createVariableStatement( /*modifiers*/ undefined, - factory.createVariableDeclarationList([varDecl], NodeFlags.Let) + factory.createVariableDeclarationList([varDecl], NodeFlags.Let), ); setOriginalNode(varStatement, node); setCommentRange(varStatement, node); @@ -951,19 +956,19 @@ export function transformTypeScript(context: TransformationContext) { if (facts & ClassFacts.IsExportOfNamespace) { return [ statement, - createExportMemberAssignmentStatement(node) + createExportMemberAssignmentStatement(node), ]; } if (facts & ClassFacts.IsDefaultExternalExport) { return [ statement, - factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)), ]; } if (facts & ClassFacts.IsNamedExternalExport) { return [ statement, - factory.createExternalModuleExport(factory.getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + factory.createExternalModuleExport(factory.getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)), ]; } } @@ -983,7 +988,7 @@ export function transformTypeScript(context: TransformationContext) { node.name, /*typeParameters*/ undefined, visitNodes(node.heritageClauses, visitor, isHeritageClause), - transformClassMembers(node) + transformClassMembers(node), ); } @@ -1007,7 +1012,8 @@ export function transformTypeScript(context: TransformationContext) { parameter.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined); + /*initializer*/ undefined, + ); setOriginalNode(parameterProperty, parameter); newMembers = append(newMembers, parameterProperty); } @@ -1136,7 +1142,7 @@ export function transformTypeScript(context: TransformationContext) { * * @param node The node to test. */ - function shouldAddParamTypesMetadata(node: Declaration): node is ClassLikeDeclaration & { _hasConstructorBrand: never } | MethodDeclaration | AccessorDeclaration { + function shouldAddParamTypesMetadata(node: Declaration): node is ClassLikeDeclaration & { _hasConstructorBrand: never; } | MethodDeclaration | AccessorDeclaration { switch (node.kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: @@ -1228,7 +1234,7 @@ export function transformTypeScript(context: TransformationContext) { return factory.updateExpressionWithTypeArguments( node, Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression)), - /*typeArguments*/ undefined + /*typeArguments*/ undefined, ); } @@ -1238,7 +1244,7 @@ export function transformTypeScript(context: TransformationContext) { * * @param node The declaration node. */ - function shouldEmitFunctionLikeDeclaration(node: T): node is T & { body: NonNullable } { + function shouldEmitFunctionLikeDeclaration(node: T): node is T & { body: NonNullable; } { return !nodeIsMissing(node.body); } @@ -1263,7 +1269,7 @@ export function transformTypeScript(context: TransformationContext) { Debug.checkDefined(visitNode(node.name, visitor, isPropertyName)), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined + /*initializer*/ undefined, ); } @@ -1273,7 +1279,7 @@ export function transformTypeScript(context: TransformationContext) { visitPropertyNameOfClassElement(node), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression), ); } @@ -1286,7 +1292,7 @@ export function transformTypeScript(context: TransformationContext) { node, /*modifiers*/ undefined, visitParameterList(node.parameters, visitor, context), - transformConstructorBody(node.body, node) + transformConstructorBody(node.body, node), ); } @@ -1303,7 +1309,8 @@ export function transformTypeScript(context: TransformationContext) { /*statementOffset*/ 0, superPath, superPathDepth + 1, - initializerStatements); + initializerStatements, + ); const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); @@ -1312,7 +1319,8 @@ export function transformTypeScript(context: TransformationContext) { superStatement, factory.updateBlock(superStatement.tryBlock, tryBlockStatements), visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock))); + visitNode(superStatement.finallyBlock, visitor, isBlock), + )); } else { addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); @@ -1392,18 +1400,18 @@ export function transformTypeScript(context: TransformationContext) { setTextRange( factory.createPropertyAccessExpression( factory.createThis(), - propertyName + propertyName, ), - node.name + node.name, ), - localName - ) + localName, + ), ), - node + node, ), - moveRangePos(node, -1) - ) - ) + moveRangePos(node, -1), + ), + ), ); } @@ -1431,7 +1439,7 @@ export function transformTypeScript(context: TransformationContext) { /*typeParameters*/ undefined, visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - visitFunctionBody(node.body, visitor, context) + visitFunctionBody(node.body, visitor, context), ); } @@ -1466,7 +1474,7 @@ export function transformTypeScript(context: TransformationContext) { visitPropertyNameOfClassElement(node), visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - visitFunctionBody(node.body, visitor, context) || factory.createBlock([]) + visitFunctionBody(node.body, visitor, context) || factory.createBlock([]), ); } @@ -1490,7 +1498,7 @@ export function transformTypeScript(context: TransformationContext) { modifiers, visitPropertyNameOfClassElement(node), visitParameterList(node.parameters, visitor, context), - visitFunctionBody(node.body, visitor, context) || factory.createBlock([]) + visitFunctionBody(node.body, visitor, context) || factory.createBlock([]), ); } @@ -1506,7 +1514,7 @@ export function transformTypeScript(context: TransformationContext) { /*typeParameters*/ undefined, visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - visitFunctionBody(node.body, visitor, context) || factory.createBlock([]) + visitFunctionBody(node.body, visitor, context) || factory.createBlock([]), ); if (isExportOfNamespace(node)) { const statements: Statement[] = [updated]; @@ -1528,7 +1536,7 @@ export function transformTypeScript(context: TransformationContext) { /*typeParameters*/ undefined, visitParameterList(node.parameters, visitor, context), /*type*/ undefined, - visitFunctionBody(node.body, visitor, context) || factory.createBlock([]) + visitFunctionBody(node.body, visitor, context) || factory.createBlock([]), ); return updated; } @@ -1558,7 +1566,7 @@ export function transformTypeScript(context: TransformationContext) { Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), /*questionToken*/ undefined, /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression) + visitNode(node.initializer, visitor, isExpression), ); if (updated !== node) { // While we emit the source map for the node after skipping decorators and modifiers, @@ -1582,10 +1590,10 @@ export function transformTypeScript(context: TransformationContext) { return setTextRange( factory.createExpressionStatement( factory.inlineExpressions( - map(variables, transformInitializedVariable) - ) + map(variables, transformInitializedVariable), + ), ), - node + node, ); } else { @@ -1602,16 +1610,16 @@ export function transformTypeScript(context: TransformationContext) { context, FlattenLevel.All, /*needsValue*/ false, - createNamespaceExportExpression + createNamespaceExportExpression, ); } else { return setTextRange( factory.createAssignment( getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), - Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)) + Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)), ), - /*location*/ node + /*location*/ node, ); } } @@ -1622,7 +1630,8 @@ export function transformTypeScript(context: TransformationContext) { Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), /*exclamationToken*/ undefined, /*type*/ undefined, - visitNode(node.initializer, visitor, isExpression)); + visitNode(node.initializer, visitor, isExpression), + ); if (node.type) { setTypeNode(updated.name, node.type); } @@ -1683,7 +1692,8 @@ export function transformTypeScript(context: TransformationContext) { node, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), /*typeArguments*/ undefined, - visitNodes(node.arguments, visitor, isExpression)); + visitNodes(node.arguments, visitor, isExpression), + ); } function visitNewExpression(node: NewExpression) { @@ -1691,7 +1701,8 @@ export function transformTypeScript(context: TransformationContext) { node, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), /*typeArguments*/ undefined, - visitNodes(node.arguments, visitor, isExpression)); + visitNodes(node.arguments, visitor, isExpression), + ); } function visitTaggedTemplateExpression(node: TaggedTemplateExpression) { @@ -1699,7 +1710,8 @@ export function transformTypeScript(context: TransformationContext) { node, Debug.checkDefined(visitNode(node.tag, visitor, isExpression)), /*typeArguments*/ undefined, - Debug.checkDefined(visitNode(node.template, visitor, isTemplateLiteral))); + Debug.checkDefined(visitNode(node.template, visitor, isTemplateLiteral)), + ); } function visitJsxSelfClosingElement(node: JsxSelfClosingElement) { @@ -1707,7 +1719,8 @@ export function transformTypeScript(context: TransformationContext) { node, Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)), /*typeArguments*/ undefined, - Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes))); + Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes)), + ); } function visitJsxJsxOpeningElement(node: JsxOpeningElement) { @@ -1715,7 +1728,8 @@ export function transformTypeScript(context: TransformationContext) { node, Debug.checkDefined(visitNode(node.tagName, visitor, isJsxTagNameExpression)), /*typeArguments*/ undefined, - Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes))); + Debug.checkDefined(visitNode(node.attributes, visitor, isJsxAttributes)), + ); } /** @@ -1770,14 +1784,13 @@ export function transformTypeScript(context: TransformationContext) { // x || (x = {}) // exports.x || (exports.x = {}) - let moduleArg = - factory.createLogicalOr( + let moduleArg = factory.createLogicalOr( + exportName, + factory.createAssignment( exportName, - factory.createAssignment( - exportName, - factory.createObjectLiteralExpression() - ) - ); + factory.createObjectLiteralExpression(), + ), + ); if (isExportOfNamespace(node)) { // `localName` is the expression used within this node's containing scope for any local references. @@ -1800,11 +1813,11 @@ export function transformTypeScript(context: TransformationContext) { /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, - transformEnumBody(node, containerName) + transformEnumBody(node, containerName), ), /*typeArguments*/ undefined, - [moduleArg] - ) + [moduleArg], + ), ); setOriginalNode(enumStatement, node); @@ -1838,7 +1851,7 @@ export function transformTypeScript(context: TransformationContext) { currentNamespaceContainerName = savedCurrentNamespaceLocalName; return factory.createBlock( setTextRange(factory.createNodeArray(statements), /*location*/ node.members), - /*multiLine*/ true + /*multiLine*/ true, ); } @@ -1856,27 +1869,27 @@ export function transformTypeScript(context: TransformationContext) { const innerAssignment = factory.createAssignment( factory.createElementAccessExpression( currentNamespaceContainerName, - name + name, ), - valueExpression + valueExpression, ); const outerAssignment = valueExpression.kind === SyntaxKind.StringLiteral ? innerAssignment : factory.createAssignment( factory.createElementAccessExpression( currentNamespaceContainerName, - innerAssignment + innerAssignment, ), - name + name, ); return setTextRange( factory.createExpressionStatement( setTextRange( outerAssignment, - member - ) + member, + ), ), - member + member, ); } @@ -1960,7 +1973,7 @@ export function transformTypeScript(context: TransformationContext) { const varFlags = currentLexicalScope.kind === SyntaxKind.SourceFile ? NodeFlags.None : NodeFlags.Let; const statement = factory.createVariableStatement( visitNodes(node.modifiers, modifierVisitor, isModifier), - factory.createVariableDeclarationList([varDecl], varFlags) + factory.createVariableDeclarationList([varDecl], varFlags), ); setOriginalNode(varDecl, node); @@ -2053,14 +2066,13 @@ export function transformTypeScript(context: TransformationContext) { // x || (x = {}) // exports.x || (exports.x = {}) - let moduleArg = - factory.createLogicalOr( + let moduleArg = factory.createLogicalOr( + exportName, + factory.createAssignment( exportName, - factory.createAssignment( - exportName, - factory.createObjectLiteralExpression() - ) - ); + factory.createObjectLiteralExpression(), + ), + ); if (isExportOfNamespace(node)) { // `localName` is the expression used within this node's containing scope for any local references. @@ -2082,11 +2094,11 @@ export function transformTypeScript(context: TransformationContext) { /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], /*type*/ undefined, - transformModuleBody(node, containerName) + transformModuleBody(node, containerName), ), /*typeArguments*/ undefined, - [moduleArg] - ) + [moduleArg], + ), ); setOriginalNode(moduleStatement, node); @@ -2150,9 +2162,9 @@ export function transformTypeScript(context: TransformationContext) { const block = factory.createBlock( setTextRange( factory.createNodeArray(statements), - /*location*/ statementsLocation + /*location*/ statementsLocation, ), - /*multiLine*/ true + /*multiLine*/ true, ); setTextRange(block, blockLocation); @@ -2208,14 +2220,15 @@ export function transformTypeScript(context: TransformationContext) { // Elide the declaration if the import clause was elided. const importClause = visitNode(node.importClause, visitImportClause, isImportClause); return importClause || - compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve || - compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error + compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve || + compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error ? factory.updateImportDeclaration( node, /*modifiers*/ undefined, importClause, node.moduleSpecifier, - node.assertClause) + node.assertClause, + ) : undefined; } @@ -2245,8 +2258,9 @@ export function transformTypeScript(context: TransformationContext) { else { // Elide named imports if all of its import specifiers are elided and settings allow. const allowEmpty = compilerOptions.verbatimModuleSyntax || compilerOptions.preserveValueImports && ( - compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve || - compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error); + compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve || + compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error + ); const elements = visitNodes(node.elements, visitImportSpecifier, isImportSpecifier); return allowEmpty || some(elements) ? factory.updateNamedImports(node, elements) : undefined; } @@ -2293,12 +2307,14 @@ export function transformTypeScript(context: TransformationContext) { // Elide the export declaration if all of its named exports are elided. const allowEmpty = compilerOptions.verbatimModuleSyntax || !!node.moduleSpecifier && ( - compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve || - compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error); + compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve || + compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error + ); const exportClause = visitNode( node.exportClause, (bindings: NamedExportBindings) => visitNamedExportBindings(bindings, allowEmpty), - isNamedExportBindings); + isNamedExportBindings, + ); return exportClause ? factory.updateExportDeclaration( @@ -2307,7 +2323,8 @@ export function transformTypeScript(context: TransformationContext) { node.isTypeOnly, exportClause, node.moduleSpecifier, - node.assertClause) + node.assertClause, + ) : undefined; } @@ -2376,7 +2393,7 @@ export function transformTypeScript(context: TransformationContext) { /*modifiers*/ undefined, /*importClause*/ undefined, node.moduleReference.expression, - /*assertClause*/ undefined + /*assertClause*/ undefined, ), node, ), @@ -2407,15 +2424,15 @@ export function transformTypeScript(context: TransformationContext) { node.name, /*exclamationToken*/ undefined, /*type*/ undefined, - moduleReference + moduleReference, ), - node - ) - ]) + node, + ), + ]), ), - node + node, ), - node + node, ); } else { @@ -2424,9 +2441,9 @@ export function transformTypeScript(context: TransformationContext) { createNamespaceExport( node.name, moduleReference, - node + node, ), - node + node, ); } } @@ -2472,7 +2489,7 @@ export function transformTypeScript(context: TransformationContext) { function createExportMemberAssignmentStatement(node: ClassDeclaration | FunctionDeclaration) { const expression = factory.createAssignment( factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), - factory.getLocalName(node) + factory.getLocalName(node), ); setSourceMapRange(expression, createRange(node.name ? node.name.pos : node.pos, node.end)); @@ -2490,10 +2507,10 @@ export function transformTypeScript(context: TransformationContext) { factory.createExpressionStatement( factory.createAssignment( factory.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), - exportValue - ) + exportValue, + ), ), - location + location, ); } @@ -2640,13 +2657,12 @@ export function transformTypeScript(context: TransformationContext) { // an identifier that is exported from a merged namespace. const container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); if (container && container.kind !== SyntaxKind.SourceFile) { - const substitute = - (applicableSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports && container.kind === SyntaxKind.ModuleDeclaration) || + const substitute = (applicableSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports && container.kind === SyntaxKind.ModuleDeclaration) || (applicableSubstitutions & TypeScriptSubstitutionFlags.NonQualifiedEnumMembers && container.kind === SyntaxKind.EnumDeclaration); if (substitute) { return setTextRange( factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), - /*location*/ node + /*location*/ node, ); } } diff --git a/src/compiler/transformers/typeSerializer.ts b/src/compiler/transformers/typeSerializer.ts index 831a581b8258b..5db6762696316 100644 --- a/src/compiler/transformers/typeSerializer.ts +++ b/src/compiler/transformers/typeSerializer.ts @@ -72,20 +72,15 @@ import { /** @internal */ export type SerializedEntityName = | Identifier // Globals (i.e., `String`, `Number`, etc.) - // Globals (i.e., `String`, `Number`, etc.) | PropertyAccessEntityNameExpression // `A.B` - // `A.B` - ; - +; /** @internal */ export type SerializedTypeNode = | SerializedEntityName | ConditionalExpression // Type Reference or Global fallback - // Type Reference or Global fallback | VoidExpression // `void 0` used for null/undefined/never - // `void 0` used for null/undefined/never - ; +; /** @internal */ export interface RuntimeTypeSerializerContext { @@ -137,7 +132,7 @@ export interface RuntimeTypeSerializer { export function createRuntimeTypeSerializer(context: TransformationContext): RuntimeTypeSerializer { const { factory, - hoistVariableDeclaration + hoistVariableDeclaration, } = context; const resolver = context.getEmitResolver(); @@ -203,12 +198,11 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run * @param node The node that should have its type serialized. */ function serializeParameterTypesOfNode(node: Node, container: ClassLikeDeclaration): ArrayLiteralExpression { - const valueDeclaration = - isClassLike(node) - ? getFirstConstructorWithBody(node) - : isFunctionLike(node) && nodeIsPresent((node as FunctionLikeDeclaration).body) - ? node - : undefined; + const valueDeclaration = isClassLike(node) + ? getFirstConstructorWithBody(node) + : isFunctionLike(node) && nodeIsPresent((node as FunctionLikeDeclaration).body) + ? node + : undefined; const expressions: SerializedTypeNode[] = []; if (valueDeclaration) { @@ -456,45 +450,36 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run return ( // temp vars used in fallback isGeneratedIdentifier(left) ? isGeneratedIdentifier(right) : - - // entity names - isIdentifier(left) ? isIdentifier(right) - && left.escapedText === right.escapedText : - - isPropertyAccessExpression(left) ? isPropertyAccessExpression(right) - && equateSerializedTypeNodes(left.expression, right.expression) - && equateSerializedTypeNodes(left.name, right.name) : - - // `void 0` - isVoidExpression(left) ? isVoidExpression(right) - && isNumericLiteral(left.expression) && left.expression.text === "0" - && isNumericLiteral(right.expression) && right.expression.text === "0" : - - // `"undefined"` or `"function"` in `typeof` checks - isStringLiteral(left) ? isStringLiteral(right) - && left.text === right.text : - - // used in `typeof` checks for fallback - isTypeOfExpression(left) ? isTypeOfExpression(right) - && equateSerializedTypeNodes(left.expression, right.expression) : - - // parens in `typeof` checks with temps - isParenthesizedExpression(left) ? isParenthesizedExpression(right) - && equateSerializedTypeNodes(left.expression, right.expression) : - - // conditionals used in fallback - isConditionalExpression(left) ? isConditionalExpression(right) - && equateSerializedTypeNodes(left.condition, right.condition) - && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) - && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : - - // logical binary and assignments used in fallback - isBinaryExpression(left) ? isBinaryExpression(right) - && left.operatorToken.kind === right.operatorToken.kind - && equateSerializedTypeNodes(left.left, right.left) - && equateSerializedTypeNodes(left.right, right.right) : - - false + // entity names + isIdentifier(left) ? isIdentifier(right) + && left.escapedText === right.escapedText : + isPropertyAccessExpression(left) ? isPropertyAccessExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) + && equateSerializedTypeNodes(left.name, right.name) : + // `void 0` + isVoidExpression(left) ? isVoidExpression(right) + && isNumericLiteral(left.expression) && left.expression.text === "0" + && isNumericLiteral(right.expression) && right.expression.text === "0" : + // `"undefined"` or `"function"` in `typeof` checks + isStringLiteral(left) ? isStringLiteral(right) + && left.text === right.text : + // used in `typeof` checks for fallback + isTypeOfExpression(left) ? isTypeOfExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // parens in `typeof` checks with temps + isParenthesizedExpression(left) ? isParenthesizedExpression(right) + && equateSerializedTypeNodes(left.expression, right.expression) : + // conditionals used in fallback + isConditionalExpression(left) ? isConditionalExpression(right) + && equateSerializedTypeNodes(left.condition, right.condition) + && equateSerializedTypeNodes(left.whenTrue, right.whenTrue) + && equateSerializedTypeNodes(left.whenFalse, right.whenFalse) : + // logical binary and assignments used in fallback + isBinaryExpression(left) ? isBinaryExpression(right) + && left.operatorToken.kind === right.operatorToken.kind + && equateSerializedTypeNodes(left.left, right.left) + && equateSerializedTypeNodes(left.right, right.right) : + false ); } @@ -518,7 +503,7 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run /*questionToken*/ undefined, temp, /*colonToken*/ undefined, - factory.createIdentifier("Object") + factory.createIdentifier("Object"), ); case TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: @@ -573,7 +558,7 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run function createCheckedValue(left: Expression, right: Expression) { return factory.createLogicalAnd( factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), - right + right, ); } @@ -597,9 +582,9 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run return factory.createLogicalAnd( factory.createLogicalAnd( left.left, - factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero()) + factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero()), ), - factory.createPropertyAccessExpression(temp, node.right) + factory.createPropertyAccessExpression(temp, node.right), ); } @@ -636,7 +621,7 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run /*questionToken*/ undefined, factory.createIdentifier(name), /*colonToken*/ undefined, - factory.createIdentifier("Object") + factory.createIdentifier("Object"), ); } diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts index d01206af9057f..900a409ee9681 100644 --- a/src/compiler/transformers/utilities.ts +++ b/src/compiler/transformers/utilities.ts @@ -86,7 +86,7 @@ import { TransformationContext, unorderedRemoveItem, VariableDeclaration, - VariableStatement + VariableStatement, } from "../_namespaces/ts"; /** @internal */ @@ -463,22 +463,36 @@ export function isCompoundAssignment(kind: BinaryOperator): kind is CompoundAssi /** @internal */ export function getNonAssignmentOperatorForCompoundAssignment(kind: CompoundAssignmentOperator): LogicalOperatorOrHigher | SyntaxKind.QuestionQuestionToken { switch (kind) { - case SyntaxKind.PlusEqualsToken: return SyntaxKind.PlusToken; - case SyntaxKind.MinusEqualsToken: return SyntaxKind.MinusToken; - case SyntaxKind.AsteriskEqualsToken: return SyntaxKind.AsteriskToken; - case SyntaxKind.AsteriskAsteriskEqualsToken: return SyntaxKind.AsteriskAsteriskToken; - case SyntaxKind.SlashEqualsToken: return SyntaxKind.SlashToken; - case SyntaxKind.PercentEqualsToken: return SyntaxKind.PercentToken; - case SyntaxKind.LessThanLessThanEqualsToken: return SyntaxKind.LessThanLessThanToken; - case SyntaxKind.GreaterThanGreaterThanEqualsToken: return SyntaxKind.GreaterThanGreaterThanToken; - case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: return SyntaxKind.GreaterThanGreaterThanGreaterThanToken; - case SyntaxKind.AmpersandEqualsToken: return SyntaxKind.AmpersandToken; - case SyntaxKind.BarEqualsToken: return SyntaxKind.BarToken; - case SyntaxKind.CaretEqualsToken: return SyntaxKind.CaretToken; - case SyntaxKind.BarBarEqualsToken: return SyntaxKind.BarBarToken; - case SyntaxKind.AmpersandAmpersandEqualsToken: return SyntaxKind.AmpersandAmpersandToken; - case SyntaxKind.QuestionQuestionEqualsToken: return SyntaxKind.QuestionQuestionToken; - + case SyntaxKind.PlusEqualsToken: + return SyntaxKind.PlusToken; + case SyntaxKind.MinusEqualsToken: + return SyntaxKind.MinusToken; + case SyntaxKind.AsteriskEqualsToken: + return SyntaxKind.AsteriskToken; + case SyntaxKind.AsteriskAsteriskEqualsToken: + return SyntaxKind.AsteriskAsteriskToken; + case SyntaxKind.SlashEqualsToken: + return SyntaxKind.SlashToken; + case SyntaxKind.PercentEqualsToken: + return SyntaxKind.PercentToken; + case SyntaxKind.LessThanLessThanEqualsToken: + return SyntaxKind.LessThanLessThanToken; + case SyntaxKind.GreaterThanGreaterThanEqualsToken: + return SyntaxKind.GreaterThanGreaterThanToken; + case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + return SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + case SyntaxKind.AmpersandEqualsToken: + return SyntaxKind.AmpersandToken; + case SyntaxKind.BarEqualsToken: + return SyntaxKind.BarToken; + case SyntaxKind.CaretEqualsToken: + return SyntaxKind.CaretToken; + case SyntaxKind.BarBarEqualsToken: + return SyntaxKind.BarBarToken; + case SyntaxKind.AmpersandAmpersandEqualsToken: + return SyntaxKind.AmpersandAmpersandToken; + case SyntaxKind.QuestionQuestionEqualsToken: + return SyntaxKind.QuestionQuestionToken; } } @@ -642,7 +656,7 @@ export function getAllDecoratorsOfClass(node: ClassLikeDeclaration): AllDecorato return { decorators, - parameters + parameters, }; } @@ -686,8 +700,7 @@ function getAllDecoratorsOfAccessors(accessor: AccessorDeclaration, parent: Clas } const { firstAccessor, secondAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(parent.members, accessor); - const firstAccessorWithDecorators = - hasDecorators(firstAccessor) ? firstAccessor : + const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : undefined; @@ -705,7 +718,7 @@ function getAllDecoratorsOfAccessors(accessor: AccessorDeclaration, parent: Clas decorators, parameters, getDecorators: getAccessor && getDecorators(getAccessor), - setDecorators: setAccessor && getDecorators(setAccessor) + setDecorators: setAccessor && getDecorators(setAccessor), }; } @@ -737,7 +750,6 @@ function getAllDecoratorsOfProperty(property: PropertyDeclaration): AllDecorator const decorators = getDecorators(property); if (!some(decorators)) { return undefined; - } return { decorators }; @@ -768,7 +780,7 @@ export interface LexicalEnvironment( env: LexicalEnvironment | undefined, - cb: (env: LexicalEnvironment) => U + cb: (env: LexicalEnvironment) => U, ): U | undefined { while (env) { const result = cb(env); @@ -785,7 +797,7 @@ export function newPrivateEnvironment(data: TData): PrivateEnviro /** @internal */ export function getPrivateIdentifier( privateEnv: PrivateEnvironment | undefined, - name: PrivateIdentifier + name: PrivateIdentifier, ) { return isGeneratedPrivateIdentifier(name) ? privateEnv?.generatedIdentifiers?.get(getNodeForGeneratedName(name)) : @@ -796,7 +808,7 @@ export function getPrivateIdentifier( export function setPrivateIdentifier( privateEnv: PrivateEnvironment, name: PrivateIdentifier, - entry: TEntry + entry: TEntry, ) { if (isGeneratedPrivateIdentifier(name)) { privateEnv.generatedIdentifiers ??= new Map(); diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 741ffe0a8941d..0e89b75351622 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -135,7 +135,7 @@ export namespace Status { } export interface OutOfDateRoots { - type: UpToDateStatusType.OutOfDateRoots, + type: UpToDateStatusType.OutOfDateRoots; buildInfoFile: string; inputFile: Path; } diff --git a/src/compiler/tsbuildPublic.ts b/src/compiler/tsbuildPublic.ts index b734ca7eed949..8512e52f07f86 100644 --- a/src/compiler/tsbuildPublic.ts +++ b/src/compiler/tsbuildPublic.ts @@ -185,7 +185,7 @@ enum BuildResultFlags { DeclarationEmitErrors = 1 << 5, EmitErrors = 1 << 6, - AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors | EmitErrors + AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors | EmitErrors, } /** @internal */ @@ -477,13 +477,14 @@ function createSolutionBuilderState(watch: boolean, ho let libraryResolutionCache: ModuleResolutionCache | undefined; if (!compilerHost.resolveLibrary) { libraryResolutionCache = createModuleResolutionCache(compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, /*options*/ undefined, moduleResolutionCache?.getPackageJsonInfoCache()); - compilerHost.resolveLibrary = (libraryName, resolveFrom, options) => resolveLibrary( - libraryName, - resolveFrom, - options, - host, - libraryResolutionCache, - ); + compilerHost.resolveLibrary = (libraryName, resolveFrom, options) => + resolveLibrary( + libraryName, + resolveFrom, + options, + host, + libraryResolutionCache, + ); } compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo(state, fileName, toResolvedConfigFilePath(state, configFilePath as ResolvedConfigFileName), /*modifiedTime*/ undefined); @@ -625,8 +626,8 @@ function createBuildOrder(state: SolutionBuilderState< (circularDiagnostics || (circularDiagnostics = [])).push( createCompilerDiagnostic( Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, - circularityReportStack.join("\r\n") - ) + circularityReportStack.join("\r\n"), + ), ); } return; @@ -661,7 +662,8 @@ function createStateBuildOrder(state: SolutionBuilderS // TODO(rbuckton): Should be a `Set`, but that requires changing the code below that uses `mutateMapSkippingNewValues` const currentProjects = new Map( getBuildOrderFromAnyBuildOrder(buildOrder).map( - resolved => [toResolvedConfigFilePath(state, resolved), true as const]) + resolved => [toResolvedConfigFilePath(state, resolved), true as const], + ), ); const noopOnDelete = { onDeleteValue: noop }; @@ -680,7 +682,7 @@ function createStateBuildOrder(state: SolutionBuilderS mutateMapSkippingNewValues( state.allWatchedConfigFiles, currentProjects, - { onDeleteValue: closeFileWatcher } + { onDeleteValue: closeFileWatcher }, ); state.allWatchedExtendedConfigFiles.forEach(watcher => { @@ -695,19 +697,19 @@ function createStateBuildOrder(state: SolutionBuilderS mutateMapSkippingNewValues( state.allWatchedWildcardDirectories, currentProjects, - { onDeleteValue: existingMap => existingMap.forEach(closeFileWatcherOf) } + { onDeleteValue: existingMap => existingMap.forEach(closeFileWatcherOf) }, ); mutateMapSkippingNewValues( state.allWatchedInputFiles, currentProjects, - { onDeleteValue: existingMap => existingMap.forEach(closeFileWatcher) } + { onDeleteValue: existingMap => existingMap.forEach(closeFileWatcher) }, ); mutateMapSkippingNewValues( state.allWatchedPackageJsonFiles, currentProjects, - { onDeleteValue: existingMap => existingMap.forEach(closeFileWatcher) } + { onDeleteValue: existingMap => existingMap.forEach(closeFileWatcher) }, ); } return state.buildOrder = buildOrder; @@ -721,7 +723,7 @@ function getBuildOrderFor(state: SolutionBuilderState< const projectPath = toResolvedConfigFilePath(state, resolvedProject); const projectIndex = findIndex( buildOrderFromState, - configFileName => toResolvedConfigFilePath(state, configFileName) === projectPath + configFileName => toResolvedConfigFilePath(state, configFileName) === projectPath, ); if (projectIndex === -1) return undefined; } @@ -743,13 +745,17 @@ function enableCache(state: SolutionBuilderState) { const originalGetSourceFile = compilerHost.getSourceFile; const { - originalReadFile, originalFileExists, originalDirectoryExists, - originalCreateDirectory, originalWriteFile, - getSourceFileWithCache, readFileWithCache + originalReadFile, + originalFileExists, + originalDirectoryExists, + originalCreateDirectory, + originalWriteFile, + getSourceFileWithCache, + readFileWithCache, } = changeCompilerHostLikeToUseCache( host, fileName => toPath(state, fileName), - (...args) => originalGetSourceFile.call(compilerHost, ...args) + (...args) => originalGetSourceFile.call(compilerHost, ...args), ); state.readFileWithCache = readFileWithCache; compilerHost.getSourceFile = getSourceFileWithCache!; @@ -809,7 +815,7 @@ function setupInitialBuild(state: SolutionBuilderState buildOrder.forEach(configFileName => state.projectPendingBuild.set( toResolvedConfigFilePath(state, configFileName), - ConfigFileProgramReloadLevel.None + ConfigFileProgramReloadLevel.None, ) ); @@ -821,7 +827,7 @@ function setupInitialBuild(state: SolutionBuilderState export enum InvalidatedProjectKind { Build, /** @deprecated */ UpdateBundle, - UpdateOutputFileStamps + UpdateOutputFileStamps, } export interface InvalidatedProjectBase { @@ -882,7 +888,7 @@ export type InvalidatedProject = UpdateOutputFileStamp function doneInvalidatedProject( state: SolutionBuilderState, - projectPath: ResolvedConfigFilePath + projectPath: ResolvedConfigFilePath, ) { state.projectPendingBuild.delete(projectPath); return state.diagnostics.has(projectPath) ? @@ -895,7 +901,7 @@ function createUpdateOutputFileStampsProject( project: ResolvedConfigFileName, projectPath: ResolvedConfigFilePath, config: ParsedCommandLine, - buildOrder: readonly ResolvedConfigFileName[] + buildOrder: readonly ResolvedConfigFileName[], ): UpdateOutputFileStampsProject { let updateOutputFileStampsPending = true; return { @@ -915,7 +921,7 @@ function createUpdateOutputFileStampsProject( } performance.mark("SolutionBuilder::Timestamps only updates"); return doneInvalidatedProject(state, projectPath); - } + }, }; } @@ -928,7 +934,7 @@ enum BuildStep { EmitBuildInfo, /** @deprecated */ BuildInvalidatedProjectOfBundle, QueueReferencingProjects, - Done + Done, } function createBuildOrUpdateInvalidedProject( @@ -956,50 +962,50 @@ function createBuildOrUpdateInvalidedProject( getBuilderProgram: () => withProgramOrUndefined(identity), getProgram: () => withProgramOrUndefined( - program => program.getProgramOrUndefined() + program => program.getProgramOrUndefined(), ), getSourceFile: fileName => withProgramOrUndefined( - program => program.getSourceFile(fileName) + program => program.getSourceFile(fileName), ), getSourceFiles: () => withProgramOrEmptyArray( - program => program.getSourceFiles() + program => program.getSourceFiles(), ), getOptionsDiagnostics: cancellationToken => withProgramOrEmptyArray( - program => program.getOptionsDiagnostics(cancellationToken) + program => program.getOptionsDiagnostics(cancellationToken), ), getGlobalDiagnostics: cancellationToken => withProgramOrEmptyArray( - program => program.getGlobalDiagnostics(cancellationToken) + program => program.getGlobalDiagnostics(cancellationToken), ), getConfigFileParsingDiagnostics: () => withProgramOrEmptyArray( - program => program.getConfigFileParsingDiagnostics() + program => program.getConfigFileParsingDiagnostics(), ), getSyntacticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray( - program => program.getSyntacticDiagnostics(sourceFile, cancellationToken) + program => program.getSyntacticDiagnostics(sourceFile, cancellationToken), ), getAllDependencies: sourceFile => withProgramOrEmptyArray( - program => program.getAllDependencies(sourceFile) + program => program.getAllDependencies(sourceFile), ), getSemanticDiagnostics: (sourceFile, cancellationToken) => withProgramOrEmptyArray( - program => program.getSemanticDiagnostics(sourceFile, cancellationToken) + program => program.getSemanticDiagnostics(sourceFile, cancellationToken), ), getSemanticDiagnosticsOfNextAffectedFile: (cancellationToken, ignoreSourceFile) => withProgramOrUndefined( program => ((program as any as SemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile) && - (program as any as SemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) + (program as any as SemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile), ), emit: (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) => { if (targetSourceFile || emitOnlyDtsFiles) { return withProgramOrUndefined( - program => program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers || state.host.getCustomTransformers?.(project)) + program => program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers || state.host.getCustomTransformers?.(project)), ); } executeSteps(BuildStep.SemanticDiagnostics, cancellationToken); @@ -1009,7 +1015,7 @@ function createBuildOrUpdateInvalidedProject( if (step !== BuildStep.Emit) return undefined; return emit(writeFile, cancellationToken, customTransformers); }, - done + done, } : { kind, @@ -1074,13 +1080,16 @@ function createBuildOrUpdateInvalidedProject( compilerHost, getOldProgram(state, projectPath, config), getConfigFileParsingDiagnostics(config), - config.projectReferences + config.projectReferences, ); if (state.watch) { - state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && map( - state.moduleResolutionCache.getPackageJsonInfoCache().entries(), - ([path, data]) => ([state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data] as const) - )); + state.lastCachedPackageJsonLookups.set( + projectPath, + state.moduleResolutionCache && map( + state.moduleResolutionCache.getPackageJsonInfoCache().entries(), + ([path, data]) => ([state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data] as const), + ), + ); state.builderPrograms.set(projectPath, program); } @@ -1096,7 +1105,7 @@ function createBuildOrUpdateInvalidedProject( config, diagnostics, errorFlags, - errorType + errorType, )); } else { @@ -1111,10 +1120,10 @@ function createBuildOrUpdateInvalidedProject( ...program.getConfigFileParsingDiagnostics(), ...program.getOptionsDiagnostics(cancellationToken), ...program.getGlobalDiagnostics(cancellationToken), - ...program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken) + ...program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken), ], BuildResultFlags.SyntaxErrors, - "Syntactic" + "Syntactic", ); } @@ -1122,7 +1131,7 @@ function createBuildOrUpdateInvalidedProject( handleDiagnostics( Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, - "Semantic" + "Semantic", ); } @@ -1142,7 +1151,7 @@ function createBuildOrUpdateInvalidedProject( (name, text, writeByteOrderMark, _onError, _sourceFiles, data) => outputFiles.push({ name, text, writeByteOrderMark, data }), cancellationToken, /*emitOnlyDtsFiles*/ false, - customTransformers || state.host.getCustomTransformers?.(project) + customTransformers || state.host.getCustomTransformers?.(project), ); // Don't emit .d.ts if there are decl file errors if (declDiagnostics) { @@ -1154,11 +1163,11 @@ function createBuildOrUpdateInvalidedProject( config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, - "Declaration file" + "Declaration file", )); return { emitSkipped: true, - diagnostics: emitResult.diagnostics + diagnostics: emitResult.diagnostics, }; } @@ -1188,7 +1197,7 @@ function createBuildOrUpdateInvalidedProject( emitterDiagnostics, emittedOutputs, outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), - resultFlags + resultFlags, ); return emitResult; } @@ -1219,7 +1228,7 @@ function createBuildOrUpdateInvalidedProject( emitterDiagnostics: DiagnosticCollection, emittedOutputs: Map, oldestOutputFileName: string, - resultFlags: BuildResultFlags + resultFlags: BuildResultFlags, ) { const emitDiagnostics = emitterDiagnostics.getDiagnostics(); if (emitDiagnostics.length) { @@ -1230,7 +1239,7 @@ function createBuildOrUpdateInvalidedProject( config, emitDiagnostics, BuildResultFlags.EmitErrors, - "Emit" + "Emit", )); return emitDiagnostics; } @@ -1244,7 +1253,7 @@ function createBuildOrUpdateInvalidedProject( state.diagnostics.delete(projectPath); state.projectStatus.set(projectPath, { type: UpToDateStatusType.UpToDate, - oldestOutputFileName + oldestOutputFileName, }); afterProgramDone(state, program, config); step = BuildStep.QueueReferencingProjects; @@ -1274,7 +1283,7 @@ function createBuildOrUpdateInvalidedProject( const refName = resolveProjectName(state, ref.path); return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName)); }, - customTransformers || state.host.getCustomTransformers?.(project) + customTransformers || state.host.getCustomTransformers?.(project), ); if (isString(outputFiles)) { @@ -1287,7 +1296,7 @@ function createBuildOrUpdateInvalidedProject( projectPath, projectIndex, config, - buildOrder + buildOrder, ) as BuildInvalidedProject; } @@ -1312,7 +1321,7 @@ function createBuildOrUpdateInvalidedProject( emitterDiagnostics, emittedOutputs, outputFiles[0].name, - resultFlags + resultFlags, ); return { emitSkipped: false, diagnostics: emitDiagnostics }; } @@ -1359,7 +1368,6 @@ function createBuildOrUpdateInvalidedProject( case BuildStep.Done: default: assertType(step); - } Debug.assert(step > currentStep); } @@ -1385,7 +1393,7 @@ interface InvalidateProjectCreateInfo { function getNextInvalidatedProjectCreateInfo( state: SolutionBuilderState, buildOrder: AnyBuildOrder, - reportQueue: boolean + reportQueue: boolean, ): InvalidateProjectCreateInfo | undefined { if (!state.projectPendingBuild.size) return undefined; if (isCircularBuildOrder(buildOrder)) return undefined; @@ -1446,7 +1454,7 @@ function getNextInvalidatedProjectCreateInfo( project, projectPath, projectIndex, - config + config, }; } } @@ -1462,7 +1470,7 @@ function getNextInvalidatedProjectCreateInfo( Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built : Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, - status.upstreamProjectName + status.upstreamProjectName, ); } continue; @@ -1512,14 +1520,14 @@ function createInvalidatedProjectWithInfo( info.project, info.projectPath, info.config, - buildOrder as BuildOrder + buildOrder as BuildOrder, ); } function getNextInvalidatedProject( state: SolutionBuilderState, buildOrder: AnyBuildOrder, - reportQueue: boolean + reportQueue: boolean, ): InvalidatedProject | undefined { const info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); if (!info) return info; @@ -1542,7 +1550,7 @@ function getOldProgram({ options, builderPrograms, com function afterProgramDone( state: SolutionBuilderState, program: T | undefined, - config: ParsedCommandLine + config: ParsedCommandLine, ) { if (program) { if (state.write) listFiles(program, state.write); @@ -1616,7 +1624,7 @@ function watchFile(state: SolutionBuilderState, fil pollingInterval, options, watchType, - project + project, ); state.filesWatched.set(path, { callbacks: [callback], watcher, modifiedTime: existing }); } @@ -1632,7 +1640,7 @@ function watchFile(state: SolutionBuilderState, fil else { unorderedRemoveItem(existing.callbacks, callback); } - } + }, }; } @@ -1694,7 +1702,7 @@ function checkConfigFileUpToDateStatus(state: Solution return { type: UpToDateStatusType.OutOfDateWithSelf, outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: configFile + newerInputFileName: configFile, }; } } @@ -1703,7 +1711,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde // Container if no files are specified in the project if (!project.fileNames.length && !canJsonReportNoInputFiles(project.raw)) { return { - type: UpToDateStatusType.ContainerOnly + type: UpToDateStatusType.ContainerOnly, }; } @@ -1719,18 +1727,22 @@ function getUpToDateStatusWorker(state: SolutionBuilde const refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); // Its a circular reference ignore the status of this project - if (refStatus.type === UpToDateStatusType.ComputingUpstream || - refStatus.type === UpToDateStatusType.ContainerOnly) { // Container only ignore this project + if ( + refStatus.type === UpToDateStatusType.ComputingUpstream || + refStatus.type === UpToDateStatusType.ContainerOnly + ) { // Container only ignore this project continue; } // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable || - refStatus.type === UpToDateStatusType.UpstreamBlocked) { + if ( + refStatus.type === UpToDateStatusType.Unbuildable || + refStatus.type === UpToDateStatusType.UpstreamBlocked + ) { return { type: UpToDateStatusType.UpstreamBlocked, upstreamProjectName: ref.path, - upstreamProjectBlocked: refStatus.type === UpToDateStatusType.UpstreamBlocked + upstreamProjectBlocked: refStatus.type === UpToDateStatusType.UpstreamBlocked, }; } @@ -1738,7 +1750,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde if (refStatus.type !== UpToDateStatusType.UpToDate) { return { type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path + upstreamProjectName: ref.path, }; } @@ -1763,12 +1775,12 @@ function getUpToDateStatusWorker(state: SolutionBuilde state.buildInfoCache.set(resolvedPath, { path: toPath(state, buildInfoPath), buildInfo: false, - modifiedTime: buildInfoTime + modifiedTime: buildInfoTime, }); } return { type: UpToDateStatusType.OutputMissing, - missingOutputFileName: buildInfoPath + missingOutputFileName: buildInfoPath, }; } @@ -1777,13 +1789,13 @@ function getUpToDateStatusWorker(state: SolutionBuilde // Error reading buildInfo return { type: UpToDateStatusType.ErrorReadingFile, - fileName: buildInfoPath + fileName: buildInfoPath, }; } if ((buildInfo.bundle || buildInfo.program) && buildInfo.version !== version) { return { type: UpToDateStatusType.TsVersionOutputOfDate, - version: buildInfo.version + version: buildInfo.version, }; } @@ -1794,21 +1806,22 @@ function getUpToDateStatusWorker(state: SolutionBuilde // Checking presence of affectedFilesPendingEmit list is fast and good way to tell if there were semantic errors and file emit was blocked // But if noEmit is true, affectedFilesPendingEmit will have file list even if there are no semantic errors to preserve list of files to be emitted when running with noEmit false // So with noEmit set to true, check on semantic diagnostics needs to be explicit as oppose to when it is false when only files pending emit is sufficient - if ((buildInfo.program as ProgramMultiFileEmitBuildInfo).changeFileSet?.length || + if ( + (buildInfo.program as ProgramMultiFileEmitBuildInfo).changeFileSet?.length || (!project.options.noEmit ? (buildInfo.program as ProgramMultiFileEmitBuildInfo).affectedFilesPendingEmit?.length : some((buildInfo.program as ProgramMultiFileEmitBuildInfo).semanticDiagnosticsPerFile, isArray)) ) { return { type: UpToDateStatusType.OutOfDateBuildInfo, - buildInfoFile: buildInfoPath + buildInfoFile: buildInfoPath, }; } if (!project.options.noEmit && getPendingEmitKind(project.options, buildInfo.program.options || {})) { return { type: UpToDateStatusType.OutOfDateOptions, - buildInfoFile: buildInfoPath + buildInfoFile: buildInfoPath, }; } buildInfoProgram = buildInfo.program; @@ -1830,7 +1843,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde if (inputTime === missingFileModifiedTime) { return { type: UpToDateStatusType.Unbuildable, - reason: `${inputFile} does not exist` + reason: `${inputFile} does not exist`, }; } @@ -1851,7 +1864,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde return { type: UpToDateStatusType.OutOfDateWithSelf, outOfDateOutputFileName: buildInfoPath!, - newerInputFileName: inputFile + newerInputFileName: inputFile, }; } } @@ -1896,7 +1909,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde if (outputTime === missingFileModifiedTime) { return { type: UpToDateStatusType.OutputMissing, - missingOutputFileName: output + missingOutputFileName: output, }; } @@ -1905,7 +1918,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde return { type: UpToDateStatusType.OutOfDateWithSelf, outOfDateOutputFileName: output, - newerInputFileName: newestInputFileName + newerInputFileName: newestInputFileName, }; } @@ -1937,7 +1950,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde return { type: UpToDateStatusType.OutOfDateWithUpstream, outOfDateOutputFileName: buildInfoPath!, - newerProjectName: ref.path + newerProjectName: ref.path, }; } @@ -1955,7 +1968,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde return { type: UpToDateStatusType.OutOfDateWithUpstream, outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path + newerProjectName: ref.path, }; } } @@ -1971,7 +1984,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde // Check package file time const dependentPackageFileStatus = forEach( state.lastCachedPackageJsonLookups.get(resolvedPath) || emptyArray, - ([path]) => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName!) + ([path]) => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName!), ); if (dependentPackageFileStatus) return dependentPackageFileStatus; @@ -1979,7 +1992,7 @@ function getUpToDateStatusWorker(state: SolutionBuilde return { type: UpToDateStatusType.OutOfDateWithPrepend, outOfDateOutputFileName: oldestOutputFileName!, - newerProjectName: upstreamChangedProject! + newerProjectName: upstreamChangedProject!, }; } @@ -1988,11 +2001,11 @@ function getUpToDateStatusWorker(state: SolutionBuilde type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : pseudoInputUpToDate ? - UpToDateStatusType.UpToDateWithInputFileText : - UpToDateStatusType.UpToDate, + UpToDateStatusType.UpToDateWithInputFileText : + UpToDateStatusType.UpToDate, newestInputFileTime, newestInputFileName, - oldestOutputFileName: oldestOutputFileName! + oldestOutputFileName: oldestOutputFileName!, }; } @@ -2024,7 +2037,7 @@ function updateOutputTimestampsWorker( proj: ParsedCommandLine, projectPath: ResolvedConfigFilePath, verboseMessage: DiagnosticMessage, - skipOutputs?: Map + skipOutputs?: Map, ) { if (proj.options.noEmit) return; let now: Date | undefined; @@ -2087,7 +2100,7 @@ function updateOutputTimestamps(state: SolutionBuilder updateOutputTimestampsWorker(state, proj, resolvedPath, Diagnostics.Updating_output_timestamps_of_project_0); state.projectStatus.set(resolvedPath, { type: UpToDateStatusType.UpToDate, - oldestOutputFileName: getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()) + oldestOutputFileName: getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames()), }); } @@ -2098,7 +2111,7 @@ function queueReferencingProjects( projectIndex: number, config: ParsedCommandLine, buildOrder: readonly ResolvedConfigFileName[], - buildResult: BuildResultFlags + buildResult: BuildResultFlags, ) { // Queue only if there are no errors if (buildResult & BuildResultFlags.AnyErrors) return; @@ -2127,7 +2140,7 @@ function queueReferencingProjects( state.projectStatus.set(nextProjectPath, { type: UpToDateStatusType.OutOfDateWithPrepend, outOfDateOutputFileName: status.oldestOutputFileName, - newerProjectName: project + newerProjectName: project, }); } else { @@ -2144,7 +2157,7 @@ function queueReferencingProjects( state.projectStatus.set(nextProjectPath, { type: UpToDateStatusType.OutOfDateWithUpstream, outOfDateOutputFileName: status.type === UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName, - newerProjectName: project + newerProjectName: project, }); } break; @@ -2193,10 +2206,10 @@ function buildWorker(state: SolutionBuilderState, p return isCircularBuildOrder(buildOrder) ? ExitStatus.ProjectReferenceCycle_OutputsSkipped : !buildOrder.some(p => state.diagnostics.has(toResolvedConfigFilePath(state, p))) - ? ExitStatus.Success - : successfulProjects - ? ExitStatus.DiagnosticsPresent_OutputsGenerated - : ExitStatus.DiagnosticsPresent_OutputsSkipped; + ? ExitStatus.Success + : successfulProjects + ? ExitStatus.DiagnosticsPresent_OutputsGenerated + : ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state: SolutionBuilderState, project?: string, onlyReferences?: boolean): ExitStatus { @@ -2326,15 +2339,18 @@ function buildNextInvalidatedProjectWorker(state: Solu function watchConfigFile(state: SolutionBuilderState, resolved: ResolvedConfigFileName, resolvedPath: ResolvedConfigFilePath, parsed: ParsedCommandLine | undefined) { if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; - state.allWatchedConfigFiles.set(resolvedPath, watchFile( - state, - resolved, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.Full), - PollingInterval.High, - parsed?.watchOptions, - WatchType.ConfigFile, - resolved - )); + state.allWatchedConfigFiles.set( + resolvedPath, + watchFile( + state, + resolved, + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.Full), + PollingInterval.High, + parsed?.watchOptions, + WatchType.ConfigFile, + resolved, + ), + ); } function watchExtendedConfigFiles(state: SolutionBuilderState, resolvedPath: ResolvedConfigFilePath, parsed: ParsedCommandLine | undefined) { @@ -2342,15 +2358,15 @@ function watchExtendedConfigFiles(state: SolutionBuild resolvedPath, parsed?.options, state.allWatchedExtendedConfigFiles, - (extendedConfigFileName, extendedConfigFilePath) => watchFile( - state, - extendedConfigFileName, - () => state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)?.projects.forEach(projectConfigFilePath => - invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ConfigFileProgramReloadLevel.Full)), - PollingInterval.High, - parsed?.watchOptions, - WatchType.ExtendedConfigFile, - ), + (extendedConfigFileName, extendedConfigFilePath) => + watchFile( + state, + extendedConfigFileName, + () => state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)?.projects.forEach(projectConfigFilePath => invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ConfigFileProgramReloadLevel.Full)), + PollingInterval.High, + parsed?.watchOptions, + WatchType.ExtendedConfigFile, + ), fileName => toPath(state, fileName), ); } @@ -2360,29 +2376,32 @@ function watchWildCardDirectories(state: SolutionBuild updateWatchingWildcardDirectories( getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new Map(Object.entries(parsed.wildcardDirectories!)), - (dir, flags) => state.watchDirectory( - dir, - fileOrDirectory => { - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: toPath(state, dir), - fileOrDirectory, - fileOrDirectoryPath: toPath(state, fileOrDirectory), - configFileName: resolved, - currentDirectory: state.compilerHost.getCurrentDirectory(), - options: parsed.options, - program: state.builderPrograms.get(resolvedPath) || getCachedParsedConfigFile(state, resolvedPath)?.fileNames, - useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, - writeLog: s => state.writeLog(s), - toPath: fileName => toPath(state, fileName) - })) return; - - invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.Partial); - }, - flags, - parsed?.watchOptions, - WatchType.WildcardDirectory, - resolved - ) + (dir, flags) => + state.watchDirectory( + dir, + fileOrDirectory => { + if ( + isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(state, dir), + fileOrDirectory, + fileOrDirectoryPath: toPath(state, fileOrDirectory), + configFileName: resolved, + currentDirectory: state.compilerHost.getCurrentDirectory(), + options: parsed.options, + program: state.builderPrograms.get(resolvedPath) || getCachedParsedConfigFile(state, resolvedPath)?.fileNames, + useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, + writeLog: s => state.writeLog(s), + toPath: fileName => toPath(state, fileName), + }) + ) return; + + invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.Partial); + }, + flags, + parsed?.watchOptions, + WatchType.WildcardDirectory, + resolved, + ), ); } @@ -2392,17 +2411,18 @@ function watchInputFiles(state: SolutionBuilderState toPath(state, fileName)), { - createNewValue: (_path, input) => watchFile( - state, - input, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.None), - PollingInterval.Low, - parsed?.watchOptions, - WatchType.SourceFile, - resolved - ), + createNewValue: (_path, input) => + watchFile( + state, + input, + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.None), + PollingInterval.Low, + parsed?.watchOptions, + WatchType.SourceFile, + resolved, + ), onDeleteValue: closeFileWatcher, - } + }, ); } @@ -2412,17 +2432,18 @@ function watchPackageJsonFiles(state: SolutionBuilderS getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), new Map(state.lastCachedPackageJsonLookups.get(resolvedPath)), { - createNewValue: (path, _input) => watchFile( - state, - path, - () => invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.None), - PollingInterval.High, - parsed?.watchOptions, - WatchType.PackageJson, - resolved - ), + createNewValue: (path, _input) => + watchFile( + state, + path, + () => invalidateProjectAndScheduleBuilds(state, resolvedPath, ConfigFileProgramReloadLevel.None), + PollingInterval.High, + parsed?.watchOptions, + WatchType.PackageJson, + resolved, + ), onDeleteValue: closeFileWatcher, - } + }, ); } @@ -2565,7 +2586,7 @@ function reportUpToDateStatus(state: SolutionBuilderSt Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), - relName(state, status.newerInputFileName) + relName(state, status.newerInputFileName), ); case UpToDateStatusType.OutOfDateWithUpstream: return reportStatus( @@ -2573,35 +2594,35 @@ function reportUpToDateStatus(state: SolutionBuilderSt Diagnostics.Project_0_is_out_of_date_because_output_1_is_older_than_input_2, relName(state, configFileName), relName(state, status.outOfDateOutputFileName), - relName(state, status.newerProjectName) + relName(state, status.newerProjectName), ); case UpToDateStatusType.OutputMissing: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(state, configFileName), - relName(state, status.missingOutputFileName) + relName(state, status.missingOutputFileName), ); case UpToDateStatusType.ErrorReadingFile: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_there_was_error_reading_file_1, relName(state, configFileName), - relName(state, status.fileName) + relName(state, status.fileName), ); case UpToDateStatusType.OutOfDateBuildInfo: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), - relName(state, status.buildInfoFile) + relName(state, status.buildInfoFile), ); case UpToDateStatusType.OutOfDateOptions: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions, relName(state, configFileName), - relName(state, status.buildInfoFile) + relName(state, status.buildInfoFile), ); case UpToDateStatusType.OutOfDateRoots: return reportStatus( @@ -2618,7 +2639,7 @@ function reportUpToDateStatus(state: SolutionBuilderSt Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_output_2, relName(state, configFileName), relName(state, status.newestInputFileName || ""), - relName(state, status.oldestOutputFileName || "") + relName(state, status.oldestOutputFileName || ""), ); } // Don't report anything for "up to date because it was already built" -- too verbose @@ -2628,26 +2649,26 @@ function reportUpToDateStatus(state: SolutionBuilderSt state, Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(state, configFileName), - relName(state, status.newerProjectName) + relName(state, status.newerProjectName), ); case UpToDateStatusType.UpToDateWithUpstreamTypes: return reportStatus( state, Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, - relName(state, configFileName) + relName(state, configFileName), ); case UpToDateStatusType.UpToDateWithInputFileText: return reportStatus( state, Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, - relName(state, configFileName) + relName(state, configFileName), ); case UpToDateStatusType.UpstreamOutOfDate: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), - relName(state, status.upstreamProjectName) + relName(state, status.upstreamProjectName), ); case UpToDateStatusType.UpstreamBlocked: return reportStatus( @@ -2656,14 +2677,14 @@ function reportUpToDateStatus(state: SolutionBuilderSt Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built : Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), - relName(state, status.upstreamProjectName) + relName(state, status.upstreamProjectName), ); case UpToDateStatusType.Unbuildable: return reportStatus( state, Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), - status.reason + status.reason, ); case UpToDateStatusType.TsVersionOutputOfDate: return reportStatus( @@ -2671,13 +2692,13 @@ function reportUpToDateStatus(state: SolutionBuilderSt Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(state, configFileName), status.version, - version + version, ); case UpToDateStatusType.ForceBuild: return reportStatus( state, Diagnostics.Project_0_is_being_forcibly_rebuilt, - relName(state, configFileName) + relName(state, configFileName), ); case UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 5432adf33ebb5..2096b177c5930 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -21,7 +21,7 @@ import { // branded string type used to store absolute, normalized and canonicalized paths // arbitrary file name can be converted to Path via toPath function -export type Path = string & { __pathBrand: any }; +export type Path = string & { __pathBrand: any; }; /** @internal */ export type MatchingKeys = K extends (TRecord[K] extends TMatch ? K : never) ? K : never; @@ -500,8 +500,7 @@ export type TriviaSyntaxKind = | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia - | SyntaxKind.ConflictMarkerTrivia - ; + | SyntaxKind.ConflictMarkerTrivia; export type LiteralSyntaxKind = | SyntaxKind.NumericLiteral @@ -510,14 +509,12 @@ export type LiteralSyntaxKind = | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.RegularExpressionLiteral - | SyntaxKind.NoSubstitutionTemplateLiteral - ; + | SyntaxKind.NoSubstitutionTemplateLiteral; export type PseudoLiteralSyntaxKind = | SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle - | SyntaxKind.TemplateTail - ; + | SyntaxKind.TemplateTail; export type PunctuationSyntaxKind = | SyntaxKind.OpenBraceToken @@ -580,8 +577,7 @@ export type PunctuationSyntaxKind = | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken - | SyntaxKind.CaretEqualsToken - ; + | SyntaxKind.CaretEqualsToken; /** @internal */ export type PunctuationOrKeywordSyntaxKind = PunctuationSyntaxKind | KeywordSyntaxKind; @@ -669,8 +665,7 @@ export type KeywordSyntaxKind = | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword - | SyntaxKind.YieldKeyword - ; + | SyntaxKind.YieldKeyword; export type ModifierSyntaxKind = | SyntaxKind.AbstractKeyword @@ -687,8 +682,7 @@ export type ModifierSyntaxKind = | SyntaxKind.ReadonlyKeyword | SyntaxKind.OutKeyword | SyntaxKind.OverrideKeyword - | SyntaxKind.StaticKeyword - ; + | SyntaxKind.StaticKeyword; export type KeywordTypeSyntaxKind = | SyntaxKind.AnyKeyword @@ -702,8 +696,7 @@ export type KeywordTypeSyntaxKind = | SyntaxKind.SymbolKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UnknownKeyword - | SyntaxKind.VoidKeyword - ; + | SyntaxKind.VoidKeyword; /** @internal */ export type TypeNodeSyntaxKind = @@ -743,8 +736,7 @@ export type TypeNodeSyntaxKind = | SyntaxKind.JSDocVariadicType | SyntaxKind.JSDocNamepathType | SyntaxKind.JSDocSignature - | SyntaxKind.JSDocTypeLiteral - ; + | SyntaxKind.JSDocTypeLiteral; export type TokenSyntaxKind = | SyntaxKind.Unknown @@ -754,8 +746,7 @@ export type TokenSyntaxKind = | PseudoLiteralSyntaxKind | PunctuationSyntaxKind | SyntaxKind.Identifier - | KeywordSyntaxKind - ; + | KeywordSyntaxKind; export type JsxTokenSyntaxKind = | SyntaxKind.LessThanSlashToken @@ -764,8 +755,7 @@ export type JsxTokenSyntaxKind = | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken - | SyntaxKind.LessThanToken - ; + | SyntaxKind.LessThanToken; export type JSDocSyntaxKind = | SyntaxKind.EndOfFileToken @@ -786,9 +776,9 @@ export type JSDocSyntaxKind = | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.Unknown - | KeywordSyntaxKind - ; + | KeywordSyntaxKind; +// dprint-ignore export const enum NodeFlags { None = 0, Let = 1 << 0, // Variable declaration @@ -856,6 +846,7 @@ export const enum NodeFlags { /** @internal */ IdentifierIsInJSDocNamespace = HasAsyncFunctions, // Indicates whether the identifier is part of a JSDoc namespace } +// dprint-ignore export const enum ModifierFlags { None = 0, Export = 1 << 0, // Declarations @@ -887,7 +878,7 @@ export const enum ModifierFlags { TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const | Override | In | Out, ExportDefault = Export | Default, All = Export | Ambient | Public | Private | Protected | Static | Readonly | Abstract | Accessor | Async | Default | Const | Deprecated | Override | In | Out | Decorator, - Modifier = All & ~Decorator + Modifier = All & ~Decorator, } export const enum JsxFlags { @@ -900,6 +891,7 @@ export const enum JsxFlags { IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement, } +// dprint-ignore /** @internal */ export const enum RelationComparisonResult { Succeeded = 1 << 0, // Should be truthy @@ -908,7 +900,7 @@ export const enum RelationComparisonResult { ReportsUnmeasurable = 1 << 3, ReportsUnreliable = 1 << 4, - ReportsMask = ReportsUnmeasurable | ReportsUnreliable + ReportsMask = ReportsUnmeasurable | ReportsUnreliable, } /** @internal */ @@ -919,10 +911,10 @@ export interface Node extends ReadonlyTextRange { readonly flags: NodeFlags; /** @internal */ modifierFlagsCache: ModifierFlags; /** @internal */ readonly transformFlags: TransformFlags; // Flags for transforms - /** @internal */ id?: NodeId; // Unique id (used to look up NodeLinks) - readonly parent: Node; // Parent node (initialized by binding) - /** @internal */ original?: Node; // The original node if this is an updated node. - /** @internal */ emitNode?: EmitNode; // Associated EmitNode (initialized by transforms) + /** @internal */ id?: NodeId; // Unique id (used to look up NodeLinks) + readonly parent: Node; // Parent node (initialized by binding) + /** @internal */ original?: Node; // The original node if this is an updated node. + /** @internal */ emitNode?: EmitNode; // Associated EmitNode (initialized by transforms) // NOTE: `symbol` and `localSymbol` have been moved to `Declaration` // `locals` and `nextContainer` have been moved to `LocalsContainer` // `flowNode` has been moved to `FlowContainer` @@ -931,23 +923,23 @@ export interface Node extends ReadonlyTextRange { export interface JSDocContainer extends Node { _jsdocContainerBrand: any; - /** @internal */ jsDoc?: JSDocArray; // JSDoc that directly precedes this node + /** @internal */ jsDoc?: JSDocArray; // JSDoc that directly precedes this node } /** @internal */ export interface JSDocArray extends Array { - jsDocCache?: readonly JSDocTag[]; // Cache for getJSDocTags + jsDocCache?: readonly JSDocTag[]; // Cache for getJSDocTags } export interface LocalsContainer extends Node { _localsContainerBrand: any; - /** @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding) - /** @internal */ nextContainer?: HasLocals; // Next container in declaration order (initialized by binding) + /** @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding) + /** @internal */ nextContainer?: HasLocals; // Next container in declaration order (initialized by binding) } export interface FlowContainer extends Node { _flowContainerBrand: any; - /** @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding) + /** @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding) } /** @internal */ @@ -981,8 +973,7 @@ export type HasFlowNode = | LabeledStatement | ThrowStatement | TryStatement - | DebuggerStatement - ; + | DebuggerStatement; // Ideally, `ForEachChildNodes` and `VisitEachChildNodes` would not differ. // However, `forEachChild` currently processes JSDoc comment syntax and missing declarations more thoroughly. @@ -1030,8 +1021,7 @@ export type ForEachChildNodes = | JSDocThrowsTag | JSDocOverrideTag | JSDocSatisfiesTag - | JSDocOverloadTag - ; + | JSDocOverloadTag; /** @internal */ export type HasChildren = @@ -1169,8 +1159,7 @@ export type HasChildren = | EnumMember | SourceFile | PartiallyEmittedExpression - | CommaListExpression - ; + | CommaListExpression; export type HasJSDoc = | AccessorDeclaration @@ -1236,8 +1225,7 @@ export type HasJSDoc = | VariableDeclaration | VariableStatement | WhileStatement - | WithStatement - ; + | WithStatement; export type HasType = | SignatureDeclaration @@ -1255,16 +1243,14 @@ export type HasType = | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType - | JSDocVariadicType - ; + | JSDocVariadicType; // NOTE: Changing the following list requires changes to: // - `canHaveIllegalType` in factory/utilities.ts /** @internal */ export type HasIllegalType = | ConstructorDeclaration - | SetAccessorDeclaration - ; + | SetAccessorDeclaration; // NOTE: Changing the following list requires changes to: // - `canHaveIllegalTypeParameters` in factory/utilities.ts @@ -1272,8 +1258,7 @@ export type HasIllegalType = export type HasIllegalTypeParameters = | ConstructorDeclaration | SetAccessorDeclaration - | GetAccessorDeclaration - ; + | GetAccessorDeclaration; export type HasTypeArguments = | CallExpression @@ -1287,8 +1272,7 @@ export type HasInitializer = | ForStatement | ForInStatement | ForOfStatement - | JsxAttribute - ; + | JsxAttribute; export type HasExpressionInitializer = | VariableDeclaration @@ -1296,13 +1280,10 @@ export type HasExpressionInitializer = | BindingElement | PropertyDeclaration | PropertyAssignment - | EnumMember - ; + | EnumMember; /** @internal */ -export type HasIllegalExpressionInitializer = - | PropertySignature - ; +export type HasIllegalExpressionInitializer = PropertySignature; // NOTE: Changing the following list requires changes to: // - `canHaveDecorators` in factory/utilities.ts @@ -1314,8 +1295,7 @@ export type HasDecorators = | GetAccessorDeclaration | SetAccessorDeclaration | ClassExpression - | ClassDeclaration - ; + | ClassDeclaration; // NOTE: Changing the following list requires changes to: // - `canHaveIllegalDecorators` in factory/utilities.ts @@ -1337,8 +1317,7 @@ export type HasIllegalDecorators = | ImportDeclaration | NamespaceExportDeclaration | ExportDeclaration - | ExportAssignment - ; + | ExportAssignment; // NOTE: Changing the following list requires changes to: // - `canHaveModifiers` in factory/utilitiesPublic.ts @@ -1368,8 +1347,7 @@ export type HasModifiers = | ImportEqualsDeclaration | ImportDeclaration | ExportAssignment - | ExportDeclaration - ; + | ExportDeclaration; // NOTE: Changing the following list requires changes to: // - `canHaveIllegalModifiers` in factory/utilities.ts @@ -1379,8 +1357,7 @@ export type HasIllegalModifiers = | PropertyAssignment | ShorthandPropertyAssignment | MissingDeclaration - | NamespaceExportDeclaration - ; + | NamespaceExportDeclaration; /** * Declarations that can contain other declarations. Corresponds with `ContainerFlags.IsContainer` in binder.ts. @@ -1415,8 +1392,7 @@ export type IsContainer = | ConstructorTypeNode | ClassStaticBlockDeclaration | FunctionExpression - | ArrowFunction - ; + | ArrowFunction; /** * Nodes that introduce a new block scope. Corresponds with `ContainerFlags.IsBlockScopedContainer` in binder.ts. @@ -1430,8 +1406,7 @@ export type IsBlockScopedContainer = | ForInStatement | ForOfStatement | CaseBlock - | Block - ; + | Block; /** * Corresponds with `ContainerFlags.IsControlFlowContainer` in binder.ts. @@ -1456,8 +1431,7 @@ export type IsControlFlowContainer = | FunctionExpression | ArrowFunction | ModuleBlock - | PropertyDeclaration - ; + | PropertyDeclaration; /** * Corresponds with `ContainerFlags.IsFunctionLike` in binder.ts. @@ -1479,8 +1453,7 @@ export type IsFunctionLike = | ConstructorTypeNode | ClassStaticBlockDeclaration | FunctionExpression - | ArrowFunction - ; + | ArrowFunction; /** * Corresponds with `ContainerFlags.IsFunctionExpression` in binder.ts. @@ -1489,8 +1462,7 @@ export type IsFunctionLike = */ export type IsFunctionExpression = | FunctionExpression - | ArrowFunction - ; + | ArrowFunction; /** * Nodes that can have local symbols. Corresponds with `ContainerFlags.HasLocals`. Constituents should extend @@ -1528,17 +1500,14 @@ export type HasLocals = | ModuleDeclaration | SetAccessorDeclaration | SourceFile - | TypeAliasDeclaration - ; + | TypeAliasDeclaration; /** * Corresponds with `ContainerFlags.IsInterface` in binder.ts. * * @internal */ -export type IsInterface = - | InterfaceDeclaration - ; +export type IsInterface = InterfaceDeclaration; /** * Corresponds with `ContainerFlags.IsObjectLiteralOrClassExpressionMethodOrAccessor` in binder.ts. @@ -1548,8 +1517,7 @@ export type IsInterface = export type IsObjectLiteralOrClassExpressionMethodOrAccessor = | GetAccessorDeclaration | SetAccessorDeclaration - | MethodDeclaration - ; + | MethodDeclaration; /** * Corresponds with `ContainerFlags` in binder.ts. @@ -1564,18 +1532,17 @@ export type HasContainerFlags = | IsFunctionExpression | HasLocals | IsInterface - | IsObjectLiteralOrClassExpressionMethodOrAccessor - ; + | IsObjectLiteralOrClassExpressionMethodOrAccessor; /** @internal */ export interface MutableNodeArray extends Array, TextRange { hasTrailingComma: boolean; - /** @internal */ transformFlags: TransformFlags; // Flags for transforms, possibly undefined + /** @internal */ transformFlags: TransformFlags; // Flags for transforms, possibly undefined } export interface NodeArray extends ReadonlyArray, ReadonlyTextRange { readonly hasTrailingComma: boolean; - /** @internal */ transformFlags: TransformFlags; // Flags for transforms, possibly undefined + /** @internal */ transformFlags: TransformFlags; // Flags for transforms, possibly undefined } // TODO(rbuckton): Constraint 'TKind' to 'TokenSyntaxKind' @@ -1647,31 +1614,28 @@ export type Modifier = | OutKeyword | OverrideKeyword | ReadonlyKeyword - | StaticKeyword - ; + | StaticKeyword; export type ModifierLike = Modifier | Decorator; export type AccessibilityModifier = | PublicKeyword | PrivateKeyword - | ProtectedKeyword - ; + | ProtectedKeyword; export type ParameterPropertyModifier = | AccessibilityModifier - | ReadonlyKeyword - ; + | ReadonlyKeyword; export type ClassMemberModifier = | AccessibilityModifier | ReadonlyKeyword | StaticKeyword - | AccessorKeyword - ; + | AccessorKeyword; export type ModifiersArray = NodeArray; +// dprint-ignore export const enum GeneratedIdentifierFlags { // Kinds None = 0, // Not automatically generated. @@ -1702,6 +1666,7 @@ export interface TransientIdentifier extends Identifier { resolvedSymbol: Symbol; } +// dprint-ignore /** @internal */ export interface AutoGenerateInfo { flags: GeneratedIdentifierFlags; // Specifies whether to auto-generate the text for an identifier. @@ -1737,8 +1702,8 @@ export type DeclarationName = export interface Declaration extends Node { _declarationBrand: any; - /** @internal */ symbol: Symbol; // Symbol declared by node (initialized by binding) - /** @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes) + /** @internal */ symbol: Symbol; // Symbol declared by node (initialized by binding) + /** @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes) } export interface NamedDeclaration extends Declaration { @@ -1791,7 +1756,7 @@ export interface PrivateIdentifier extends PrimaryExpression { /** @internal */ export interface GeneratedPrivateIdentifier extends PrivateIdentifier { - readonly emitNode: EmitNode & { autoGenerate: AutoGenerateInfo }; + readonly emitNode: EmitNode & { autoGenerate: AutoGenerateInfo; }; } /** @internal */ @@ -1853,6 +1818,7 @@ export interface ConstructSignatureDeclaration extends SignatureDeclarationBase, export type BindingName = Identifier | BindingPattern; +// dprint-ignore export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.VariableDeclaration; readonly parent: VariableDeclarationList | CatchClause; @@ -1863,7 +1829,7 @@ export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { } /** @internal */ -export type InitializedVariableDeclaration = VariableDeclaration & { readonly initializer: Expression }; +export type InitializedVariableDeclaration = VariableDeclaration & { readonly initializer: Expression; }; export interface VariableDeclarationList extends Node { readonly kind: SyntaxKind.VariableDeclarationList; @@ -1871,6 +1837,7 @@ export interface VariableDeclarationList extends Node { readonly declarations: NodeArray; } +// dprint-ignore export interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.Parameter; readonly parent: SignatureDeclaration; @@ -1882,6 +1849,7 @@ export interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { readonly initializer?: Expression; // Optional initializer } +// dprint-ignore export interface BindingElement extends NamedDeclaration, FlowContainer { readonly kind: SyntaxKind.BindingElement; readonly parent: BindingPattern; @@ -1894,6 +1862,7 @@ export interface BindingElement extends NamedDeclaration, FlowContainer { /** @internal */ export type BindingElementGrandparent = BindingElement["parent"]["parent"]; +// dprint-ignore export interface PropertySignature extends TypeElement, JSDocContainer { readonly kind: SyntaxKind.PropertySignature; readonly parent: TypeLiteralNode | InterfaceDeclaration; @@ -1906,6 +1875,7 @@ export interface PropertySignature extends TypeElement, JSDocContainer { /** @internal */ readonly initializer?: Expression | undefined; // A property signature cannot have an initializer } +// dprint-ignore export interface PropertyDeclaration extends ClassElement, JSDocContainer { readonly kind: SyntaxKind.PropertyDeclaration; readonly parent: ClassLikeDeclaration; @@ -1952,7 +1922,7 @@ export type PrivateClassElementDeclaration = | PrivateIdentifierSetAccessorDeclaration; /** @internal */ -export type InitializedPropertyDeclaration = PropertyDeclaration & { readonly initializer: Expression }; +export type InitializedPropertyDeclaration = PropertyDeclaration & { readonly initializer: Expression; }; export interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrand: any; @@ -1960,13 +1930,12 @@ export interface ObjectLiteralElement extends NamedDeclaration { } /** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ -export type ObjectLiteralElementLike - = PropertyAssignment +export type ObjectLiteralElementLike = + | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration - | AccessorDeclaration - ; + | AccessorDeclaration; export interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { readonly kind: SyntaxKind.PropertyAssignment; @@ -2188,7 +2157,7 @@ export interface ImportTypeNode extends NodeWithTypeArguments { } /** @internal */ -export type LiteralImportTypeNode = ImportTypeNode & { readonly argument: LiteralTypeNode & { readonly literal: StringLiteral } }; +export type LiteralImportTypeNode = ImportTypeNode & { readonly argument: LiteralTypeNode & { readonly literal: StringLiteral; }; }; export interface ThisTypeNode extends TypeNode { readonly kind: SyntaxKind.ThisType; @@ -2349,13 +2318,13 @@ export type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; export type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral | JsxNamespacedName; export interface TemplateLiteralTypeNode extends TypeNode { - kind: SyntaxKind.TemplateLiteralType, + kind: SyntaxKind.TemplateLiteralType; readonly head: TemplateHead; readonly templateSpans: NodeArray; } export interface TemplateLiteralTypeSpan extends TypeNode { - readonly kind: SyntaxKind.TemplateLiteralTypeSpan, + readonly kind: SyntaxKind.TemplateLiteralTypeSpan; readonly parent: TemplateLiteralTypeNode; readonly type: TypeNode; readonly literal: TemplateMiddle | TemplateTail; @@ -2395,8 +2364,8 @@ export interface UpdateExpression extends UnaryExpression { // see: https://tc39.github.io/ecma262/#prod-UpdateExpression // see: https://tc39.github.io/ecma262/#prod-UnaryExpression -export type PrefixUnaryOperator - = SyntaxKind.PlusPlusToken +export type PrefixUnaryOperator = + | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken @@ -2410,10 +2379,9 @@ export interface PrefixUnaryExpression extends UpdateExpression { } // see: https://tc39.github.io/ecma262/#prod-UpdateExpression -export type PostfixUnaryOperator - = SyntaxKind.PlusPlusToken - | SyntaxKind.MinusMinusToken - ; +export type PostfixUnaryOperator = + | SyntaxKind.PlusPlusToken + | SyntaxKind.MinusMinusToken; export interface PostfixUnaryExpression extends UpdateExpression { readonly kind: SyntaxKind.PostfixUnaryExpression; @@ -2493,47 +2461,39 @@ export interface SyntheticExpression extends Expression { } // see: https://tc39.github.io/ecma262/#prod-ExponentiationExpression -export type ExponentiationOperator = - | SyntaxKind.AsteriskAsteriskToken - ; +export type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; // see: https://tc39.github.io/ecma262/#prod-MultiplicativeOperator export type MultiplicativeOperator = | SyntaxKind.AsteriskToken | SyntaxKind.SlashToken - | SyntaxKind.PercentToken - ; + | SyntaxKind.PercentToken; // see: https://tc39.github.io/ecma262/#prod-MultiplicativeExpression export type MultiplicativeOperatorOrHigher = | ExponentiationOperator - | MultiplicativeOperator - ; + | MultiplicativeOperator; // see: https://tc39.github.io/ecma262/#prod-AdditiveExpression export type AdditiveOperator = | SyntaxKind.PlusToken - | SyntaxKind.MinusToken - ; + | SyntaxKind.MinusToken; // see: https://tc39.github.io/ecma262/#prod-AdditiveExpression export type AdditiveOperatorOrHigher = | MultiplicativeOperatorOrHigher - | AdditiveOperator - ; + | AdditiveOperator; // see: https://tc39.github.io/ecma262/#prod-ShiftExpression export type ShiftOperator = | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken - | SyntaxKind.GreaterThanGreaterThanGreaterThanToken - ; + | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; // see: https://tc39.github.io/ecma262/#prod-ShiftExpression export type ShiftOperatorOrHigher = | AdditiveOperatorOrHigher - | ShiftOperator - ; + | ShiftOperator; // see: https://tc39.github.io/ecma262/#prod-RelationalExpression export type RelationalOperator = @@ -2542,22 +2502,19 @@ export type RelationalOperator = | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword - | SyntaxKind.InKeyword - ; + | SyntaxKind.InKeyword; // see: https://tc39.github.io/ecma262/#prod-RelationalExpression export type RelationalOperatorOrHigher = | ShiftOperatorOrHigher - | RelationalOperator - ; + | RelationalOperator; // see: https://tc39.github.io/ecma262/#prod-EqualityExpression export type EqualityOperator = | SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken - | SyntaxKind.ExclamationEqualsToken - ; + | SyntaxKind.ExclamationEqualsToken; // see: https://tc39.github.io/ecma262/#prod-EqualityExpression export type EqualityOperatorOrHigher = @@ -2570,30 +2527,26 @@ export type EqualityOperatorOrHigher = export type BitwiseOperator = | SyntaxKind.AmpersandToken | SyntaxKind.BarToken - | SyntaxKind.CaretToken - ; + | SyntaxKind.CaretToken; // see: https://tc39.github.io/ecma262/#prod-BitwiseANDExpression // see: https://tc39.github.io/ecma262/#prod-BitwiseXORExpression // see: https://tc39.github.io/ecma262/#prod-BitwiseORExpression export type BitwiseOperatorOrHigher = | EqualityOperatorOrHigher - | BitwiseOperator - ; + | BitwiseOperator; // see: https://tc39.github.io/ecma262/#prod-LogicalANDExpression // see: https://tc39.github.io/ecma262/#prod-LogicalORExpression export type LogicalOperator = | SyntaxKind.AmpersandAmpersandToken - | SyntaxKind.BarBarToken - ; + | SyntaxKind.BarBarToken; // see: https://tc39.github.io/ecma262/#prod-LogicalANDExpression // see: https://tc39.github.io/ecma262/#prod-LogicalORExpression export type LogicalOperatorOrHigher = | BitwiseOperatorOrHigher - | LogicalOperator - ; + | LogicalOperator; // see: https://tc39.github.io/ecma262/#prod-AssignmentOperator export type CompoundAssignmentOperator = @@ -2611,33 +2564,28 @@ export type CompoundAssignmentOperator = | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.BarBarEqualsToken | SyntaxKind.AmpersandAmpersandEqualsToken - | SyntaxKind.QuestionQuestionEqualsToken - ; + | SyntaxKind.QuestionQuestionEqualsToken; // see: https://tc39.github.io/ecma262/#prod-AssignmentExpression export type AssignmentOperator = | SyntaxKind.EqualsToken - | CompoundAssignmentOperator - ; + | CompoundAssignmentOperator; // see: https://tc39.github.io/ecma262/#prod-AssignmentExpression export type AssignmentOperatorOrHigher = | SyntaxKind.QuestionQuestionToken | LogicalOperatorOrHigher - | AssignmentOperator - ; + | AssignmentOperator; // see: https://tc39.github.io/ecma262/#prod-Expression export type BinaryOperator = | AssignmentOperatorOrHigher - | SyntaxKind.CommaToken - ; + | SyntaxKind.CommaToken; -export type LogicalOrCoalescingAssignmentOperator - = SyntaxKind.AmpersandAmpersandEqualsToken +export type LogicalOrCoalescingAssignmentOperator = + | SyntaxKind.AmpersandAmpersandEqualsToken | SyntaxKind.BarBarEqualsToken - | SyntaxKind.QuestionQuestionEqualsToken - ; + | SyntaxKind.QuestionQuestionEqualsToken; export type BinaryOperatorToken = Token; @@ -2665,22 +2613,20 @@ export interface ArrayDestructuringAssignment extends AssignmentExpression; @@ -2695,7 +2641,7 @@ export type ArrayBindingOrAssignmentElement = | Identifier // DestructuringAssignmentTarget | PropertyAccessExpression // DestructuringAssignmentTarget | ElementAccessExpression // DestructuringAssignmentTarget - ; +; /** @internal */ export type ArrayAssignmentElement = Exclude; @@ -2704,7 +2650,7 @@ export type BindingOrAssignmentElementRestIndicator = | DotDotDotToken // from BindingElement | SpreadElement // AssignmentRestElement | SpreadAssignment // AssignmentRestProperty - ; +; export type BindingOrAssignmentElementTarget = | BindingOrAssignmentPattern @@ -2719,12 +2665,12 @@ export type AssignmentElementTarget = Exclude; readonly name?: Identifier; - readonly body: FunctionBody; // Required, whereas the member inherited from FunctionDeclaration is optional + readonly body: FunctionBody; // Required, whereas the member inherited from FunctionDeclaration is optional } export interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer, LocalsContainer, FlowContainer { @@ -2789,6 +2735,7 @@ export interface NoSubstitutionTemplateLiteral extends LiteralExpression, Templa templateFlags?: TokenFlags; } +// dprint-ignore export const enum TokenFlags { None = 0, /** @internal */ @@ -2846,8 +2793,7 @@ export type LiteralToken = | StringLiteral | JsxText | RegularExpressionLiteral - | NoSubstitutionTemplateLiteral - ; + | NoSubstitutionTemplateLiteral; export interface TemplateHead extends TemplateLiteralLikeNode { readonly kind: SyntaxKind.TemplateHead; @@ -2873,13 +2819,11 @@ export interface TemplateTail extends TemplateLiteralLikeNode { export type PseudoLiteralToken = | TemplateHead | TemplateMiddle - | TemplateTail - ; + | TemplateTail; export type TemplateLiteralToken = | NoSubstitutionTemplateLiteral - | PseudoLiteralToken - ; + | PseudoLiteralToken; export interface TemplateExpression extends PrimaryExpression { readonly kind: SyntaxKind.TemplateExpression; @@ -2889,8 +2833,7 @@ export interface TemplateExpression extends PrimaryExpression { export type TemplateLiteral = | TemplateExpression - | NoSubstitutionTemplateLiteral - ; + | NoSubstitutionTemplateLiteral; // Each of these corresponds to a substitution expression and a template literal, in that order. // The template literal must have kind TemplateMiddleLiteral or TemplateTailLiteral. @@ -3022,15 +2965,13 @@ export type OptionalChain = | PropertyAccessChain | ElementAccessChain | CallChain - | NonNullChain - ; + | NonNullChain; /** @internal */ export type OptionalChainRoot = | PropertyAccessChainRoot | ElementAccessChainRoot - | CallChainRoot - ; + | CallChainRoot; /** @internal */ export type BindableObjectDefinePropertyCall = CallExpression & { @@ -3040,8 +2981,7 @@ export type BindableObjectDefinePropertyCall = CallExpression & { /** @internal */ export type BindableStaticNameExpression = | EntityNameExpression - | BindableStaticElementAccessExpression - ; + | BindableStaticElementAccessExpression; /** @internal */ export type LiteralLikeElementAccessExpression = ElementAccessExpression & Declaration & { @@ -3061,14 +3001,12 @@ export type BindableElementAccessExpression = ElementAccessExpression & { /** @internal */ export type BindableStaticAccessExpression = | PropertyAccessEntityNameExpression - | BindableStaticElementAccessExpression - ; + | BindableStaticElementAccessExpression; /** @internal */ export type BindableAccessExpression = | PropertyAccessEntityNameExpression - | BindableElementAccessExpression - ; + | BindableElementAccessExpression; /** @internal */ export interface BindableStaticPropertyAssignmentExpression extends BinaryExpression { @@ -3114,8 +3052,7 @@ export type CallLikeExpression = | NewExpression | TaggedTemplateExpression | Decorator - | JsxOpeningLikeElement - ; + | JsxOpeningLikeElement; export interface AsExpression extends Expression { readonly kind: SyntaxKind.AsExpression; @@ -3137,8 +3074,7 @@ export interface SatisfiesExpression extends Expression { export type AssertionExpression = | TypeAssertion - | AsExpression - ; + | AsExpression; export interface NonNullExpression extends LeftHandSideExpression { readonly kind: SyntaxKind.NonNullExpression; @@ -3160,7 +3096,7 @@ export interface MetaProperty extends PrimaryExpression, FlowContainer { /** @internal */ export interface ImportMetaProperty extends MetaProperty { readonly keywordToken: SyntaxKind.ImportKeyword; - readonly name: Identifier & { readonly escapedText: __String & "meta" }; + readonly name: Identifier & { readonly escapedText: __String & "meta"; }; } /// A JSX expression of the form ... @@ -3174,25 +3110,21 @@ export interface JsxElement extends PrimaryExpression { /// Either the opening tag in a ... pair or the lone in a self-closing form export type JsxOpeningLikeElement = | JsxSelfClosingElement - | JsxOpeningElement - ; + | JsxOpeningElement; export type JsxAttributeLike = | JsxAttribute - | JsxSpreadAttribute - ; + | JsxSpreadAttribute; export type JsxAttributeName = | Identifier - | JsxNamespacedName - ; + | JsxNamespacedName; export type JsxTagNameExpression = | Identifier | ThisExpression | JsxTagNamePropertyAccess - | JsxNamespacedName - ; + | JsxNamespacedName; export interface JsxTagNamePropertyAccess extends PropertyAccessExpression { readonly expression: Identifier | ThisExpression | JsxTagNamePropertyAccess; @@ -3292,8 +3224,7 @@ export type JsxChild = | JsxExpression | JsxElement | JsxSelfClosingElement - | JsxFragment - ; + | JsxFragment; export interface Statement extends Node, JSDocContainer { _statementBrand: any; @@ -3313,7 +3244,6 @@ export interface CommaListExpression extends Expression { readonly elements: NodeArray; } - /** @internal */ export interface SyntheticReferenceExpression extends LeftHandSideExpression { readonly kind: SyntaxKind.SyntheticReferenceExpression; @@ -3341,8 +3271,7 @@ export type BlockLike = | SourceFile | Block | ModuleBlock - | CaseOrDefaultClause - ; + | CaseOrDefaultClause; export interface Block extends Statement, LocalsContainer { readonly kind: SyntaxKind.Block; @@ -3389,8 +3318,7 @@ export interface WhileStatement extends IterationStatement, FlowContainer { export type ForInitializer = | VariableDeclarationList - | Expression - ; + | Expression; export interface ForStatement extends IterationStatement, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.ForStatement; @@ -3401,8 +3329,7 @@ export interface ForStatement extends IterationStatement, LocalsContainer, FlowC export type ForInOrOfStatement = | ForInStatement - | ForOfStatement - ; + | ForOfStatement; export interface ForInStatement extends IterationStatement, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.ForInStatement; @@ -3429,8 +3356,7 @@ export interface ContinueStatement extends Statement, FlowContainer { export type BreakOrContinueStatement = | BreakStatement - | ContinueStatement - ; + | ContinueStatement; export interface ReturnStatement extends Statement, FlowContainer { readonly kind: SyntaxKind.ReturnStatement; @@ -3473,8 +3399,7 @@ export interface DefaultClause extends Node { export type CaseOrDefaultClause = | CaseClause - | DefaultClause - ; + | DefaultClause; export interface LabeledStatement extends Statement, FlowContainer { readonly kind: SyntaxKind.LabeledStatement; @@ -3504,23 +3429,20 @@ export interface CatchClause extends Node, LocalsContainer { export type ObjectTypeDeclaration = | ClassLikeDeclaration | InterfaceDeclaration - | TypeLiteralNode - ; + | TypeLiteralNode; export type DeclarationWithTypeParameters = | DeclarationWithTypeParameterChildren | JSDocTypedefTag | JSDocCallbackTag - | JSDocSignature - ; + | JSDocSignature; export type DeclarationWithTypeParameterChildren = | SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration - | JSDocTemplateTag - ; + | JSDocTemplateTag; export interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; @@ -3544,8 +3466,7 @@ export interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpres export type ClassLikeDeclaration = | ClassDeclaration - | ClassExpression - ; + | ClassExpression; export interface ClassElement extends NamedDeclaration { _classElementBrand: any; @@ -3600,13 +3521,11 @@ export interface EnumDeclaration extends DeclarationStatement, JSDocContainer { export type ModuleName = | Identifier - | StringLiteral - ; + | StringLiteral; export type ModuleBody = | NamespaceBody - | JSDocNamespaceBody - ; + | JSDocNamespaceBody; /** @internal */ export interface AmbientModuleDeclaration extends ModuleDeclaration { @@ -3623,8 +3542,7 @@ export interface ModuleDeclaration extends DeclarationStatement, JSDocContainer, export type NamespaceBody = | ModuleBlock - | NamespaceDeclaration - ; + | NamespaceDeclaration; export interface NamespaceDeclaration extends ModuleDeclaration { readonly name: Identifier; @@ -3633,8 +3551,7 @@ export interface NamespaceDeclaration extends ModuleDeclaration { export type JSDocNamespaceBody = | Identifier - | JSDocNamespaceDeclaration - ; + | JSDocNamespaceDeclaration; export interface JSDocNamespaceDeclaration extends ModuleDeclaration { readonly name: Identifier; @@ -3649,8 +3566,7 @@ export interface ModuleBlock extends Node, Statement { export type ModuleReference = | EntityName - | ExternalModuleReference - ; + | ExternalModuleReference; /** * One of: @@ -3691,13 +3607,11 @@ export interface ImportDeclaration extends Statement { export type NamedImportBindings = | NamespaceImport - | NamedImports - ; + | NamedImports; export type NamedExportBindings = | NamespaceExport - | NamedExports - ; + | NamedExports; // In case of: // import d from "mod" => name = d, namedBinding = undefined @@ -3724,7 +3638,7 @@ export interface AssertEntry extends Node { export interface AssertClause extends Node { readonly kind: SyntaxKind.AssertClause; - readonly parent: ImportDeclaration | ExportDeclaration + readonly parent: ImportDeclaration | ExportDeclaration; readonly elements: NodeArray; readonly multiLine?: boolean; } @@ -3738,7 +3652,7 @@ export interface NamespaceImport extends NamedDeclaration { export interface NamespaceExport extends NamedDeclaration { readonly kind: SyntaxKind.NamespaceExport; readonly parent: ExportDeclaration; - readonly name: Identifier + readonly name: Identifier; } export interface NamespaceExportDeclaration extends DeclarationStatement, JSDocContainer { @@ -3778,8 +3692,8 @@ export type NamedImportsOrExports = NamedImports | NamedExports; export interface ImportSpecifier extends NamedDeclaration { readonly kind: SyntaxKind.ImportSpecifier; readonly parent: NamedImports; - readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) - readonly name: Identifier; // Declared name + readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) + readonly name: Identifier; // Declared name readonly isTypeOnly: boolean; } @@ -3787,14 +3701,13 @@ export interface ExportSpecifier extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.ExportSpecifier; readonly parent: NamedExports; readonly isTypeOnly: boolean; - readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) - readonly name: Identifier; // Declared name + readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) + readonly name: Identifier; // Declared name } export type ImportOrExportSpecifier = | ImportSpecifier - | ExportSpecifier - ; + | ExportSpecifier; export type TypeOnlyCompatibleAliasDeclaration = | ImportClause @@ -3802,21 +3715,19 @@ export type TypeOnlyCompatibleAliasDeclaration = | NamespaceImport | ImportOrExportSpecifier | ExportDeclaration - | NamespaceExport - ; + | NamespaceExport; export type TypeOnlyImportDeclaration = - | ImportClause & { readonly isTypeOnly: true, readonly name: Identifier } - | ImportEqualsDeclaration & { readonly isTypeOnly: true } - | NamespaceImport & { readonly parent: ImportClause & { readonly isTypeOnly: true } } - | ImportSpecifier & ({ readonly isTypeOnly: true } | { readonly parent: NamedImports & { readonly parent: ImportClause & { readonly isTypeOnly: true } } }) - ; + | ImportClause & { readonly isTypeOnly: true; readonly name: Identifier; } + | ImportEqualsDeclaration & { readonly isTypeOnly: true; } + | NamespaceImport & { readonly parent: ImportClause & { readonly isTypeOnly: true; }; } + | ImportSpecifier & ({ readonly isTypeOnly: true; } | { readonly parent: NamedImports & { readonly parent: ImportClause & { readonly isTypeOnly: true; }; }; }); export type TypeOnlyExportDeclaration = - | ExportSpecifier & ({ readonly isTypeOnly: true } | { readonly parent: NamedExports & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true } } }) - | ExportDeclaration & { readonly isTypeOnly: true, readonly moduleSpecifier: Expression } // export * from "mod" - | NamespaceExport & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true, readonly moduleSpecifier: Expression } } // export * as ns from "mod" - ; + | ExportSpecifier & ({ readonly isTypeOnly: true; } | { readonly parent: NamedExports & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true; }; }; }) + | ExportDeclaration & { readonly isTypeOnly: true; readonly moduleSpecifier: Expression; } // export * from "mod" + | NamespaceExport & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true; readonly moduleSpecifier: Expression; }; } // export * as ns from "mod" +; export type TypeOnlyAliasDeclaration = TypeOnlyImportDeclaration | TypeOnlyExportDeclaration; @@ -3920,8 +3831,7 @@ export type JSDocTypeReferencingNode = | JSDocVariadicType | JSDocOptionalType | JSDocNullableType - | JSDocNonNullableType - ; + | JSDocNonNullableType; export interface JSDoc extends Node { readonly kind: SyntaxKind.JSDoc; @@ -3971,12 +3881,12 @@ export interface JSDocUnknownTag extends JSDocTag { */ export interface JSDocAugmentsTag extends JSDocTag { readonly kind: SyntaxKind.JSDocAugmentsTag; - readonly class: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression }; + readonly class: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; }; } export interface JSDocImplementsTag extends JSDocTag { readonly kind: SyntaxKind.JSDocImplementsTag; - readonly class: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression }; + readonly class: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; }; } export interface JSDocAuthorTag extends JSDocTag { @@ -4059,7 +3969,6 @@ export interface JSDocCallbackTag extends JSDocTag, NamedDeclaration, LocalsCont readonly typeExpression: JSDocSignature; } - export interface JSDocOverloadTag extends JSDocTag { readonly kind: SyntaxKind.JSDocOverloadTag; readonly parent: JSDoc; @@ -4113,6 +4022,7 @@ export interface JSDocSatisfiesExpression extends ParenthesizedExpression { } // NOTE: Ensure this is up-to-date with src/debug/debug.ts +// dprint-ignore export const enum FlowFlags { Unreachable = 1 << 0, // Unreachable code Start = 1 << 1, // Start of flow graph @@ -4144,7 +4054,7 @@ export type FlowNode = export interface FlowNodeBase { flags: FlowFlags; - id?: number; // Node id used by flow type cache in checker + id?: number; // Node id used by flow type cache in checker } // FlowStart represents the start of a control flow. For a function expression or arrow @@ -4178,6 +4088,7 @@ export interface FlowCondition extends FlowNodeBase { antecedent: FlowNode; } +// dprint-ignore export interface FlowSwitchClause extends FlowNodeBase { switchStatement: SwitchStatement; clauseStart: number; // Start index of case/default clause range @@ -4203,6 +4114,7 @@ export type FlowType = Type | IncompleteType; // Incomplete types occur during control flow analysis of loops. An IncompleteType // is distinguished from a regular type by a flags value of zero. Incomplete type // objects are internal to the getFlowTypeOfReference function and never escape it. +// dprint-ignore export interface IncompleteType { flags: TypeFlags | 0; // No flags set type: Type; // The type marked incomplete @@ -4415,7 +4327,7 @@ export interface SourceFile extends ReadonlyPragmaContext {} /** @internal */ export interface CommentDirective { range: TextRange; - type: CommentDirectiveType, + type: CommentDirectiveType; } /** @internal */ @@ -4481,15 +4393,13 @@ export interface UnparsedSource extends Node { /** @deprecated */ export type UnparsedSourceText = | UnparsedPrepend - | UnparsedTextLike - ; + | UnparsedTextLike; /** @deprecated */ export type UnparsedNode = | UnparsedPrologue | UnparsedSourceText - | UnparsedSyntheticReference - ; + | UnparsedSyntheticReference; /** @deprecated */ export interface UnparsedSection extends Node { @@ -4548,8 +4458,7 @@ export type JsonObjectExpression = | NumericLiteral | StringLiteral | BooleanLiteral - | NullLiteral - ; + | NullLiteral; export interface JsonObjectExpressionStatement extends ExpressionStatement { readonly expression: JsonObjectExpression; @@ -4582,7 +4491,7 @@ export interface ParseConfigHost extends ModuleResolutionHost { * specified like "./blah" to an absolute path to an actual * tsconfig file, e.g. "/root/blah/tsconfig.json" */ -export type ResolvedConfigFileName = string & { _isResolvedConfigFileName: never }; +export type ResolvedConfigFileName = string & { _isResolvedConfigFileName: never; }; export interface WriteFileCallbackData { /** @internal */ sourceMapUrlPos?: number; @@ -4599,7 +4508,7 @@ export type WriteFileCallback = ( data?: WriteFileCallbackData, ) => void; -export class OperationCanceledException { } +export class OperationCanceledException {} export interface CancellationToken { isCancellationRequested(): boolean; @@ -4618,12 +4527,12 @@ export enum FileIncludeKind { TypeReferenceDirective, LibFile, LibReferenceDirective, - AutomaticTypeDirectiveFile + AutomaticTypeDirectiveFile, } /** @internal */ export interface RootFile { - kind: FileIncludeKind.RootFile, + kind: FileIncludeKind.RootFile; index: number; } @@ -4634,8 +4543,9 @@ export interface LibFile { } /** @internal */ -export type ProjectReferenceFileKind = FileIncludeKind.SourceFromProjectReference | - FileIncludeKind.OutputFromProjectReference; +export type ProjectReferenceFileKind = + | FileIncludeKind.SourceFromProjectReference + | FileIncludeKind.OutputFromProjectReference; /** @internal */ export interface ProjectReferenceFile { @@ -4644,10 +4554,11 @@ export interface ProjectReferenceFile { } /** @internal */ -export type ReferencedFileKind = FileIncludeKind.Import | - FileIncludeKind.ReferenceFile | - FileIncludeKind.TypeReferenceDirective | - FileIncludeKind.LibReferenceDirective; +export type ReferencedFileKind = + | FileIncludeKind.Import + | FileIncludeKind.ReferenceFile + | FileIncludeKind.TypeReferenceDirective + | FileIncludeKind.LibReferenceDirective; /** @internal */ export interface ReferencedFile { @@ -4665,11 +4576,11 @@ export interface AutomaticTypeDirectiveFile { /** @internal */ export type FileIncludeReason = - RootFile | - LibFile | - ProjectReferenceFile | - ReferencedFile | - AutomaticTypeDirectiveFile; + | RootFile + | LibFile + | ProjectReferenceFile + | ReferencedFile + | AutomaticTypeDirectiveFile; /** @internal */ export const enum FilePreprocessingDiagnosticsKind { @@ -4705,7 +4616,7 @@ export interface ResolutionDiagnostics { export type FilePreprocessingDiagnostics = FilePreprocessingReferencedDiagnostic | FilePreprocessingFileExplainingDiagnostic | ResolutionDiagnostics; /** @internal */ -export const enum EmitOnly{ +export const enum EmitOnly { Js, Dts, } @@ -4781,7 +4692,7 @@ export interface Program extends ScriptReferenceHost { getSymbolCount(): number; getTypeCount(): number; getInstantiationCount(): number; - getRelationCacheSizes(): { assignable: number, identity: number, subtype: number, strictSubtype: number }; + getRelationCacheSizes(): { assignable: number; identity: number; subtype: number; strictSubtype: number; }; /** @internal */ getFileProcessingDiagnostics(): FilePreprocessingDiagnostics[] | undefined; /** @internal */ getResolvedTypeReferenceDirectives(): ModeAwareCache; @@ -4913,7 +4824,7 @@ export interface SourceMapSpan { /** @internal */ export interface SourceMapEmitResult { - inputSourceFileNames: readonly string[]; // Input source file (which one can use on program to get the file), 1:1 mapping with the sourceMap.sources list + inputSourceFileNames: readonly string[]; // Input source file (which one can use on program to get the file), 1:1 mapping with the sourceMap.sources list sourceMap: RawSourceMap; } @@ -4942,7 +4853,7 @@ export interface EmitResult { /** Contains declaration emit diagnostics */ diagnostics: readonly Diagnostic[]; emittedFiles?: string[]; // Array of files the compiler wrote to disk - /** @internal */ sourceMaps?: SourceMapEmitResult[]; // Array of sourceMapData if compiler emitted sourcemaps + /** @internal */ sourceMaps?: SourceMapEmitResult[]; // Array of sourceMapData if compiler emitted sourcemaps } /** @internal */ @@ -4992,7 +4903,7 @@ export interface TypeChecker { * @internal */ getParameterType(signature: Signature, parameterIndex: number): Type; - /** @internal */ getParameterIdentifierInfoAtPosition(signature: Signature, parameterIndex: number): { parameter: Identifier, parameterName: __String, isRestParameter: boolean } | undefined; + /** @internal */ getParameterIdentifierInfoAtPosition(signature: Signature, parameterIndex: number): { parameter: Identifier; parameterName: __String; isRestParameter: boolean; } | undefined; getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** @internal */ getNonOptionalType(type: Type): Type; @@ -5004,8 +4915,8 @@ export interface TypeChecker { typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; /** @internal */ typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): TypeNode | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): SignatureDeclaration & {typeArguments?: NodeArray} | undefined; - /** @internal */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): SignatureDeclaration & {typeArguments?: NodeArray} | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): SignatureDeclaration & { typeArguments?: NodeArray; } | undefined; + /** @internal */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): SignatureDeclaration & { typeArguments?: NodeArray; } | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; /** @internal */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): IndexSignatureDeclaration | undefined; // eslint-disable-line @typescript-eslint/unified-signatures @@ -5196,7 +5107,7 @@ export interface TypeChecker { resolvedReturnType: Type, typePredicate: TypePredicate | undefined, minArgumentCount: number, - flags: SignatureFlags + flags: SignatureFlags, ): Signature; /** @internal */ createSymbol(flags: SymbolFlags, name: __String): TransientSymbol; /** @internal */ createIndexInfo(keyType: Type, type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo; @@ -5216,7 +5127,7 @@ export interface TypeChecker { /** @internal */ getSymbolCount(): number; /** @internal */ getTypeCount(): number; /** @internal */ getInstantiationCount(): number; - /** @internal */ getRelationCacheSizes(): { assignable: number, identity: number, subtype: number, strictSubtype: number }; + /** @internal */ getRelationCacheSizes(): { assignable: number; identity: number; subtype: number; strictSubtype: number; }; /** @internal */ getRecursionIdentity(type: Type): object | undefined; /** @internal */ getUnmatchedProperties(source: Type, target: Type, requireOptionalProperties: boolean, matchDiscriminantProperties: boolean): IterableIterator; @@ -5313,7 +5224,7 @@ export interface TypeChecker { export const enum MemberOverrideStatus { Ok, NeedsOverride, - HasInvalidOverride + HasInvalidOverride, } /** @internal */ @@ -5323,6 +5234,7 @@ export const enum UnionReduction { Subtype, } +// dprint-ignore /** @internal */ export const enum ContextFlags { None = 0, @@ -5333,6 +5245,7 @@ export const enum ContextFlags { } // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! +// dprint-ignore export const enum NodeBuilderFlags { None = 0, // Options @@ -5378,6 +5291,7 @@ export const enum NodeBuilderFlags { } // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment +// dprint-ignore export const enum TypeFormatFlags { None = 0, NoTruncation = 1 << 0, // Don't truncate typeToString result @@ -5416,9 +5330,10 @@ export const enum TypeFormatFlags { NodeBuilderFlagsMask = NoTruncation | WriteArrayAsGenericType | UseStructuralFallback | WriteTypeArgumentsOfSignature | UseFullyQualifiedType | SuppressAnyReturnType | MultilineObjectLiterals | WriteClassExpressionAsTypeLiteral | UseTypeOfFunction | OmitParameterModifiers | UseAliasDefinedOutsideCurrentScope | AllowUniqueESSymbolType | InTypeAlias | - UseSingleQuotesForStringLiteralType | NoTypeReduction | OmitThisParameter + UseSingleQuotesForStringLiteralType | NoTypeReduction | OmitThisParameter, } +// dprint-ignore export const enum SymbolFormatFlags { None = 0, @@ -5449,9 +5364,9 @@ export const enum SymbolFormatFlags { /** @internal */ export interface SymbolWalker { /** Note: Return values are not ordered. */ - walkType(root: Type): { visitedTypes: readonly Type[], visitedSymbols: readonly Symbol[] }; + walkType(root: Type): { visitedTypes: readonly Type[]; visitedSymbols: readonly Symbol[]; }; /** Note: Return values are not ordered. */ - walkSymbol(root: Symbol): { visitedTypes: readonly Type[], visitedSymbols: readonly Symbol[] }; + walkSymbol(root: Symbol): { visitedTypes: readonly Type[]; visitedSymbols: readonly Symbol[]; }; } // This was previously deprecated in our public API, but is still used internally @@ -5475,20 +5390,20 @@ export interface SymbolWriter { export const enum SymbolAccessibility { Accessible, NotAccessible, - CannotBeNamed + CannotBeNamed, } /** @internal */ export const enum SyntheticSymbolKind { UnionOrIntersection, - Spread + Spread, } export const enum TypePredicateKind { This, Identifier, AssertsThis, - AssertsIdentifier + AssertsIdentifier, } export interface TypePredicateBase { @@ -5538,8 +5453,10 @@ export type AnyImportOrBareOrAccessedRequire = AnyImportSyntax | VariableDeclara /** @internal */ export type AliasDeclarationNode = | ImportEqualsDeclaration - | VariableDeclarationInitializedTo + | VariableDeclarationInitializedTo< + | RequireOrImportCall + | AccessExpression + > | ImportClause | NamespaceImport | ImportSpecifier @@ -5548,7 +5465,7 @@ export type AliasDeclarationNode = | BindingElementOfBareOrAccessedRequire; /** @internal */ -export type BindingElementOfBareOrAccessedRequire = BindingElement & { parent: { parent: VariableDeclarationInitializedTo } }; +export type BindingElementOfBareOrAccessedRequire = BindingElement & { parent: { parent: VariableDeclarationInitializedTo; }; }; /** @internal */ export type AnyImportOrRequireStatement = AnyImportSyntax | RequireVariableStatement; @@ -5558,18 +5475,18 @@ export type AnyImportOrReExport = AnyImportSyntax | ExportDeclaration; /** @internal */ export interface ValidImportTypeNode extends ImportTypeNode { - argument: LiteralTypeNode & { literal: StringLiteral }; + argument: LiteralTypeNode & { literal: StringLiteral; }; } /** @internal */ export type AnyValidImportOrReExport = - | (ImportDeclaration | ExportDeclaration) & { moduleSpecifier: StringLiteral } - | ImportEqualsDeclaration & { moduleReference: ExternalModuleReference & { expression: StringLiteral } } + | (ImportDeclaration | ExportDeclaration) & { moduleSpecifier: StringLiteral; } + | ImportEqualsDeclaration & { moduleReference: ExternalModuleReference & { expression: StringLiteral; }; } | RequireOrImportCall | ValidImportTypeNode; /** @internal */ -export type RequireOrImportCall = CallExpression & { expression: Identifier, arguments: [StringLiteralLike] }; +export type RequireOrImportCall = CallExpression & { expression: Identifier; arguments: [StringLiteralLike]; }; /** @internal */ export interface VariableDeclarationInitializedTo extends VariableDeclaration { @@ -5719,6 +5636,7 @@ export interface EmitResolver { isImportRequiredByAugmentation(decl: ImportDeclaration): boolean; } +// dprint-ignore export const enum SymbolFlags { None = 0, FunctionScopedVariable = 1 << 0, // Variable (var) or parameter @@ -5815,6 +5733,7 @@ export const enum SymbolFlags { /** @internal */ export type SymbolId = number; +// dprint-ignore export interface Symbol { flags: SymbolFlags; // Symbol flags escapedName: __String; // Name of symbol @@ -5834,6 +5753,7 @@ export interface Symbol { /** @internal */ assignmentDeclarationMembers?: Map; // detected late-bound assignment declarations associated with the symbol } +// dprint-ignore /** @internal */ export interface SymbolLinks { _symbolLinksBrand: any; @@ -5888,10 +5808,11 @@ export interface SymbolLinks { /** @internal */ export const enum EnumKind { - Numeric, // Numeric enum (each member has a TypeFlags.Enum type) - Literal // Literal enum (each member has a TypeFlags.EnumLiteral type) + Numeric, // Numeric enum (each member has a TypeFlags.Enum type) + Literal, // Literal enum (each member has a TypeFlags.EnumLiteral type) } +// dprint-ignore /** @internal */ export const enum CheckFlags { None = 0, @@ -5918,7 +5839,7 @@ export const enum CheckFlags { Unresolved = 1 << 20, // Unresolved type alias symbol Synthetic = SyntheticProperty | SyntheticMethod, Discriminant = HasNonUniformType | HasLiteralType, - Partial = ReadPartial | WritePartial + Partial = ReadPartial | WritePartial, } /** @internal */ @@ -5982,7 +5903,7 @@ export const enum InternalSymbolName { * with a normal string (which is good, it cannot be misused on assignment or on usage), * while still being comparable with a normal string via === (also good) and castable from a string. */ -export type __String = (string & { __escapedIdentifier: void }) | (void & { __escapedIdentifier: void }) | InternalSymbolName; +export type __String = (string & { __escapedIdentifier: void; }) | (void & { __escapedIdentifier: void; }) | InternalSymbolName; /** @deprecated Use ReadonlyMap<__String, T> instead. */ export type ReadonlyUnderscoreEscapedMap = ReadonlyMap<__String, T>; @@ -6003,6 +5924,7 @@ export interface PatternAmbientModule { symbol: Symbol; } +// dprint-ignore /** @internal */ export const enum NodeCheckFlags { None = 0, @@ -6031,6 +5953,7 @@ export const enum NodeCheckFlags { InCheckIdentifier = 1 << 22, } +// dprint-ignore /** @internal */ export interface NodeLinks { flags: NodeCheckFlags; // Set of flags specific to Node @@ -6073,6 +5996,7 @@ export interface SerializedTypeEntry { addedLength: number; } +// dprint-ignore export const enum TypeFlags { Any = 1 << 0, Unknown = 1 << 1, @@ -6172,6 +6096,7 @@ export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | Ar export type TypeId = number; // Properties common to all types +// dprint-ignore export interface Type { flags: TypeFlags; // Flags /** @internal */ id: TypeId; // Unique ID @@ -6193,7 +6118,7 @@ export interface Type { /** @internal */ // Intrinsic types (TypeFlags.Intrinsic) export interface IntrinsicType extends Type { - intrinsicName: string; // Name of intrinsic type + intrinsicName: string; // Name of intrinsic type objectFlags: ObjectFlags; } @@ -6203,8 +6128,8 @@ export interface NullableType extends IntrinsicType { } export interface FreshableType extends Type { - freshType: FreshableType; // Fresh version of type - regularType: FreshableType; // Regular version of type + freshType: FreshableType; // Fresh version of type + regularType: FreshableType; // Regular version of type } /** @internal */ @@ -6243,6 +6168,7 @@ export interface EnumType extends FreshableType { // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check // for a certain TypeFlags value to determine their meaning. +// dprint-ignore export const enum ObjectFlags { None = 0, Class = 1 << 0, // Class @@ -6324,6 +6250,7 @@ export const enum ObjectFlags { export type ObjectFlagsType = NullableType | ObjectType | UnionType | IntersectionType | TemplateLiteralType; // Object types (TypeFlags.ObjectType) +// dprint-ignore export interface ObjectType extends Type { objectFlags: ObjectFlags; /** @internal */ members?: SymbolTable; // Properties by name @@ -6335,6 +6262,7 @@ export interface ObjectType extends Type { } /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ +// dprint-ignore export interface InterfaceType extends ObjectType { typeParameters: TypeParameter[] | undefined; // Type parameters (undefined if non-generic) outerTypeParameters: TypeParameter[] | undefined; // Outer type parameters (undefined if none) @@ -6351,6 +6279,7 @@ export interface InterfaceType extends ObjectType { // Object type or intersection of object types export type BaseType = ObjectType | IntersectionType | TypeVariable; // Also `any` and `object` +// dprint-ignore export interface InterfaceTypeWithDeclaredMembers extends InterfaceType { declaredProperties: Symbol[]; // Declared members declaredCallSignatures: Signature[]; // Declared call signatures @@ -6369,14 +6298,14 @@ export interface InterfaceTypeWithDeclaredMembers extends InterfaceType { * explicit "this" argument. */ export interface TypeReference extends ObjectType { - target: GenericType; // Type reference target + target: GenericType; // Type reference target node?: TypeReferenceNode | ArrayTypeNode | TupleTypeNode; /** @internal */ mapper?: TypeMapper; /** @internal */ - resolvedTypeArguments?: readonly Type[]; // Resolved type reference type arguments + resolvedTypeArguments?: readonly Type[]; // Resolved type reference type arguments /** @internal */ - literalType?: TypeReference; // Clone of type with ObjectFlags.ArrayLiteral set + literalType?: TypeReference; // Clone of type with ObjectFlags.ArrayLiteral set /** @internal */ cachedEquivalentBaseType?: Type; // Only set on references to class or interfaces with a single base type and no augmentations } @@ -6390,6 +6319,7 @@ export interface DeferredTypeReference extends TypeReference { instantiations?: Map; // Instantiations of generic type alias (undefined if non-generic) } +// dprint-ignore /** @internal */ export const enum VarianceFlags { Invariant = 0, // Neither covariant nor contravariant @@ -6406,11 +6336,12 @@ export const enum VarianceFlags { // Generic class and interface types export interface GenericType extends InterfaceType, TypeReference { /** @internal */ - instantiations: Map; // Generic instantiation cache + instantiations: Map; // Generic instantiation cache /** @internal */ - variances?: VarianceFlags[]; // Variance of each type parameter + variances?: VarianceFlags[]; // Variance of each type parameter } +// dprint-ignore export const enum ElementFlags { Required = 1 << 0, // T Optional = 1 << 1, // T? @@ -6440,11 +6371,11 @@ export interface TupleTypeReference extends TypeReference { } export interface UnionOrIntersectionType extends Type { - types: Type[]; // Constituent types + types: Type[]; // Constituent types /** @internal */ objectFlags: ObjectFlags; /** @internal */ - propertyCache?: SymbolTable; // Cache of resolved properties + propertyCache?: SymbolTable; // Cache of resolved properties /** @internal */ propertyCacheWithoutObjectFunctionPropertyAugment?: SymbolTable; // Cache of resolved properties that does not augment function or object type properties /** @internal */ @@ -6463,11 +6394,11 @@ export interface UnionType extends UnionOrIntersectionType { /** @internal */ regularType?: UnionType; /** @internal */ - origin?: Type; // Denormalized union, intersection, or index type in which union originates + origin?: Type; // Denormalized union, intersection, or index type in which union originates /** @internal */ - keyPropertyName?: __String; // Property with unique unit type that exists in every object/intersection in union type + keyPropertyName?: __String; // Property with unique unit type that exists in every object/intersection in union type /** @internal */ - constituentMap?: Map; // Constituents keyed by unit type discriminants + constituentMap?: Map; // Constituents keyed by unit type discriminants /** @internal */ arrayFallbackSignatures?: readonly Signature[]; // Special remapped signature list for unions of arrays } @@ -6476,7 +6407,7 @@ export interface IntersectionType extends UnionOrIntersectionType { /** @internal */ resolvedApparentType: Type; /** @internal */ - uniqueLiteralFilledInstantiation?: Type; // Instantiation with type parameters mapped to never type + uniqueLiteralFilledInstantiation?: Type; // Instantiation with type parameters mapped to never type } export type StructuredType = ObjectType | UnionType | IntersectionType; @@ -6484,8 +6415,8 @@ export type StructuredType = ObjectType | UnionType | IntersectionType; /** @internal */ // An instantiated anonymous type has a target and a mapper export interface AnonymousType extends ObjectType { - target?: AnonymousType; // Instantiation target - mapper?: TypeMapper; // Instantiation mapper + target?: AnonymousType; // Instantiation target + mapper?: TypeMapper; // Instantiation mapper instantiations?: Map; // Instantiations of generic type alias (undefined if non-generic) } @@ -6507,8 +6438,8 @@ export interface MappedType extends AnonymousType { } export interface EvolvingArrayType extends ObjectType { - elementType: Type; // Element expressions of evolving array type - finalArrayType?: Type; // Final array type of evolving array type + elementType: Type; // Element expressions of evolving array type + finalArrayType?: Type; // Final array type of evolving array type } /** @internal */ @@ -6520,6 +6451,7 @@ export interface ReverseMappedType extends ObjectType { /** @internal */ // Resolved object, union, or intersection type +// dprint-ignore export interface ResolvedType extends ObjectType, UnionOrIntersectionType { members: SymbolTable; // Properties by name properties: Symbol[]; // Properties @@ -6533,7 +6465,7 @@ export interface ResolvedType extends ObjectType, UnionOrIntersectionType { // before a type assertion, or when an object literal's type is widened. The regular // version of a fresh type is identical except for the TypeFlags.FreshObjectLiteral flag. export interface FreshObjectLiteralType extends ResolvedType { - regularType: ResolvedType; // Regular version of fresh type + regularType: ResolvedType; // Regular version of fresh type } /** @internal */ @@ -6578,6 +6510,7 @@ export interface InstantiableType extends Type { } // Type parameters (TypeFlags.TypeParameter) +// dprint-ignore export interface TypeParameter extends InstantiableType { /** * Retrieve using getConstraintFromTypeParameter @@ -6618,7 +6551,7 @@ export interface IndexedAccessType extends InstantiableType { objectType: Type; indexType: Type; /** @internal */ - accessFlags: AccessFlags; // Only includes AccessFlags.Persistent + accessFlags: AccessFlags; // Only includes AccessFlags.Persistent constraint?: Type; simplifiedForReading?: Type; simplifiedForWriting?: Type; @@ -6675,8 +6608,8 @@ export interface ConditionalType extends InstantiableType { export interface TemplateLiteralType extends InstantiableType { /** @internal */ objectFlags: ObjectFlags; - texts: readonly string[]; // Always one element longer than types - types: readonly Type[]; // Always at least one element + texts: readonly string[]; // Always one element longer than types + types: readonly Type[]; // Always at least one element } export interface StringMappingType extends InstantiableType { @@ -6692,15 +6625,15 @@ export interface StringMappingType extends InstantiableType { // types disappear upon instantiation (just like type parameters). export interface SubstitutionType extends InstantiableType { objectFlags: ObjectFlags; - baseType: Type; // Target type - constraint: Type; // Constraint that target type is known to satisfy + baseType: Type; // Target type + constraint: Type; // Constraint that target type is known to satisfy } /** @internal */ export const enum JsxReferenceKind { Component, Function, - Mixed + Mixed, } export const enum SignatureKind { @@ -6708,6 +6641,7 @@ export const enum SignatureKind { Construct, } +// dprint-ignore /** @internal */ export const enum SignatureFlags { None = 0, @@ -6732,6 +6666,7 @@ export const enum SignatureFlags { CallChainFlags = IsInnerCallChain | IsOuterCallChain, } +// dprint-ignore export interface Signature { /** @internal */ flags: SignatureFlags; /** @internal */ checker?: TypeChecker; @@ -6798,12 +6733,13 @@ export const enum TypeMapKind { /** @internal */ export type TypeMapper = - | { kind: TypeMapKind.Simple, source: Type, target: Type } - | { kind: TypeMapKind.Array, sources: readonly Type[], targets: readonly Type[] | undefined } - | { kind: TypeMapKind.Deferred, sources: readonly Type[], targets: (() => Type)[] } - | { kind: TypeMapKind.Function, func: (t: Type) => Type, debugInfo?: () => string } - | { kind: TypeMapKind.Composite | TypeMapKind.Merged, mapper1: TypeMapper, mapper2: TypeMapper }; + | { kind: TypeMapKind.Simple; source: Type; target: Type; } + | { kind: TypeMapKind.Array; sources: readonly Type[]; targets: readonly Type[] | undefined; } + | { kind: TypeMapKind.Deferred; sources: readonly Type[]; targets: (() => Type)[]; } + | { kind: TypeMapKind.Function; func: (t: Type) => Type; debugInfo?: () => string; } + | { kind: TypeMapKind.Composite | TypeMapKind.Merged; mapper1: TypeMapper; mapper2: TypeMapper; }; +// dprint-ignore export const enum InferencePriority { None = 0, NakedTypeVariable = 1 << 0, // Naked type variable in union or intersection type @@ -6823,6 +6759,7 @@ export const enum InferencePriority { Circularity = -1, // Inference circularity (value less than all other priorities) } +// dprint-ignore /** @internal */ export interface InferenceInfo { typeParameter: TypeParameter; // Type parameter for which inferences are being made @@ -6835,6 +6772,7 @@ export interface InferenceInfo { impliedArity?: number; } +// dprint-ignore /** @internal */ export const enum InferenceFlags { None = 0, // No special inference behaviors @@ -6857,12 +6795,13 @@ export const enum Ternary { False = 0, Unknown = 1, Maybe = 3, - True = -1 + True = -1, } /** @internal */ export type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; +// dprint-ignore /** @internal */ export interface InferenceContext { inferences: InferenceInfo[]; // Inferences made for each type parameter @@ -6882,6 +6821,7 @@ export interface IntraExpressionInferenceSite { type: Type; } +// dprint-ignore /** @internal */ export interface WideningContext { parent?: WideningContext; // Parent context @@ -6963,7 +6903,7 @@ export interface Diagnostic extends DiagnosticRelatedInformation { /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ reportsUnnecessary?: {}; - reportsDeprecated?: {} + reportsDeprecated?: {}; source?: string; relatedInformation?: DiagnosticRelatedInformation[]; /** @internal */ skippedOn?: keyof CompilerOptions; @@ -7002,31 +6942,31 @@ export enum DiagnosticCategory { Warning, Error, Suggestion, - Message + Message, } /** @internal */ -export function diagnosticCategoryName(d: { category: DiagnosticCategory }, lowerCase = true): string { +export function diagnosticCategoryName(d: { category: DiagnosticCategory; }, lowerCase = true): string { const name = DiagnosticCategory[d.category]; return lowerCase ? name.toLowerCase() : name; } export enum ModuleResolutionKind { - Classic = 1, + Classic = 1, /** * @deprecated * `NodeJs` was renamed to `Node10` to better reflect the version of Node that it targets. * Use the new name or consider switching to a modern module resolution target. */ - NodeJs = 2, - Node10 = 2, + NodeJs = 2, + Node10 = 2, // Starting with node12, node's module resolver has significant departures from traditional cjs resolution // to better support ecmascript modules and their use within node - however more features are still being added. // TypeScript's Node ESM support was introduced after Node 12 went end-of-life, and Node 14 is the earliest stable // version that supports both pattern trailers - *but*, Node 16 is the first version that also supports ECMASCript 2022. // In turn, we offer both a `NodeNext` moving resolution target, and a `Node16` version-anchored resolution target - Node16 = 3, + Node16 = 3, NodeNext = 99, // Not simply `Node16` so that compiled code linked against TS can use the `Next` value reliably (same as with `ModuleKind`) - Bundler = 100, + Bundler = 100, } export enum ModuleDetectionKind { @@ -7094,7 +7034,7 @@ export interface CompilerOptions { allowUmdGlobalAccess?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; - alwaysStrict?: boolean; // Always combine with strict property + alwaysStrict?: boolean; // Always combine with strict property baseUrl?: string; /** * An error if set - this should only go through the -b pipeline and not actually be observed @@ -7128,23 +7068,23 @@ export interface CompilerOptions { exactOptionalPropertyTypes?: boolean; experimentalDecorators?: boolean; forceConsistentCasingInFileNames?: boolean; - /** @internal */generateCpuProfile?: string; - /** @internal */generateTrace?: string; - /** @internal */help?: boolean; + /** @internal */ generateCpuProfile?: string; + /** @internal */ generateTrace?: string; + /** @internal */ help?: boolean; ignoreDeprecations?: string; importHelpers?: boolean; importsNotUsedAsValues?: ImportsNotUsedAsValues; - /** @internal */init?: boolean; + /** @internal */ init?: boolean; inlineSourceMap?: boolean; inlineSources?: boolean; isolatedModules?: boolean; jsx?: JsxEmit; keyofStringsOnly?: boolean; lib?: string[]; - /** @internal */listEmittedFiles?: boolean; - /** @internal */listFiles?: boolean; - /** @internal */explainFiles?: boolean; - /** @internal */listFilesOnly?: boolean; + /** @internal */ listEmittedFiles?: boolean; + /** @internal */ listFiles?: boolean; + /** @internal */ explainFiles?: boolean; + /** @internal */ listFilesOnly?: boolean; locale?: string; mapRoot?: string; maxNodeModuleJsDepth?: number; @@ -7154,14 +7094,14 @@ export interface CompilerOptions { moduleDetection?: ModuleDetectionKind; newLine?: NewLineKind; noEmit?: boolean; - /** @internal */noEmitForJsFiles?: boolean; + /** @internal */ noEmitForJsFiles?: boolean; noEmitHelpers?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; noFallthroughCasesInSwitch?: boolean; - noImplicitAny?: boolean; // Always combine with strict property + noImplicitAny?: boolean; // Always combine with strict property noImplicitReturns?: boolean; - noImplicitThis?: boolean; // Always combine with strict property + noImplicitThis?: boolean; // Always combine with strict property noStrictGenericChecks?: boolean; noUnusedLocals?: boolean; noUnusedParameters?: boolean; @@ -7208,10 +7148,10 @@ export interface CompilerOptions { sourceMap?: boolean; sourceRoot?: string; strict?: boolean; - strictFunctionTypes?: boolean; // Always combine with strict property - strictBindCallApply?: boolean; // Always combine with strict property - strictNullChecks?: boolean; // Always combine with strict property - strictPropertyInitialization?: boolean; // Always combine with strict property + strictFunctionTypes?: boolean; // Always combine with strict property + strictBindCallApply?: boolean; // Always combine with strict property + strictNullChecks?: boolean; // Always combine with strict property + strictPropertyInitialization?: boolean; // Always combine with strict property stripInternal?: boolean; suppressExcessPropertyErrors?: boolean; suppressImplicitAnyIndexErrors?: boolean; @@ -7289,7 +7229,7 @@ export const enum ImportsNotUsedAsValues { export const enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1 + LineFeed = 1, } export interface LineAndCharacter { @@ -7313,7 +7253,7 @@ export const enum ScriptKind { * Used on extensions that doesn't define the ScriptKind but the content defines it. * Deferred extensions are going to be included in all project contexts. */ - Deferred = 7 + Deferred = 7, } export const enum ScriptTarget { @@ -7334,7 +7274,7 @@ export const enum ScriptTarget { export const enum LanguageVariant { Standard, - JSX + JSX, } /** Either a parsed command line or a parsed tsconfig.json */ @@ -7375,8 +7315,8 @@ export interface ConfigFileSpecs { /** @internal */ export type ModuleImportResult = - | { module: T, modulePath?: string, error: undefined } - | { module: undefined, modulePath?: undefined, error: { stack?: string, message?: string } }; + | { module: T; modulePath?: string; error: undefined; } + | { module: undefined; modulePath?: undefined; error: { stack?: string; message?: string; }; }; export interface CreateProgramOptions { rootNames: readonly string[]; @@ -7389,6 +7329,7 @@ export interface CreateProgramOptions { typeScriptVersion?: string; } +// dprint-ignore /** @internal */ export interface CommandLineOptionBase { name: string; @@ -7436,7 +7377,7 @@ export interface CommandLineOptionOfBooleanType extends CommandLineOptionBase { /** @internal */ export interface CommandLineOptionOfCustomType extends CommandLineOptionBase { - type: Map; // an object literal mapping named values to actual values + type: Map; // an object literal mapping named values to actual values defaultValueDescription: number | string | undefined | DiagnosticMessage; deprecatedKeys?: Set; } @@ -7451,8 +7392,8 @@ export interface AlternateModeDiagnostics { export interface DidYouMeanOptionsDiagnostics { alternateMode?: AlternateModeDiagnostics; optionDeclarations: CommandLineOption[]; - unknownOptionDiagnostic: DiagnosticMessage, - unknownDidYouMeanDiagnostic: DiagnosticMessage, + unknownOptionDiagnostic: DiagnosticMessage; + unknownDidYouMeanDiagnostic: DiagnosticMessage; } /** @internal */ @@ -7472,6 +7413,7 @@ export interface CommandLineOptionOfListType extends CommandLineOptionBase { /** @internal */ export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfStringType | CommandLineOptionOfNumberType | CommandLineOptionOfBooleanType | TsConfigOnlyOption | CommandLineOptionOfListType; +// dprint-ignore /** @internal */ export const enum CharacterCodes { nullCharacter = 0, @@ -7720,7 +7662,7 @@ export interface ResolvedModuleWithFailedLookupLocations { /** @internal */ affectingLocations?: string[]; /** @internal */ - resolutionDiagnostics?: Diagnostic[] + resolutionDiagnostics?: Diagnostic[]; /** * @internal * Used to issue a diagnostic if typings for a non-relative import couldn't be found @@ -7805,7 +7747,7 @@ export interface CompilerHost extends ModuleResolutionHost { redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile | undefined, - reusedNames: readonly T[] | undefined + reusedNames: readonly T[] | undefined, ): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[]; /** @internal */ resolveLibrary?( @@ -7830,8 +7772,8 @@ export interface CompilerHost extends ModuleResolutionHost { /** @internal */ useSourceOfProjectReferenceRedirect?(): boolean; // TODO: later handle this in better way in builder host instead once the api for tsbuild finalizes and doesn't use compilerHost as base - /** @internal */createDirectory?(directory: string): void; - /** @internal */getSymlinkCache?(): SymlinkCache; + /** @internal */ createDirectory?(directory: string): void; + /** @internal */ getSymlinkCache?(): SymlinkCache; // For testing: /** @internal */ storeFilesChangingSignatureDuringEmit?: boolean; @@ -7932,7 +7874,6 @@ export const enum TransformFlags { // Propagating flags // - Bitmasks for flags that should propagate from a child PropertyNamePropagatingFlags = ContainsLexicalThis | ContainsLexicalSuper, - // Masks // - Additional bitmasks } @@ -7950,6 +7891,7 @@ export interface SourceMapSource { /** @internal */ // NOTE: Any new properties should be accounted for in `mergeEmitNode` in factory/nodeFactory.ts +// dprint-ignore export interface EmitNode { flags: EmitFlags; // Flags that customize emit internalFlags: InternalEmitFlags; // Internal flags that customize emit @@ -7989,6 +7931,7 @@ export interface Placeholder { } // Reference: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax +// dprint-ignore /** @internal */ export const enum SnippetKind { TabStop, // `$1`, `$2` @@ -7997,6 +7940,7 @@ export const enum SnippetKind { Variable, // `$name`, `${name:default}` } +// dprint-ignore export const enum EmitFlags { None = 0, SingleLine = 1 << 0, // The contents of this node should be emitted on a single line. @@ -8029,6 +7973,7 @@ export const enum EmitFlags { NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions. } +// dprint-ignore /** @internal */ export const enum InternalEmitFlags { None = 0, @@ -8040,6 +7985,7 @@ export const enum InternalEmitFlags { TransformPrivateStaticElements = 1 << 5, // Indicates static private elements in a file or class should be transformed regardless of --target (used by esDecorators transform) } +// dprint-ignore export interface EmitHelperBase { readonly name: string; // A unique name for this helper. readonly scoped: boolean; // Indicates whether the helper MUST be emitted in the current scope. @@ -8052,6 +7998,7 @@ export interface ScopedEmitHelper extends EmitHelperBase { readonly scoped: true; } +// dprint-ignore export interface UnscopedEmitHelper extends EmitHelperBase { readonly scoped: false; // Indicates whether the helper MUST be emitted in the current scope. /** @internal */ @@ -8066,6 +8013,7 @@ export type UniqueNameHandler = (baseName: string, checkFn?: (name: string) => b export type EmitHelperUniqueNameCallback = (name: string) => string; +// dprint-ignore /** * Used by the checker, this enum keeps track of external emit helpers that should be type * checked. @@ -8120,6 +8068,7 @@ export const enum ExternalEmitHelpers { SpreadIncludes = Read | SpreadArray, } +// dprint-ignore export const enum EmitHint { SourceFile, // Emitting a SourceFile Expression, // Emitting an Expression @@ -8193,9 +8142,8 @@ export type OuterExpression = /** @internal */ export type WrappedExpression = - | OuterExpression & { readonly expression: WrappedExpression } - | T - ; + | OuterExpression & { readonly expression: WrappedExpression; } + | T; /** @internal */ export type TypeOfTag = "null" | "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function"; @@ -8320,7 +8268,7 @@ export interface NodeFactory { getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; /** @internal */ getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags, prefix?: string | GeneratedNamePart, suffix?: string): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures - createPrivateIdentifier(text: string): PrivateIdentifier + createPrivateIdentifier(text: string): PrivateIdentifier; createUniquePrivateName(text?: string): PrivateIdentifier; /** @internal */ createUniquePrivateName(text?: string, prefix?: string | GeneratedNamePart, suffix?: string): PrivateIdentifier; // eslint-disable-line @typescript-eslint/unified-signatures getGeneratedPrivateNameForNode(node: Node): PrivateIdentifier; @@ -8893,7 +8841,6 @@ export interface NodeFactory { createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; - createVoidZero(): VoidExpression; createExportDefault(expression: Expression): ExportAssignment; createExternalModuleExport(exportName: Identifier): ExportDeclaration; @@ -9078,7 +9025,7 @@ export interface NodeFactory { export const enum LexicalEnvironmentFlags { None = 0, InParameters = 1 << 0, // currently visiting a parameter list - VariablesHoistedInParameters = 1 << 1 // a temp variable was hoisted while visiting a parameter list + VariablesHoistedInParameters = 1 << 1, // a temp variable was hoisted while visiting a parameter list } export interface CoreTransformationContext { @@ -9378,7 +9325,7 @@ export interface BundleFileTextLike extends BundleFileSectionBase { /** @deprecated @internal */ export type BundleFileSection = - BundleFilePrologue + | BundleFilePrologue | BundleFileEmitHelpers | BundleFileHasNoDefaultLib | BundleFileReference @@ -9679,7 +9626,7 @@ export interface SymbolTracker { reportCyclicStructureError?(): void; reportLikelyUnsafeImportRequiredError?(specifier: string): void; reportTruncationError?(): void; - moduleResolverHost?: ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string }; + moduleResolverHost?: ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string; }; trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void; trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void; reportNonlocalAugmentation?(containingFile: SourceFile, parentSymbol: Symbol, augmentingSymbol: Symbol): void; @@ -9720,6 +9667,7 @@ export interface SyntaxList extends Node { _children: Node[]; } +// dprint-ignore export const enum ListFormat { None = 0, @@ -9808,24 +9756,24 @@ export const enum ListFormat { /** @internal */ export const enum PragmaKindFlags { - None = 0, + None = 0, /** * Triple slash comment of the form * /// */ - TripleSlashXML = 1 << 0, + TripleSlashXML = 1 << 0, /** * Single line comment of the form * // @pragma-name argval1 argval2 * or * /// @pragma-name argval1 argval2 */ - SingleLine = 1 << 1, + SingleLine = 1 << 1, /** * Multiline non-jsdoc pragma of the form * /* @pragma-name argval1 argval2 * / */ - MultiLine = 1 << 2, + MultiLine = 1 << 2, All = TripleSlashXML | SingleLine | MultiLine, Default = All, } @@ -9858,58 +9806,55 @@ export const commentPragmas = { { name: "lib", optional: true, captureSpan: true }, { name: "path", optional: true, captureSpan: true }, { name: "no-default-lib", optional: true }, - { name: "resolution-mode", optional: true } + { name: "resolution-mode", optional: true }, ], - kind: PragmaKindFlags.TripleSlashXML + kind: PragmaKindFlags.TripleSlashXML, }, "amd-dependency": { args: [{ name: "path" }, { name: "name", optional: true }], - kind: PragmaKindFlags.TripleSlashXML + kind: PragmaKindFlags.TripleSlashXML, }, "amd-module": { args: [{ name: "name" }], - kind: PragmaKindFlags.TripleSlashXML + kind: PragmaKindFlags.TripleSlashXML, }, "ts-check": { - kind: PragmaKindFlags.SingleLine + kind: PragmaKindFlags.SingleLine, }, "ts-nocheck": { - kind: PragmaKindFlags.SingleLine + kind: PragmaKindFlags.SingleLine, }, "jsx": { args: [{ name: "factory" }], - kind: PragmaKindFlags.MultiLine + kind: PragmaKindFlags.MultiLine, }, "jsxfrag": { args: [{ name: "factory" }], - kind: PragmaKindFlags.MultiLine + kind: PragmaKindFlags.MultiLine, }, "jsximportsource": { args: [{ name: "factory" }], - kind: PragmaKindFlags.MultiLine + kind: PragmaKindFlags.MultiLine, }, "jsxruntime": { args: [{ name: "factory" }], - kind: PragmaKindFlags.MultiLine + kind: PragmaKindFlags.MultiLine, }, } as const; /** @internal */ -export type PragmaArgTypeMaybeCapture = TDesc extends {captureSpan: true} ? {value: string, pos: number, end: number} : string; +export type PragmaArgTypeMaybeCapture = TDesc extends { captureSpan: true; } ? { value: string; pos: number; end: number; } : string; /** @internal */ -export type PragmaArgTypeOptional = - TDesc extends {optional: true} - ? {[K in TName]?: PragmaArgTypeMaybeCapture} - : {[K in TName]: PragmaArgTypeMaybeCapture}; +export type PragmaArgTypeOptional = TDesc extends { optional: true; } ? { [K in TName]?: PragmaArgTypeMaybeCapture; } + : { [K in TName]: PragmaArgTypeMaybeCapture; }; /** @internal */ -export type UnionToIntersection = - (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; +export type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; /** @internal */ export type ArgumentDefinitionToFieldUnion[]> = { - [K in keyof T]: PragmaArgTypeOptional + [K in keyof T]: PragmaArgTypeOptional; }[Extract]; // The mapped type maps over only the tuple members, but this reindex gets _all_ members - by extracting only `number` keys, we get only the tuple members /** @@ -9917,19 +9862,17 @@ export type ArgumentDefinitionToFieldUnion = - ConcretePragmaSpecs[KPrag] extends { args: readonly PragmaArgumentSpecification[] } - ? UnionToIntersection> - : never; +export type PragmaArgumentType = ConcretePragmaSpecs[KPrag] extends { args: readonly PragmaArgumentSpecification[]; } ? UnionToIntersection> + : never; /** @internal */ export type ConcretePragmaSpecs = typeof commentPragmas; /** @internal */ -export type PragmaPseudoMap = {[K in keyof ConcretePragmaSpecs]: {arguments: PragmaArgumentType, range: CommentRange}}; +export type PragmaPseudoMap = { [K in keyof ConcretePragmaSpecs]: { arguments: PragmaArgumentType; range: CommentRange; }; }; /** @internal */ -export type PragmaPseudoMapEntry = {[K in keyof PragmaPseudoMap]: {name: K, args: PragmaPseudoMap[K]}}[keyof PragmaPseudoMap]; +export type PragmaPseudoMapEntry = { [K in keyof PragmaPseudoMap]: { name: K; args: PragmaPseudoMap[K]; }; }[keyof PragmaPseudoMap]; /** @internal */ export interface ReadonlyPragmaMap extends ReadonlyMap { @@ -9978,7 +9921,7 @@ export interface UserPreferences { readonly jsxAttributeCompletionStyle?: "auto" | "braces" | "none"; readonly includeInlayParameterNameHints?: "none" | "literals" | "all"; readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; - readonly includeInlayFunctionParameterTypeHints?: boolean, + readonly includeInlayFunctionParameterTypeHints?: boolean; readonly includeInlayVariableTypeHints?: boolean; readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; readonly includeInlayPropertyDeclarationTypeHints?: boolean; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index f00b10dbc7bb6..2edd5b0243bc8 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -668,8 +668,7 @@ export function changesAffectingProgramStructure(oldOptions: CompilerOptions, ne /** @internal */ export function optionsHaveChanges(oldOptions: CompilerOptions, newOptions: CompilerOptions, optionDeclarations: readonly CommandLineOption[]) { - return oldOptions !== newOptions && optionDeclarations.some(o => - !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); + return oldOptions !== newOptions && optionDeclarations.some(o => !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); } /** @internal */ @@ -785,13 +784,13 @@ export function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleWithFaile return oldResolution === newResolution || oldResolution.resolvedModule === newResolution.resolvedModule || !!oldResolution.resolvedModule && - !!newResolution.resolvedModule && - oldResolution.resolvedModule.isExternalLibraryImport === newResolution.resolvedModule.isExternalLibraryImport && - oldResolution.resolvedModule.extension === newResolution.resolvedModule.extension && - oldResolution.resolvedModule.resolvedFileName === newResolution.resolvedModule.resolvedFileName && - oldResolution.resolvedModule.originalPath === newResolution.resolvedModule.originalPath && - packageIdIsEqual(oldResolution.resolvedModule.packageId, newResolution.resolvedModule.packageId) && - oldResolution.node10Result === newResolution.node10Result; + !!newResolution.resolvedModule && + oldResolution.resolvedModule.isExternalLibraryImport === newResolution.resolvedModule.isExternalLibraryImport && + oldResolution.resolvedModule.extension === newResolution.resolvedModule.extension && + oldResolution.resolvedModule.resolvedFileName === newResolution.resolvedModule.resolvedFileName && + oldResolution.resolvedModule.originalPath === newResolution.resolvedModule.originalPath && + packageIdIsEqual(oldResolution.resolvedModule.packageId, newResolution.resolvedModule.packageId) && + oldResolution.node10Result === newResolution.node10Result; } /** @internal */ @@ -802,23 +801,28 @@ export function createModuleNotFoundChain(sourceFile: SourceFile, host: TypeChec /*details*/ undefined, Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings, node10Result, - node10Result.indexOf(nodeModulesPathPart + "@types/") > -1 ? `@types/${mangleScopedPackageName(packageName)}` : packageName) + node10Result.indexOf(nodeModulesPathPart + "@types/") > -1 ? `@types/${mangleScopedPackageName(packageName)}` : packageName, + ) : host.typesPackageExists(packageName) - ? chainDiagnosticMessages( - /*details*/ undefined, - Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, - packageName, mangleScopedPackageName(packageName)) - : host.packageBundlesTypes(packageName) - ? chainDiagnosticMessages( - /*details*/ undefined, - Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, - packageName, - moduleReference) - : chainDiagnosticMessages( - /*details*/ undefined, - Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, - moduleReference, - mangleScopedPackageName(packageName)); + ? chainDiagnosticMessages( + /*details*/ undefined, + Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, + packageName, + mangleScopedPackageName(packageName), + ) + : host.packageBundlesTypes(packageName) + ? chainDiagnosticMessages( + /*details*/ undefined, + Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, + packageName, + moduleReference, + ) + : chainDiagnosticMessages( + /*details*/ undefined, + Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, + moduleReference, + mangleScopedPackageName(packageName), + ); if (result) result.repopulateInfo = () => ({ moduleReference, mode, packageName: packageName === moduleReference ? undefined : packageName }); return result; } @@ -842,10 +846,10 @@ export function typeDirectiveIsEqualTo(oldResolution: ResolvedTypeReferenceDirec return oldResolution === newResolution || oldResolution.resolvedTypeReferenceDirective === newResolution.resolvedTypeReferenceDirective || !!oldResolution.resolvedTypeReferenceDirective && - !!newResolution.resolvedTypeReferenceDirective && - oldResolution.resolvedTypeReferenceDirective.resolvedFileName === newResolution.resolvedTypeReferenceDirective.resolvedFileName && - !!oldResolution.resolvedTypeReferenceDirective.primary === !!newResolution.resolvedTypeReferenceDirective.primary && - oldResolution.resolvedTypeReferenceDirective.originalPath === newResolution.resolvedTypeReferenceDirective.originalPath; + !!newResolution.resolvedTypeReferenceDirective && + oldResolution.resolvedTypeReferenceDirective.resolvedFileName === newResolution.resolvedTypeReferenceDirective.resolvedFileName && + !!oldResolution.resolvedTypeReferenceDirective.primary === !!newResolution.resolvedTypeReferenceDirective.primary && + oldResolution.resolvedTypeReferenceDirective.originalPath === newResolution.resolvedTypeReferenceDirective.originalPath; } /** @internal */ @@ -865,10 +869,9 @@ export function hasChangesInResolutions( const name = nameAndModeGetter.getName(entry); const mode = nameAndModeGetter.getMode(entry, newSourceFile); const oldResolution = oldResolutions && oldResolutions.get(name, mode); - const changed = - oldResolution - ? !newResolution || !comparer(oldResolution, newResolution) - : newResolution; + const changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; if (changed) { return true; } @@ -1066,7 +1069,6 @@ function insertStatementAfterPrologue(to: T[], statement: T return to; } - function isAnyPrologueDirective(node: Node) { return isPrologueDirective(node) || !!(getEmitFlags(node) & EmitFlags.CustomPrologue); } @@ -1109,16 +1111,18 @@ export function insertStatementAfterCustomPrologue(to: T[], export function isRecognizedTripleSlashComment(text: string, commentPos: number, commentEnd: number) { // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text // so that we don't end up computing comment string and doing match for all // comments - if (text.charCodeAt(commentPos + 1) === CharacterCodes.slash && + if ( + text.charCodeAt(commentPos + 1) === CharacterCodes.slash && commentPos + 2 < commentEnd && - text.charCodeAt(commentPos + 2) === CharacterCodes.slash) { + text.charCodeAt(commentPos + 2) === CharacterCodes.slash + ) { const textSubStr = text.substring(commentPos, commentEnd); return fullTripleSlashReferencePathRegEx.test(textSubStr) || - fullTripleSlashAMDReferencePathRegEx.test(textSubStr) || - fullTripleSlashAMDModuleRegEx.test(textSubStr) || - fullTripleSlashReferenceTypeReferenceDirectiveRegEx.test(textSubStr) || - fullTripleSlashLibReferenceRegEx.test(textSubStr) || - defaultLibReferenceRegEx.test(textSubStr) ? + fullTripleSlashAMDReferencePathRegEx.test(textSubStr) || + fullTripleSlashAMDModuleRegEx.test(textSubStr) || + fullTripleSlashReferenceTypeReferenceDirectiveRegEx.test(textSubStr) || + fullTripleSlashLibReferenceRegEx.test(textSubStr) || + defaultLibReferenceRegEx.test(textSubStr) ? true : false; } return false; @@ -1133,10 +1137,10 @@ export function isPinnedComment(text: string, start: number) { /** @internal */ export function createCommentDirectivesMap(sourceFile: SourceFile, commentDirectives: CommentDirective[]): CommentDirectivesMap { const directivesByLine = new Map( - commentDirectives.map(commentDirective => ([ + commentDirectives.map(commentDirective => [ `${getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line}`, commentDirective, - ])) + ]), ); const usedLines = new Map(); @@ -1189,7 +1193,8 @@ export function getTokenPosOfNode(node: Node, sourceFile?: SourceFileLike, inclu node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ false, - isInJSDoc(node)); + isInJSDoc(node), + ); } /** @internal */ @@ -1275,7 +1280,6 @@ export function getInternalEmitFlags(node: Node): InternalEmitFlags { /** @internal */ export type ScriptTargetFeatures = ReadonlyMap>; - /** @internal */ export function getScriptTargetFeatures(): ScriptTargetFeatures { return new Map(Object.entries({ @@ -1287,21 +1291,21 @@ export function getScriptTargetFeatures(): ScriptTargetFeatures { "copyWithin", "entries", "keys", - "values" + "values", ], es2016: [ - "includes" + "includes", ], es2019: [ "flat", - "flatMap" + "flatMap", ], es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Iterator: new Map(Object.entries({ @@ -1332,11 +1336,11 @@ export function getScriptTargetFeatures(): ScriptTargetFeatures { es2015: [ "flags", "sticky", - "unicode" + "unicode", ], es2018: [ - "dotAll" - ] + "dotAll", + ], })), Reflect: new Map(Object.entries({ es2015: [ @@ -1352,14 +1356,14 @@ export function getScriptTargetFeatures(): ScriptTargetFeatures { "ownKeys", "preventExtensions", "set", - "setPrototypeOf" - ] + "setPrototypeOf", + ], })), ArrayConstructor: new Map(Object.entries({ es2015: [ "from", - "of" - ] + "of", + ], })), ObjectConstructor: new Map(Object.entries({ es2015: [ @@ -1367,19 +1371,19 @@ export function getScriptTargetFeatures(): ScriptTargetFeatures { "getOwnPropertySymbols", "keys", "is", - "setPrototypeOf" + "setPrototypeOf", ], es2017: [ "values", "entries", - "getOwnPropertyDescriptors" + "getOwnPropertyDescriptors", ], es2019: [ - "fromEntries" + "fromEntries", ], es2022: [ - "hasOwn" - ] + "hasOwn", + ], })), NumberConstructor: new Map(Object.entries({ es2015: [ @@ -1388,8 +1392,8 @@ export function getScriptTargetFeatures(): ScriptTargetFeatures { "isNaN", "isSafeInteger", "parseFloat", - "parseInt" - ] + "parseInt", + ], })), Math: new Map(Object.entries({ es2015: [ @@ -1409,59 +1413,59 @@ export function getScriptTargetFeatures(): ScriptTargetFeatures { "hypot", "trunc", "fround", - "cbrt" - ] + "cbrt", + ], })), Map: new Map(Object.entries({ es2015: [ "entries", "keys", - "values" - ] + "values", + ], })), Set: new Map(Object.entries({ es2015: [ "entries", "keys", - "values" - ] + "values", + ], })), PromiseConstructor: new Map(Object.entries({ es2015: [ "all", "race", "reject", - "resolve" + "resolve", ], es2020: [ - "allSettled" + "allSettled", ], es2021: [ - "any" - ] + "any", + ], })), Symbol: new Map(Object.entries({ es2015: [ "for", - "keyFor" + "keyFor", ], es2019: [ - "description" - ] + "description", + ], })), WeakMap: new Map(Object.entries({ es2015: [ "entries", "keys", - "values" - ] + "values", + ], })), WeakSet: new Map(Object.entries({ es2015: [ "entries", "keys", - "values" - ] + "values", + ], })), String: new Map(Object.entries({ es2015: [ @@ -1483,193 +1487,193 @@ export function getScriptTargetFeatures(): ScriptTargetFeatures { "small", "strike", "sub", - "sup" + "sup", ], es2017: [ "padStart", - "padEnd" + "padEnd", ], es2019: [ "trimStart", "trimEnd", "trimLeft", - "trimRight" + "trimRight", ], es2020: [ - "matchAll" + "matchAll", ], es2021: [ - "replaceAll" + "replaceAll", ], es2022: [ - "at" - ] + "at", + ], })), StringConstructor: new Map(Object.entries({ es2015: [ "fromCodePoint", - "raw" - ] + "raw", + ], })), DateTimeFormat: new Map(Object.entries({ es2017: [ - "formatToParts" - ] + "formatToParts", + ], })), Promise: new Map(Object.entries({ es2015: emptyArray, es2018: [ - "finally" - ] + "finally", + ], })), RegExpMatchArray: new Map(Object.entries({ es2018: [ - "groups" - ] + "groups", + ], })), RegExpExecArray: new Map(Object.entries({ es2018: [ - "groups" - ] + "groups", + ], })), Intl: new Map(Object.entries({ es2018: [ - "PluralRules" - ] + "PluralRules", + ], })), NumberFormat: new Map(Object.entries({ es2018: [ - "formatToParts" - ] + "formatToParts", + ], })), SymbolConstructor: new Map(Object.entries({ es2020: [ - "matchAll" - ] + "matchAll", + ], })), DataView: new Map(Object.entries({ es2020: [ "setBigInt64", "setBigUint64", "getBigInt64", - "getBigUint64" - ] + "getBigUint64", + ], })), BigInt: new Map(Object.entries({ - es2020: emptyArray + es2020: emptyArray, })), RelativeTimeFormat: new Map(Object.entries({ es2020: [ "format", "formatToParts", - "resolvedOptions" - ] + "resolvedOptions", + ], })), Int8Array: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Uint8Array: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Uint8ClampedArray: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Int16Array: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Uint16Array: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Int32Array: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Uint32Array: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Float32Array: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Float64Array: new Map(Object.entries({ es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), BigInt64Array: new Map(Object.entries({ es2020: emptyArray, es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), BigUint64Array: new Map(Object.entries({ es2020: emptyArray, es2022: [ - "at" + "at", ], es2023: [ "findLastIndex", - "findLast" + "findLast", ], })), Error: new Map(Object.entries({ es2022: [ - "cause" - ] + "cause", + ], })), })); } @@ -1680,7 +1684,7 @@ export const enum GetLiteralTextFlags { NeverAsciiEscape = 1 << 0, JsxAttributeEscape = 1 << 1, TerminateUnterminatedLiterals = 1 << 2, - AllowNumericSeparator = 1 << 3 + AllowNumericSeparator = 1 << 3, } /** @internal */ @@ -1792,7 +1796,7 @@ export function isModuleWithStringLiteralName(node: Node): node is ModuleDeclara } /** @internal */ -export function isNonGlobalAmbientModule(node: Node): node is ModuleDeclaration & { name: StringLiteral } { +export function isNonGlobalAmbientModule(node: Node): node is ModuleDeclaration & { name: StringLiteral; } { return isModuleDeclaration(node) && isStringLiteral(node.name); } @@ -2166,7 +2170,7 @@ export function createFileDiagnosticFromMessageChain(file: SourceFile, start: nu code: messageChain.code, category: messageChain.category, messageText: messageChain.next ? messageChain : messageChain.messageText, - relatedInformation + relatedInformation, }; } @@ -2179,7 +2183,7 @@ export function createDiagnosticForFileFromMessageChain(sourceFile: SourceFile, code: messageChain.code, category: messageChain.category, messageText: messageChain.next ? messageChain : messageChain.messageText, - relatedInformation + relatedInformation, }; } @@ -2321,7 +2325,6 @@ export function isExternalOrCommonJsModule(file: SourceFile): boolean { return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } - /** @internal */ export function isJsonSourceFile(file: SourceFile): file is JsonSourceFile { return file.scriptKind === ScriptKind.JSON; @@ -2428,12 +2431,12 @@ export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: Sour /** @internal */ export function getJSDocCommentRanges(node: Node, text: string) { const commentRanges = (node.kind === SyntaxKind.Parameter || - node.kind === SyntaxKind.TypeParameter || - node.kind === SyntaxKind.FunctionExpression || - node.kind === SyntaxKind.ArrowFunction || - node.kind === SyntaxKind.ParenthesizedExpression || - node.kind === SyntaxKind.VariableDeclaration || - node.kind === SyntaxKind.ExportSpecifier) ? + node.kind === SyntaxKind.TypeParameter || + node.kind === SyntaxKind.FunctionExpression || + node.kind === SyntaxKind.ArrowFunction || + node.kind === SyntaxKind.ParenthesizedExpression || + node.kind === SyntaxKind.VariableDeclaration || + node.kind === SyntaxKind.ExportSpecifier) ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -2489,8 +2492,7 @@ export function isPartOfTypeNode(node: Node): boolean { node = node.parent; } // At this point, node is either a qualified name or an identifier - Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.PropertyAccessExpression, - "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.PropertyAccessExpression, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through case SyntaxKind.QualifiedName: @@ -2565,7 +2567,6 @@ export function isChildOfNodeWithKind(node: Node, kind: SyntaxKind): boolean { // in that traversal terminates in the event that 'visitor' supplies a truthy value. /** @internal */ export function forEachReturnStatement(body: Block | Statement, visitor: (stmt: ReturnStatement) => T): T | undefined { - return traverse(body); function traverse(node: Node): T | undefined { @@ -2594,7 +2595,6 @@ export function forEachReturnStatement(body: Block | Statement, visitor: (stm /** @internal */ export function forEachYieldExpression(body: Block, visitor: (expr: YieldExpression) => void): void { - return traverse(body); function traverse(node: Node): void { @@ -2784,8 +2784,7 @@ export function getPropertyArrayElementValue(objectLiteral: ObjectLiteralExpress return forEachPropertyAssignment(objectLiteral, propKey, property => isArrayLiteralExpression(property.initializer) ? find(property.initializer.elements, (element): element is StringLiteral => isStringLiteral(element) && element.text === elementValue) : - undefined - ); + undefined); } /** @internal */ @@ -2862,8 +2861,7 @@ export type ThisContainer = | ConstructSignatureDeclaration | IndexSignatureDeclaration | EnumDeclaration - | SourceFile - ; + | SourceFile; /** @internal */ export function getThisContainer(node: Node, includeArrowFunctions: false, includeClassComputedPropertyName: false): ThisContainer; @@ -3000,16 +2998,14 @@ export type SuperContainer = | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration - | ClassStaticBlockDeclaration - ; + | ClassStaticBlockDeclaration; /** @internal */ export type SuperContainerOrFunctions = | SuperContainer | FunctionDeclaration | FunctionExpression - | ArrowFunction - ; + | ArrowFunction; /** * Given an super call/property node, returns the closest node where @@ -3185,7 +3181,7 @@ export function nodeCanBeDecorated(useLegacyDecorators: boolean, node: Node, par case SyntaxKind.PropertyDeclaration: // property declarations are valid if their parent is a class declaration. return parent !== undefined - && (useLegacyDecorators ? isClassDeclaration(parent) : isClassLike(parent) && !hasAbstractModifier(node) && !hasAmbientModifier(node)); + && (useLegacyDecorators ? isClassDeclaration(parent) : isClassLike(parent) && !hasAbstractModifier(node) && !hasAmbientModifier(node)); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: @@ -3205,8 +3201,8 @@ export function nodeCanBeDecorated(useLegacyDecorators: boolean, node: Node, par || parent.kind === SyntaxKind.MethodDeclaration || parent.kind === SyntaxKind.SetAccessor) && getThisParameter(parent as FunctionLikeDeclaration) !== node - && grandparent !== undefined - && grandparent.kind === SyntaxKind.ClassDeclaration; + && grandparent !== undefined + && grandparent.kind === SyntaxKind.ClassDeclaration; } return false; @@ -3245,8 +3241,8 @@ export function childIsDecorated(useLegacyDecorators: boolean, node: Node, paren switch (node.kind) { case SyntaxKind.ClassDeclaration: return some((node as ClassDeclaration).members, m => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent!)); - case SyntaxKind.ClassExpression: - return !useLegacyDecorators && some((node as ClassExpression).members, m => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent!)); + case SyntaxKind.ClassExpression: + return !useLegacyDecorators && some((node as ClassExpression).members, m => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent!)); case SyntaxKind.MethodDeclaration: case SyntaxKind.SetAccessor: case SyntaxKind.Constructor: @@ -3268,8 +3264,7 @@ export function classElementOrClassElementParameterIsDecorated(useLegacyDecorato let parameters: NodeArray | undefined; if (isAccessor(node)) { const { firstAccessor, secondAccessor, setAccessor } = getAllAccessorDeclarations(parent.members, node); - const firstAccessorWithDecorators = - hasDecorators(firstAccessor) ? firstAccessor : + const firstAccessorWithDecorators = hasDecorators(firstAccessor) ? firstAccessor : secondAccessor && hasDecorators(secondAccessor) ? secondAccessor : undefined; if (!firstAccessorWithDecorators || node !== firstAccessorWithDecorators) { @@ -3309,9 +3304,11 @@ export function isEmptyStringLiteral(node: StringLiteral): boolean { /** @internal */ export function isJSXTagName(node: Node) { const { parent } = node; - if (parent.kind === SyntaxKind.JsxOpeningElement || + if ( + parent.kind === SyntaxKind.JsxOpeningElement || parent.kind === SyntaxKind.JsxSelfClosingElement || - parent.kind === SyntaxKind.JsxClosingElement) { + parent.kind === SyntaxKind.JsxClosingElement + ) { return (parent as JsxOpeningLikeElement).tagName === node; } return false; @@ -3457,7 +3454,7 @@ export function isNamespaceReexportDeclaration(node: Node): boolean { } /** @internal */ -export function isExternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration & { moduleReference: ExternalModuleReference } { +export function isExternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration & { moduleReference: ExternalModuleReference; } { return node.kind === SyntaxKind.ImportEqualsDeclaration && (node as ImportEqualsDeclaration).moduleReference.kind === SyntaxKind.ExternalModuleReference; } @@ -3523,7 +3520,7 @@ export function isJSDocIndexSignature(node: TypeReferenceNode | ExpressionWithTy * * @internal */ -export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: true): callExpression is RequireOrImportCall & { expression: Identifier, arguments: [StringLiteralLike] }; +export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: true): callExpression is RequireOrImportCall & { expression: Identifier; arguments: [StringLiteralLike]; }; /** @internal */ export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: boolean): callExpression is CallExpression; /** @internal */ @@ -3602,10 +3599,12 @@ export function isAssignmentDeclaration(decl: Declaration) { * @internal */ export function getEffectiveInitializer(node: HasExpressionInitializer) { - if (isInJSFile(node) && node.initializer && + if ( + isInJSFile(node) && node.initializer && isBinaryExpression(node.initializer) && - (node.initializer.operatorToken.kind === SyntaxKind.BarBarToken || node.initializer.operatorToken.kind === SyntaxKind.QuestionQuestionToken) && - node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + (node.initializer.operatorToken.kind === SyntaxKind.BarBarToken || node.initializer.operatorToken.kind === SyntaxKind.QuestionQuestionToken) && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left) + ) { return node.initializer.right; } return node.initializer; @@ -3667,9 +3666,11 @@ export function getExpandoInitializer(initializer: Node, isPrototypeAssignment: const e = skipParentheses(initializer.expression); return e.kind === SyntaxKind.FunctionExpression || e.kind === SyntaxKind.ArrowFunction ? initializer : undefined; } - if (initializer.kind === SyntaxKind.FunctionExpression || + if ( + initializer.kind === SyntaxKind.FunctionExpression || initializer.kind === SyntaxKind.ClassExpression || - initializer.kind === SyntaxKind.ArrowFunction) { + initializer.kind === SyntaxKind.ArrowFunction + ) { return initializer as Expression; } if (isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -3734,12 +3735,14 @@ export function isSameEntityName(name: Expression, initializer: Expression): boo if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) { return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer); } - if (isMemberName(name) && isLiteralLikeAccess(initializer) && + if ( + isMemberName(name) && isLiteralLikeAccess(initializer) && (initializer.expression.kind === SyntaxKind.ThisKeyword || isIdentifier(initializer.expression) && - (initializer.expression.escapedText === "window" || - initializer.expression.escapedText === "self" || - initializer.expression.escapedText === "global"))) { + (initializer.expression.escapedText === "window" || + initializer.expression.escapedText === "self" || + initializer.expression.escapedText === "global")) + ) { return isSameEntityName(name, getNameOrArgument(initializer)); } if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) { @@ -3768,7 +3771,7 @@ export function isModuleIdentifier(node: Node) { } /** @internal */ -export function isModuleExportsAccessExpression(node: Node): node is LiteralLikeElementAccessExpression & { expression: Identifier } { +export function isModuleExportsAccessExpression(node: Node): node is LiteralLikeElementAccessExpression & { expression: Identifier; } { return (isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; @@ -3929,10 +3932,12 @@ export function getAssignmentDeclarationPropertyAccessKind(lhs: AccessExpression nextToLast = nextToLast.expression as Exclude; } const id = nextToLast.expression; - if ((id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + if ( + (id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && // ExportsProperty does not support binding with computed names - isBindableStaticAccessExpression(lhs)) { + isBindableStaticAccessExpression(lhs) + ) { // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return AssignmentDeclarationKind.ExportsProperty; } @@ -3975,10 +3980,12 @@ export function isSpecialPropertyDeclaration(expr: PropertyAccessExpression | El /** @internal */ export function setValueDeclaration(symbol: Symbol, node: Declaration): void { const { valueDeclaration } = symbol; - if (!valueDeclaration || + if ( + !valueDeclaration || !(node.flags & NodeFlags.Ambient && !isInJSFile(node) && !(valueDeclaration.flags & NodeFlags.Ambient)) && - (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration)) + ) { // other kinds of value declarations take precedence over modules and assignment declarations symbol.valueDeclaration = node; } @@ -4128,18 +4135,18 @@ export function isTypeAlias(node: Node): node is JSDocTypedefTag | JSDocCallback function getSourceOfAssignment(node: Node): Node | undefined { return isExpressionStatement(node) && - isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === SyntaxKind.EqualsToken + isBinaryExpression(node.expression) && + node.expression.operatorToken.kind === SyntaxKind.EqualsToken ? getRightMostAssignedExpression(node.expression) : undefined; } function getSourceOfDefaultedAssignment(node: Node): Node | undefined { return isExpressionStatement(node) && - isBinaryExpression(node.expression) && - getAssignmentDeclarationKind(node.expression) !== AssignmentDeclarationKind.None && - isBinaryExpression(node.expression.right) && - (node.expression.right.operatorToken.kind === SyntaxKind.BarBarToken || node.expression.right.operatorToken.kind === SyntaxKind.QuestionQuestionToken) + isBinaryExpression(node.expression) && + getAssignmentDeclarationKind(node.expression) !== AssignmentDeclarationKind.None && + isBinaryExpression(node.expression.right) && + (node.expression.right.operatorToken.kind === SyntaxKind.BarBarToken || node.expression.right.operatorToken.kind === SyntaxKind.QuestionQuestionToken) ? node.expression.right.right : undefined; } @@ -4164,8 +4171,8 @@ export function getSingleVariableOfVariableStatement(node: Node): VariableDeclar function getNestedModuleDeclaration(node: Node): Node | undefined { return isModuleDeclaration(node) && - node.body && - node.body.kind === SyntaxKind.ModuleDeclaration + node.body && + node.body.kind === SyntaxKind.ModuleDeclaration ? node.body : undefined; } @@ -4343,13 +4350,15 @@ function ownsJSDocTag(hostNode: Node, tag: JSDocTag) { /** @internal */ export function getNextJSDocCommentLocation(node: Node) { const parent = node.parent; - if (parent.kind === SyntaxKind.PropertyAssignment || + if ( + parent.kind === SyntaxKind.PropertyAssignment || parent.kind === SyntaxKind.ExportAssignment || parent.kind === SyntaxKind.PropertyDeclaration || parent.kind === SyntaxKind.ExpressionStatement && node.kind === SyntaxKind.PropertyAccessExpression || parent.kind === SyntaxKind.ReturnStatement || getNestedModuleDeclaration(parent) || - isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.EqualsToken) { + isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.EqualsToken + ) { return parent; } // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. @@ -4358,15 +4367,19 @@ export function getNextJSDocCommentLocation(node: Node) { // * @returns {number} // */ // var x = function(name) { return name.length; } - else if (parent.parent && + else if ( + parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node || - isBinaryExpression(parent) && parent.operatorToken.kind === SyntaxKind.EqualsToken)) { + isBinaryExpression(parent) && parent.operatorToken.kind === SyntaxKind.EqualsToken) + ) { return parent.parent; } - else if (parent.parent && parent.parent.parent && + else if ( + parent.parent && parent.parent.parent && (getSingleVariableOfVariableStatement(parent.parent.parent) || - getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || - getSourceOfDefaultedAssignment(parent.parent.parent))) { + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent)) + ) { return parent.parent.parent; } } @@ -4451,9 +4464,9 @@ export function getJSDocRoot(node: Node): JSDoc | undefined { } /** @internal */ -export function getTypeParameterFromJsDoc(node: TypeParameterDeclaration & { parent: JSDocTemplateTag }): TypeParameterDeclaration | undefined { +export function getTypeParameterFromJsDoc(node: TypeParameterDeclaration & { parent: JSDocTemplateTag; }): TypeParameterDeclaration | undefined { const name = node.name.escapedText; - const { typeParameters } = (node.parent.parent.parent as SignatureDeclaration | InterfaceDeclaration | ClassDeclaration); + const { typeParameters } = node.parent.parent.parent as SignatureDeclaration | InterfaceDeclaration | ClassDeclaration; return typeParameters && find(typeParameters, p => p.name.escapedText === name); } @@ -4464,7 +4477,9 @@ export function hasTypeArguments(node: Node): node is HasTypeArguments { /** @internal */ export const enum AssignmentKind { - None, Definite, Compound + None, + Definite, + Compound, } type AssignmentTarget = @@ -4483,7 +4498,7 @@ function getAssignmentTarget(node: Node): AssignmentTarget | undefined { return isAssignmentOperator(binaryOperator) && binaryExpression.left === node ? binaryExpression : undefined; case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: - const unaryExpression = (parent as PrefixUnaryExpression | PostfixUnaryExpression); + const unaryExpression = parent as PrefixUnaryExpression | PostfixUnaryExpression; const unaryOperator = unaryExpression.operator; return unaryOperator === SyntaxKind.PlusPlusToken || unaryOperator === SyntaxKind.MinusMinusToken ? unaryExpression : undefined; case SyntaxKind.ForInStatement: @@ -4717,9 +4732,9 @@ export function getDeclarationFromName(name: Node): Declaration | undefined { else { const binExp = parent.parent; return isBinaryExpression(binExp) && - getAssignmentDeclarationKind(binExp) !== AssignmentDeclarationKind.None && - ((binExp.left as BindableStaticNameExpression).symbol || binExp.symbol) && - getNameOfDeclaration(binExp) === name + getAssignmentDeclarationKind(binExp) !== AssignmentDeclarationKind.None && + ((binExp.left as BindableStaticNameExpression).symbol || binExp.symbol) && + getNameOfDeclaration(binExp) === name ? binExp : undefined; } @@ -4788,7 +4803,8 @@ export function isIdentifierName(node: Identifier): boolean { // const { x } = require("...").y /** @internal */ export function isAliasSymbolDeclaration(node: Node): boolean { - if (node.kind === SyntaxKind.ImportEqualsDeclaration || + if ( + node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.NamespaceExportDeclaration || node.kind === SyntaxKind.ImportClause && !!(node as ImportClause).name || node.kind === SyntaxKind.NamespaceImport || @@ -4806,7 +4822,8 @@ export function isAliasSymbolDeclaration(node: Node): boolean { && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === SyntaxKind.EqualsToken - && isAliasableExpression(node.parent.right)); + && isAliasableExpression(node.parent.right) + ); } /** @internal */ @@ -4823,7 +4840,8 @@ export function getAliasDeclarationFromName(node: EntityName): Declaration | und case SyntaxKind.QualifiedName: do { node = node.parent as QualifiedName; - } while (node.parent.kind === SyntaxKind.QualifiedName); + } + while (node.parent.kind === SyntaxKind.QualifiedName); return getAliasDeclarationFromName(node); } } @@ -4870,7 +4888,7 @@ export function getClassExtendsHeritageElement(node: ClassLikeDeclaration | Inte } /** @internal */ -export function getEffectiveImplementsTypeNodes(node: ClassLikeDeclaration): undefined | readonly ExpressionWithTypeArguments[]{ +export function getEffectiveImplementsTypeNodes(node: ClassLikeDeclaration): undefined | readonly ExpressionWithTypeArguments[] { if (isInJSFile(node)) { return getJSDocImplementsTags(node).map(n => n.class); } @@ -4974,6 +4992,7 @@ export function isTrivia(token: SyntaxKind): token is TriviaSyntaxKind { return SyntaxKind.FirstTriviaToken <= token && token <= SyntaxKind.LastTriviaToken; } +// dprint-ignore /** @internal */ export const enum FunctionFlags { Normal = 0, // Function is a normal function @@ -5033,7 +5052,7 @@ export function isStringOrNumericLiteralLike(node: Node): node is StringLiteralL } /** @internal */ -export function isSignedNumericLiteral(node: Node): node is PrefixUnaryExpression & { operand: NumericLiteral } { +export function isSignedNumericLiteral(node: Node): node is PrefixUnaryExpression & { operand: NumericLiteral; } { return isPrefixUnaryExpression(node) && (node.operator === SyntaxKind.PlusToken || node.operator === SyntaxKind.MinusToken) && isNumericLiteral(node.operand); } @@ -5156,10 +5175,9 @@ export function isProtoSetter(node: PropertyName) { /** @internal */ export type AnonymousFunctionDefinition = - | ClassExpression & { readonly name?: undefined } - | FunctionExpression & { readonly name?: undefined } - | ArrowFunction - ; + | ClassExpression & { readonly name?: undefined; } + | FunctionExpression & { readonly name?: undefined; } + | ArrowFunction; /** * Indicates whether an expression is an anonymous function definition. @@ -5190,15 +5208,14 @@ export function isAnonymousFunctionDefinition(node: Expression, cb?: (node: Anon /** @internal */ export type NamedEvaluationSource = - | PropertyAssignment & { readonly name: Identifier } - | ShorthandPropertyAssignment & { readonly objectAssignmentInitializer: Expression } - | VariableDeclaration & { readonly name: Identifier, readonly initializer: Expression } - | ParameterDeclaration & { readonly name: Identifier, readonly initializer: Expression, readonly dotDotDotToken: undefined } - | BindingElement & { readonly name: Identifier, readonly initializer: Expression, readonly dotDotDotToken: undefined } - | PropertyDeclaration & { readonly initializer: Expression } - | AssignmentExpression & { readonly left: Identifier } - | ExportAssignment - ; + | PropertyAssignment & { readonly name: Identifier; } + | ShorthandPropertyAssignment & { readonly objectAssignmentInitializer: Expression; } + | VariableDeclaration & { readonly name: Identifier; readonly initializer: Expression; } + | ParameterDeclaration & { readonly name: Identifier; readonly initializer: Expression; readonly dotDotDotToken: undefined; } + | BindingElement & { readonly name: Identifier; readonly initializer: Expression; readonly dotDotDotToken: undefined; } + | PropertyDeclaration & { readonly initializer: Expression; } + | AssignmentExpression & { readonly left: Identifier; } + | ExportAssignment; /** * Indicates whether a node is a potential source of an assigned name for a class, function, or arrow function. @@ -5236,16 +5253,15 @@ export function isNamedEvaluationSource(node: Node): node is NamedEvaluationSour /** @internal */ export type NamedEvaluation = - | PropertyAssignment & { readonly name: Identifier, readonly initializer: WrappedExpression } - | ShorthandPropertyAssignment & { readonly objectAssignmentInitializer: WrappedExpression } - | VariableDeclaration & { readonly name: Identifier, readonly initializer: WrappedExpression } - | ParameterDeclaration & { readonly name: Identifier, readonly dotDotDotToken: undefined, readonly initializer: WrappedExpression } - | BindingElement & { readonly name: Identifier, readonly dotDotDotToken: undefined, readonly initializer: WrappedExpression } - | PropertyDeclaration & { readonly initializer: WrappedExpression } - | AssignmentExpression & { readonly left: Identifier, readonly right: WrappedExpression } - | AssignmentExpression & { readonly left: Identifier, readonly right: WrappedExpression } - | ExportAssignment & { readonly expression: WrappedExpression } - ; + | PropertyAssignment & { readonly name: Identifier; readonly initializer: WrappedExpression; } + | ShorthandPropertyAssignment & { readonly objectAssignmentInitializer: WrappedExpression; } + | VariableDeclaration & { readonly name: Identifier; readonly initializer: WrappedExpression; } + | ParameterDeclaration & { readonly name: Identifier; readonly dotDotDotToken: undefined; readonly initializer: WrappedExpression; } + | BindingElement & { readonly name: Identifier; readonly dotDotDotToken: undefined; readonly initializer: WrappedExpression; } + | PropertyDeclaration & { readonly initializer: WrappedExpression; } + | AssignmentExpression & { readonly left: Identifier; readonly right: WrappedExpression; } + | AssignmentExpression & { readonly left: Identifier; readonly right: WrappedExpression; } + | ExportAssignment & { readonly expression: WrappedExpression; }; /** @internal */ export function isNamedEvaluation(node: Node, cb?: (node: AnonymousFunctionDefinition) => boolean): node is NamedEvaluation { @@ -5326,7 +5342,7 @@ export function getOriginalSourceFile(sourceFile: SourceFile) { /** @internal */ export const enum Associativity { Left, - Right + Right, } /** @internal */ @@ -5533,7 +5549,6 @@ export const enum OperatorPrecedence { // `--` UnaryExpression Unary, - // UpdateExpression: // LeftHandSideExpression // LeftHandSideExpression `++` @@ -5863,7 +5878,7 @@ const escapedCharsMap = new Map(Object.entries({ "\r": "\\r", "\n": "\\n", "\\": "\\\\", - "\"": "\\\"", + '"': '\\"', "'": "\\'", "`": "\\`", "\u2028": "\\u2028", // lineSeparator @@ -5899,8 +5914,7 @@ function getReplacement(c: string, offset: number, input: string) { * @internal */ export function escapeString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote | CharacterCodes.backtick): string { - const escapedCharsRegExp = - quoteChar === CharacterCodes.backtick ? backtickQuoteEscapedCharsRegExp : + const escapedCharsRegExp = quoteChar === CharacterCodes.backtick ? backtickQuoteEscapedCharsRegExp : quoteChar === CharacterCodes.singleQuote ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement); @@ -5924,8 +5938,8 @@ export function escapeNonAsciiString(s: string, quoteChar?: CharacterCodes.doubl const jsxDoubleQuoteEscapedCharsRegExp = /["\u0000-\u001f\u2028\u2029\u0085]/g; const jsxSingleQuoteEscapedCharsRegExp = /['\u0000-\u001f\u2028\u2029\u0085]/g; const jsxEscapedCharsMap = new Map(Object.entries({ - "\"": """, - "'": "'" + '"': """, + "'": "'", })); function encodeJsxCharacterEntity(charCode: number): string { @@ -5942,8 +5956,7 @@ function getJsxAttributeStringReplacement(c: string) { /** @internal */ export function escapeJsxAttributeString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote) { - const escapedCharsRegExp = - quoteChar === CharacterCodes.singleQuote ? jsxSingleQuoteEscapedCharsRegExp : + const escapedCharsRegExp = quoteChar === CharacterCodes.singleQuote ? jsxSingleQuoteEscapedCharsRegExp : jsxDoubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement); } @@ -5972,7 +5985,7 @@ function isQuoteOrBacktick(charCode: number) { /** @internal */ export function isIntrinsicJsxName(name: __String | string) { const ch = (name as string).charCodeAt(0); - return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || stringContains((name as string), "-"); + return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || stringContains(name as string, "-"); } const indentStrings: string[] = ["", " "]; @@ -6086,8 +6099,12 @@ export function createTextWriter(newLine: string): EmitTextWriter { rawWrite, writeLiteral, writeLine, - increaseIndent: () => { indent++; }, - decreaseIndent: () => { indent--; }, + increaseIndent: () => { + indent++; + }, + decreaseIndent: () => { + indent--; + }, getIndent: () => indent, getTextPos: () => output.length, getLine: () => lineCount, @@ -6107,7 +6124,7 @@ export function createTextWriter(newLine: string): EmitTextWriter { writeSymbol: (s, _) => write(s), writeTrailingSemicolon: write, writeComment, - getTextPosWithWriteLine + getTextPosWithWriteLine, }; } @@ -6216,8 +6233,10 @@ export function getExternalModuleNameFromDeclaration(host: ResolveModuleNameReso } // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it const specifier = getExternalModuleName(declaration); - if (specifier && isStringLiteralLike(specifier) && !pathIsRelative(specifier.text) && - getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) { + if ( + specifier && isStringLiteralLike(specifier) && !pathIsRelative(specifier.text) && + getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1 + ) { return undefined; } return getResolvedExternalModuleName(host, file); @@ -6282,7 +6301,7 @@ export function getDeclarationEmitExtensionForPath(path: string) { */ export function getPossibleOriginalInputExtensionForExtension(path: string) { return fileExtensionIsOneOf(path, [Extension.Dmts, Extension.Mjs, Extension.Mts]) ? [Extension.Mts, Extension.Mjs] : - fileExtensionIsOneOf(path, [Extension.Dcts, Extension.Cjs, Extension.Cts]) ? [Extension.Cts, Extension.Cjs]: + fileExtensionIsOneOf(path, [Extension.Dcts, Extension.Cjs, Extension.Cts]) ? [Extension.Cts, Extension.Cjs] : fileExtensionIsOneOf(path, [`.d.json.ts`]) ? [Extension.Json] : [Extension.Tsx, Extension.Ts, Extension.Jsx, Extension.Js]; } @@ -6297,7 +6316,7 @@ export function outFile(options: CompilerOptions) { * * @internal */ -export function getPathsBasePath(options: CompilerOptions, host: { getCurrentDirectory?(): string }) { +export function getPathsBasePath(options: CompilerOptions, host: { getCurrentDirectory?(): string; }) { if (!options.paths) return undefined; return options.baseUrl ?? Debug.checkDefined(options.pathsBasePath || host.getCurrentDirectory?.(), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); } @@ -6332,14 +6351,14 @@ export function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFi host.getSourceFiles(), sourceFile => (moduleEmitEnabled || !isExternalModule(sourceFile)) && - sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) + sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit), ); } else { const sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; return filter( sourceFiles, - sourceFile => sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) + sourceFile => sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit), ); } } @@ -6375,15 +6394,23 @@ export function getSourceFilePathInNewDirWorker(fileName: string, newDirPath: st /** @internal */ export function writeFile(host: { writeFile: WriteFileCallback; }, diagnostics: DiagnosticCollection, fileName: string, text: string, writeByteOrderMark: boolean, sourceFiles?: readonly SourceFile[], data?: WriteFileCallbackData) { - host.writeFile(fileName, text, writeByteOrderMark, hostErrorMessage => { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); - }, sourceFiles, data); + host.writeFile( + fileName, + text, + writeByteOrderMark, + hostErrorMessage => { + diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, + sourceFiles, + data, + ); } function ensureDirectoriesExist( directoryPath: string, createDirectory: (path: string) => void, - directoryExists: (path: string) => boolean): void { + directoryExists: (path: string) => boolean, +): void { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { const parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists); @@ -6398,8 +6425,8 @@ export function writeFileEnsuringDirectories( writeByteOrderMark: boolean, writeFile: (path: string, data: string, writeByteOrderMark: boolean) => void, createDirectory: (path: string) => void, - directoryExists: (path: string) => boolean): void { - + directoryExists: (path: string) => boolean, +): void { // PERF: Checking for directory existence is expensive. Instead, assume the directory exists // and fall back to creating it if the file write fails. try { @@ -6423,8 +6450,8 @@ export function getLineOfLocalPositionFromLineMap(lineMap: readonly number[], po } /** @internal */ -export function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration & { body: FunctionBody } | undefined { - return find(node.members, (member): member is ConstructorDeclaration & { body: FunctionBody } => isConstructorDeclaration(member) && nodeIsPresent(member.body)); +export function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration & { body: FunctionBody; } | undefined { + return find(node.members, (member): member is ConstructorDeclaration & { body: FunctionBody; } => isConstructorDeclaration(member) && nodeIsPresent(member.body)); } /** @internal */ @@ -6473,7 +6500,8 @@ export function isInTypeQuery(node: Node): boolean { // The expression is restricted to a single identifier or a sequence of identifiers separated by periods return !!findAncestor( node, - n => n.kind === SyntaxKind.TypeQuery ? true : n.kind === SyntaxKind.Identifier || n.kind === SyntaxKind.QualifiedName ? false : "quit"); + n => n.kind === SyntaxKind.TypeQuery ? true : n.kind === SyntaxKind.Identifier || n.kind === SyntaxKind.QualifiedName ? false : "quit", + ); } /** @internal */ @@ -6515,8 +6543,10 @@ export function getAllAccessorDeclarations(declarations: readonly Declaration[], } else { forEach(declarations, member => { - if (isAccessor(member) - && isStatic(member) === isStatic(accessor)) { + if ( + isAccessor(member) + && isStatic(member) === isStatic(accessor) + ) { const memberName = getPropertyNameForPropertyNameNode(member.name); const accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -6542,7 +6572,7 @@ export function getAllAccessorDeclarations(declarations: readonly Declaration[], firstAccessor, secondAccessor, getAccessor, - setAccessor + setAccessor, }; } @@ -6606,8 +6636,10 @@ export function emitNewLineBeforeLeadingComments(lineMap: readonly number[], wri /** @internal */ export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: readonly number[], writer: EmitTextWriter, pos: number, leadingComments: readonly CommentRange[] | undefined) { // If the leading comments start on different line than the start of node, write new line - if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && - getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + if ( + leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos) + ) { writer.writeLine(); } } @@ -6615,8 +6647,10 @@ export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: readonly num /** @internal */ export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: readonly number[], writer: EmitTextWriter, pos: number, commentPos: number) { // If the leading comments start on different line than the start of node, write new line - if (pos !== commentPos && - getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + if ( + pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos) + ) { writer.writeLine(); } } @@ -6630,7 +6664,8 @@ export function emitComments( leadingSeparator: boolean, trailingSeparator: boolean, newLine: string, - writeComment: (text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void) { + writeComment: (text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, +) { if (comments && comments.length > 0) { if (leadingSeparator) { writer.writeSpace(" "); @@ -6664,11 +6699,9 @@ export function emitComments( * * @internal */ -export function emitDetachedComments(text: string, lineMap: readonly number[], writer: EmitTextWriter, - writeComment: (text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, - node: TextRange, newLine: string, removeComments: boolean) { +export function emitDetachedComments(text: string, lineMap: readonly number[], writer: EmitTextWriter, writeComment: (text: string, lineMap: readonly number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean) { let leadingComments: CommentRange[] | undefined; - let currentDetachedCommentInfo: { nodePos: number, detachedCommentEndPos: number } | undefined; + let currentDetachedCommentInfo: { nodePos: number; detachedCommentEndPos: number; } | undefined; if (removeComments) { // removeComments is true, only reserve pinned comment at the top of file // For example: @@ -6725,7 +6758,6 @@ export function emitDetachedComments(text: string, lineMap: readonly number[], w function isPinnedCommentLocal(comment: CommentRange) { return isPinnedComment(text, comment.pos); } - } /** @internal */ @@ -6996,22 +7028,38 @@ export function modifiersToFlags(modifiers: readonly ModifierLike[] | undefined) /** @internal */ export function modifierToFlag(token: SyntaxKind): ModifierFlags { switch (token) { - case SyntaxKind.StaticKeyword: return ModifierFlags.Static; - case SyntaxKind.PublicKeyword: return ModifierFlags.Public; - case SyntaxKind.ProtectedKeyword: return ModifierFlags.Protected; - case SyntaxKind.PrivateKeyword: return ModifierFlags.Private; - case SyntaxKind.AbstractKeyword: return ModifierFlags.Abstract; - case SyntaxKind.AccessorKeyword: return ModifierFlags.Accessor; - case SyntaxKind.ExportKeyword: return ModifierFlags.Export; - case SyntaxKind.DeclareKeyword: return ModifierFlags.Ambient; - case SyntaxKind.ConstKeyword: return ModifierFlags.Const; - case SyntaxKind.DefaultKeyword: return ModifierFlags.Default; - case SyntaxKind.AsyncKeyword: return ModifierFlags.Async; - case SyntaxKind.ReadonlyKeyword: return ModifierFlags.Readonly; - case SyntaxKind.OverrideKeyword: return ModifierFlags.Override; - case SyntaxKind.InKeyword: return ModifierFlags.In; - case SyntaxKind.OutKeyword: return ModifierFlags.Out; - case SyntaxKind.Decorator: return ModifierFlags.Decorator; + case SyntaxKind.StaticKeyword: + return ModifierFlags.Static; + case SyntaxKind.PublicKeyword: + return ModifierFlags.Public; + case SyntaxKind.ProtectedKeyword: + return ModifierFlags.Protected; + case SyntaxKind.PrivateKeyword: + return ModifierFlags.Private; + case SyntaxKind.AbstractKeyword: + return ModifierFlags.Abstract; + case SyntaxKind.AccessorKeyword: + return ModifierFlags.Accessor; + case SyntaxKind.ExportKeyword: + return ModifierFlags.Export; + case SyntaxKind.DeclareKeyword: + return ModifierFlags.Ambient; + case SyntaxKind.ConstKeyword: + return ModifierFlags.Const; + case SyntaxKind.DefaultKeyword: + return ModifierFlags.Default; + case SyntaxKind.AsyncKeyword: + return ModifierFlags.Async; + case SyntaxKind.ReadonlyKeyword: + return ModifierFlags.Readonly; + case SyntaxKind.OverrideKeyword: + return ModifierFlags.Override; + case SyntaxKind.InKeyword: + return ModifierFlags.In; + case SyntaxKind.OutKeyword: + return ModifierFlags.Out; + case SyntaxKind.Decorator: + return ModifierFlags.Decorator; } return ModifierFlags.None; } @@ -7129,12 +7177,14 @@ export function getFirstIdentifier(node: EntityNameOrEntityNameExpression): Iden case SyntaxKind.QualifiedName: do { node = node.left; - } while (node.kind !== SyntaxKind.Identifier); + } + while (node.kind !== SyntaxKind.Identifier); return node; case SyntaxKind.PropertyAccessExpression: do { node = node.expression; - } while (node.kind !== SyntaxKind.Identifier); + } + while (node.kind !== SyntaxKind.Identifier); return node; } } @@ -7347,7 +7397,7 @@ function getStringFromExpandedCharCodes(codes: number[]): string { } /** @internal */ -export function base64encode(host: { base64encode?(input: string): string } | undefined, input: string): string { +export function base64encode(host: { base64encode?(input: string): string; } | undefined, input: string): string { if (host && host.base64encode) { return host.base64encode(input); } @@ -7355,7 +7405,7 @@ export function base64encode(host: { base64encode?(input: string): string } | un } /** @internal */ -export function base64decode(host: { base64decode?(input: string): string } | undefined, input: string): string { +export function base64decode(host: { base64decode?(input: string): string; } | undefined, input: string): string { if (host && host.base64decode) { return host.base64decode(input); } @@ -7392,7 +7442,7 @@ export function base64decode(host: { base64decode?(input: string): string } | un } /** @internal */ -export function readJsonOrUndefined(path: string, hostOrText: { readFile(fileName: string): string | undefined } | string): object | undefined { +export function readJsonOrUndefined(path: string, hostOrText: { readFile(fileName: string): string | undefined; } | string): object | undefined { const jsonText = isString(hostOrText) ? hostOrText : hostOrText.readFile(path); if (!jsonText) return undefined; // gracefully handle if readFile fails or returns not JSON @@ -7401,12 +7451,12 @@ export function readJsonOrUndefined(path: string, hostOrText: { readFile(fileNam } /** @internal */ -export function readJson(path: string, host: { readFile(fileName: string): string | undefined }): object { +export function readJson(path: string, host: { readFile(fileName: string): string | undefined; }): object { return readJsonOrUndefined(path, host) || {}; } /** @internal */ -export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean { +export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean; }): boolean { // if host does not support 'directoryExists' assume that directory will exist return !host.directoryExists || host.directoryExists(directoryName); } @@ -7420,7 +7470,7 @@ export function getNewLineCharacter(options: CompilerOptions | PrinterOptions): return carriageReturnLineFeed; case NewLineKind.LineFeed: case undefined: - return lineFeed; + return lineFeed; } } @@ -7522,7 +7572,8 @@ export function rangeStartPositionsAreOnSameLine(range1: TextRange, range2: Text return positionsAreOnSameLine( getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), - sourceFile); + sourceFile, + ); } /** @internal */ @@ -7684,7 +7735,7 @@ const enum AccessKind { /** Only writes to a variable without ever reading it. E.g.: `x=1;`. */ Write, /** Reads from and writes to a variable. E.g.: `f(x++);`, `x/=1`. */ - ReadWrite + ReadWrite, } function accessKind(node: Node): AccessKind { const { parent } = node; @@ -7783,7 +7834,7 @@ export interface MutateMapSkippingNewValuesOptions { export function mutateMapSkippingNewValues( map: Map, newMap: ReadonlyMap, - options: MutateMapSkippingNewValuesOptions + options: MutateMapSkippingNewValuesOptions, ) { const { onDeleteValue, onExistingValue } = options; // Needs update @@ -7862,19 +7913,17 @@ export function showModuleSpecifier({ moduleSpecifier }: ImportDeclaration): str /** @internal */ export function getLastChild(node: Node): Node | undefined { let lastChild: Node | undefined; - forEachChild(node, - child => { - if (nodeIsPresent(child)) lastChild = child; - }, - children => { - // As an optimization, jump straight to the end of the list. - for (let i = children.length - 1; i >= 0; i--) { - if (nodeIsPresent(children[i])) { - lastChild = children[i]; - break; - } + forEachChild(node, child => { + if (nodeIsPresent(child)) lastChild = child; + }, children => { + // As an optimization, jump straight to the end of the list. + for (let i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; } - }); + } + }); return lastChild; } @@ -8001,8 +8050,6 @@ export function forEachNameInAccessChainWalkingLeft(name: MemberName | String } } - - /** @internal */ export function getLeftmostExpression(node: Expression, stopAtCallExpressions: boolean) { while (true) { @@ -8230,7 +8277,7 @@ function attachFileToDiagnostic(diagnostic: DiagnosticWithDetachedLocation, file messageText: diagnostic.messageText, category: diagnostic.category, code: diagnostic.code, - reportsUnnecessary: diagnostic.reportsUnnecessary + reportsUnnecessary: diagnostic.reportsUnnecessary, }; if (diagnostic.relatedInformation) { diagnosticWithLocation.relatedInformation = []; @@ -8276,7 +8323,7 @@ export function createFileDiagnostic(file: SourceFile, start: number, length: nu category: message.category, code: message.code, reportsUnnecessary: message.reportsUnnecessary, - reportsDeprecated: message.reportsDeprecated + reportsDeprecated: message.reportsDeprecated, }; } @@ -8308,7 +8355,7 @@ export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: Di category: message.category, code: message.code, reportsUnnecessary: message.reportsUnnecessary, - reportsDeprecated: message.reportsDeprecated + reportsDeprecated: message.reportsDeprecated, }; } @@ -8322,7 +8369,7 @@ export function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessag code: chain.code, category: chain.category, messageText: chain.next ? chain : chain.messageText, - relatedInformation + relatedInformation, }; } @@ -8338,7 +8385,7 @@ export function chainDiagnosticMessages(details: DiagnosticMessageChain | Diagno category: message.category, code: message.code, - next: details === undefined || Array.isArray(details) ? details : [details] + next: details === undefined || Array.isArray(details) ? details : [details], }; } @@ -8488,15 +8535,15 @@ export function getSetExternalModuleIndicator(options: CompilerOptions): (file: } /** @internal */ -export function getEmitScriptTarget(compilerOptions: {module?: CompilerOptions["module"], target?: CompilerOptions["target"]}): ScriptTarget { +export function getEmitScriptTarget(compilerOptions: { module?: CompilerOptions["module"]; target?: CompilerOptions["target"]; }): ScriptTarget { return compilerOptions.target ?? ((compilerOptions.module === ModuleKind.Node16 && ScriptTarget.ES2022) || - (compilerOptions.module === ModuleKind.NodeNext && ScriptTarget.ESNext) || - ScriptTarget.ES5); + (compilerOptions.module === ModuleKind.NodeNext && ScriptTarget.ESNext) || + ScriptTarget.ES5); } /** @internal */ -export function getEmitModuleKind(compilerOptions: {module?: CompilerOptions["module"], target?: CompilerOptions["target"]}) { +export function getEmitModuleKind(compilerOptions: { module?: CompilerOptions["module"]; target?: CompilerOptions["target"]; }) { return typeof compilerOptions.module === "number" ? compilerOptions.module : getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015 ? ModuleKind.ES2015 : ModuleKind.CommonJS; @@ -8680,8 +8727,7 @@ export type StrictOptionName = | "strictBindCallApply" | "strictPropertyInitialization" | "alwaysStrict" - | "useUnknownInCatchVariables" - ; + | "useUnknownInCatchVariables"; /** @internal */ export function getStrictOptionValue(compilerOptions: CompilerOptions, flag: StrictOptionName): boolean { @@ -8734,11 +8780,11 @@ export function getJSXImplicitImportBase(compilerOptions: CompilerOptions, file? const jsxImportSourcePragmas = file?.pragmas.get("jsximportsource"); const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; return compilerOptions.jsx === JsxEmit.ReactJSX || - compilerOptions.jsx === JsxEmit.ReactJSXDev || - compilerOptions.jsxImportSource || - jsxImportSourcePragma ? - jsxImportSourcePragma?.arguments.factory || compilerOptions.jsxImportSource || "react" : - undefined; + compilerOptions.jsx === JsxEmit.ReactJSXDev || + compilerOptions.jsxImportSource || + jsxImportSourcePragma ? + jsxImportSourcePragma?.arguments.factory || compilerOptions.jsxImportSource || "react" : + undefined; } /** @internal */ @@ -8839,7 +8885,8 @@ export function createSymlinkCache(cwd: string, getCanonicalFileName: GetCanonic if (commonResolved && commonOriginal) { cache.setSymlinkedDirectory( commonOriginal, - { real: commonResolved, realPath: toPath(commonResolved, cwd, getCanonicalFileName) }); + { real: commonResolved, realPath: toPath(commonResolved, cwd, getCanonicalFileName) }, + ); } } } @@ -8917,7 +8964,7 @@ const filesMatcher: WildcardMatcher = { * files or directories, does not match subdirectories that start with a . character */ doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`, - replaceWildcardCharacter: match => replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment) + replaceWildcardCharacter: match => replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment), }; const directoriesMatcher: WildcardMatcher = { @@ -8927,19 +8974,19 @@ const directoriesMatcher: WildcardMatcher = { * files or directories, does not match subdirectories that start with a . character */ doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`, - replaceWildcardCharacter: match => replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment) + replaceWildcardCharacter: match => replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment), }; const excludeMatcher: WildcardMatcher = { singleAsteriskRegexFragment: "[^/]*", doubleAsteriskRegexFragment: "(/.+?)?", - replaceWildcardCharacter: match => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment) + replaceWildcardCharacter: match => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment), }; const wildcardMatchers = { files: filesMatcher, directories: directoriesMatcher, - exclude: excludeMatcher + exclude: excludeMatcher, }; /** @internal */ @@ -8961,8 +9008,7 @@ export function getRegularExpressionsForWildcards(specs: readonly string[] | und return undefined; } - return flatMap(specs, spec => - spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage])); + return flatMap(specs, spec => spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage])); } /** @@ -9093,7 +9139,7 @@ export function getFileMatcherPatterns(path: string, excludes: readonly string[] includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames), }; } @@ -9160,8 +9206,10 @@ export function matchFiles(path: string, extensions: readonly string[] | undefin for (const current of sort(directories, compareStringsCaseSensitive)) { const name = combinePaths(path, current); const absoluteName = combinePaths(absolutePath, current); - if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && - (!excludeRegex || !excludeRegex.test(absoluteName))) { + if ( + (!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName)) + ) { visitDirectory(name, absoluteName, depth); } } @@ -9286,7 +9334,7 @@ export function getSupportedExtensions(options?: CompilerOptions, extraFileExten const flatBuiltins = flatten(builtins); const extensions = [ ...builtins, - ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) && flatBuiltins.indexOf(x.extension as Extension) === -1 ? [x.extension] : undefined) + ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) && flatBuiltins.indexOf(x.extension as Extension) === -1 ? [x.extension] : undefined), ]; return extensions; @@ -9331,9 +9379,10 @@ export const enum ModuleSpecifierEnding { /** @internal */ export function usesExtensionsOnImports({ imports }: SourceFile, hasExtension: (text: string) => boolean = or(hasJSFileExtension, hasTSFileExtension)): boolean { - return firstDefined(imports, ({ text }) => pathIsRelative(text) && !fileExtensionIsOneOf(text, extensionsNotSupportingExtensionlessResolution) - ? hasExtension(text) - : undefined) || false; + return firstDefined(imports, ({ text }) => + pathIsRelative(text) && !fileExtensionIsOneOf(text, extensionsNotSupportingExtensionlessResolution) + ? hasExtension(text) + : undefined) || false; } /** @internal */ @@ -9432,7 +9481,7 @@ function numberOfDirectorySeparators(str: string) { export function compareNumberOfDirectorySeparators(path1: string, path2: string) { return compareValues( numberOfDirectorySeparators(path1), - numberOfDirectorySeparators(path2) + numberOfDirectorySeparators(path2), ); } @@ -9478,7 +9527,7 @@ export function tryParsePattern(pattern: string): string | Pattern | undefined { ? undefined : { prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) + suffix: pattern.substr(indexOfStar + 1), }; } @@ -9537,10 +9586,9 @@ export function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: /** @internal */ export const emptyFileSystemEntries: FileSystemEntries = { files: emptyArray, - directories: emptyArray + directories: emptyArray, }; - /** * patternOrStrings contains both patterns (containing "*") and regular strings. * Return an exact match if possible, or a pattern match, or undefined. @@ -9564,7 +9612,7 @@ export function matchPatternOrExact(patternOrStrings: readonly (string | Pattern } /** @internal */ -export type Mutable = { -readonly [K in keyof T]: T[K] }; +export type Mutable = { -readonly [K in keyof T]: T[K]; }; /** @internal */ export function sliceAfter(arr: readonly T[], value: T): readonly T[] { @@ -9587,7 +9635,7 @@ export function addRelatedInfo(diagnostic: T, ...relatedIn } /** @internal */ -export function minAndMax(arr: readonly T[], getValue: (value: T) => number): { readonly min: number, readonly max: number } { +export function minAndMax(arr: readonly T[], getValue: (value: T) => number): { readonly min: number; readonly max: number; } { Debug.assert(arr.length !== 0); let min = getValue(arr[0]); let max = min; @@ -9710,7 +9758,7 @@ export function parsePseudoBigInt(stringValue: string): string { } /** @internal */ -export function pseudoBigIntToString({negative, base10Value}: PseudoBigInt): string { +export function pseudoBigIntToString({ negative, base10Value }: PseudoBigInt): string { return (negative && base10Value !== "0" ? "-" : "") + base10Value; } @@ -9804,7 +9852,7 @@ function isIdentifierInNonEmittingHeritageClause(node: Node): boolean { } /** @internal */ -export function isIdentifierTypeReference(node: Node): node is TypeReferenceNode & { typeName: Identifier } { +export function isIdentifierTypeReference(node: Node): node is TypeReferenceNode & { typeName: Identifier; } { return isTypeReferenceNode(node) && isIdentifier(node.typeName); } @@ -9976,9 +10024,11 @@ export function expressionResultIsUnused(node: Expression): boolean { continue; } // result is unused in an expression statement, `void` expression, or the initializer or incrementer of a `for` loop - if (isExpressionStatement(parent) || + if ( + isExpressionStatement(parent) || isVoidExpression(parent) || - isForStatement(parent) && (parent.initializer === node || parent.incrementor === node)) { + isForStatement(parent) && (parent.initializer === node || parent.incrementor === node) + ) { return true; } if (isCommaListExpression(parent)) { @@ -10181,7 +10231,7 @@ export function getNodeModulePathParts(fullPath: string): NodeModulePathParts | BeforeNodeModules, NodeModules, Scope, - PackageContent + PackageContent, } let partStart = 0; @@ -10265,7 +10315,6 @@ export function isOptionalJSDocPropertyLikeTag(node: Node): node is JSDocPropert } const { isBracketed, typeExpression } = node; return isBracketed || !!typeExpression && typeExpression.type.kind === SyntaxKind.JSDocOptionalType; - } /** @internal */ @@ -10289,8 +10338,8 @@ export function isJSDocOptionalParameter(node: ParameterDeclaration) { return isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === SyntaxKind.JSDocOptionalType - || getJSDocParameterTags(node).some(({ isBracketed, typeExpression }) => - isBracketed || !!typeExpression && typeExpression.type.kind === SyntaxKind.JSDocOptionalType)); + || getJSDocParameterTags(node).some(({ isBracketed, typeExpression }) => isBracketed || !!typeExpression && typeExpression.type.kind === SyntaxKind.JSDocOptionalType) + ); } /** @internal */ diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts index 56574d44d1d65..56ee00f89a04c 100644 --- a/src/compiler/utilitiesPublic.ts +++ b/src/compiler/utilitiesPublic.ts @@ -311,7 +311,7 @@ export function getDefaultLibFileName(options: CompilerOptions): string { case ScriptTarget.ES2016: return "lib.es2016.full.d.ts"; case ScriptTarget.ES2015: - return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change. + return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change. default: return "lib.d.ts"; } @@ -539,7 +539,7 @@ export function getTypeParameterOwner(d: Declaration): Declaration | undefined { } } -export type ParameterPropertyDeclaration = ParameterDeclaration & { parent: ConstructorDeclaration, name: Identifier }; +export type ParameterPropertyDeclaration = ParameterDeclaration & { parent: ConstructorDeclaration; name: Identifier; }; export function isParameterPropertyDeclaration(node: Node, parent: Node): node is ParameterPropertyDeclaration { return isParameter(node) && hasSyntacticModifier(node, ModifierFlags.ParameterPropertyModifier) && parent.kind === SyntaxKind.Constructor; @@ -621,8 +621,9 @@ export const supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", " */ export function validateLocaleAndSetLanguage( locale: string, - sys: { getExecutingFilePath(): string, resolvePath(path: string): string, fileExists(fileName: string): boolean, readFile(fileName: string): string | undefined }, - errors?: Diagnostic[]) { + sys: { getExecutingFilePath(): string; resolvePath(path: string): string; fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; }, + errors?: Diagnostic[], +) { const lowerCaseLocale = locale.toLowerCase(); const matchResult = /^([a-z]+)([_-]([a-z]+))?$/.exec(lowerCaseLocale); @@ -871,7 +872,7 @@ export function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier } /** @internal */ -export function isNamedDeclaration(node: Node): node is NamedDeclaration & { name: DeclarationName } { +export function isNamedDeclaration(node: Node): node is NamedDeclaration & { name: DeclarationName; } { return !!(node as NamedDeclaration).name; // A 'name' property should always be a DeclarationName. } @@ -1003,8 +1004,7 @@ export function getJSDocParameterTagsNoCache(param: ParameterDeclaration): reado function getJSDocTypeParameterTagsWorker(param: TypeParameterDeclaration, noCache?: boolean): readonly JSDocTemplateTag[] { const name = param.name.escapedText; - return getJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocTemplateTag => - isJSDocTemplateTag(tag) && tag.typeParameters.some(tp => tp.name.escapedText === name)); + return getJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocTemplateTag => isJSDocTemplateTag(tag) && tag.typeParameters.some(tp => tp.name.escapedText === name)); } /** @@ -1330,7 +1330,7 @@ export function isOptionalChainRoot(node: Node): node is OptionalChainRoot { * * @internal */ -export function isExpressionOfOptionalChainRoot(node: Node): node is Expression & { parent: OptionalChainRoot } { +export function isExpressionOfOptionalChainRoot(node: Node): node is Expression & { parent: OptionalChainRoot; } { return isOptionalChainRoot(node.parent) && node.parent.expression === node; } @@ -1801,14 +1801,12 @@ export function isAssignmentPattern(node: Node): node is AssignmentPattern { || kind === SyntaxKind.ObjectLiteralExpression; } - export function isArrayBindingElement(node: Node): node is ArrayBindingElement { const kind = node.kind; return kind === SyntaxKind.BindingElement || kind === SyntaxKind.OmittedExpression; } - /** * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration * diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts index 08475d5c0ae7a..109614c3244b2 100644 --- a/src/compiler/visitorPublic.ts +++ b/src/compiler/visitorPublic.ts @@ -403,8 +403,10 @@ export function visitParameterList(nodes: NodeArray | unde // exists in a different lexical scope. To address this, we move any binding patterns and initializers // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list // when the emit target is greater than ES2015. - if (context.getLexicalEnvironmentFlags() & LexicalEnvironmentFlags.VariablesHoistedInParameters && - getEmitScriptTarget(context.getCompilerOptions()) >= ScriptTarget.ES2015) { + if ( + context.getLexicalEnvironmentFlags() & LexicalEnvironmentFlags.VariablesHoistedInParameters && + getEmitScriptTarget(context.getCompilerOptions()) >= ScriptTarget.ES2015 + ) { updated = addDefaultValueAssignmentsIfNeeded(updated, context); } context.setLexicalEnvironmentFlags(LexicalEnvironmentFlags.InParameters, false); @@ -452,25 +454,19 @@ function addDefaultValueAssignmentForBindingPattern(parameter: ParameterDeclarat factory.createConditionalExpression( factory.createStrictEquality( factory.getGeneratedNameForNode(parameter), - factory.createVoidZero() + factory.createVoidZero(), ), /*questionToken*/ undefined, parameter.initializer, /*colonToken*/ undefined, - factory.getGeneratedNameForNode(parameter) + factory.getGeneratedNameForNode(parameter), ) : - factory.getGeneratedNameForNode(parameter) + factory.getGeneratedNameForNode(parameter), ), - ]) - ) + ]), + ), ); - return factory.updateParameterDeclaration(parameter, - parameter.modifiers, - parameter.dotDotDotToken, - factory.getGeneratedNameForNode(parameter), - parameter.questionToken, - parameter.type, - /*initializer*/ undefined); + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, /*initializer*/ undefined); } function addDefaultValueAssignmentForInitializer(parameter: ParameterDeclaration, name: Identifier, initializer: Expression, context: TransformationContext) { @@ -486,27 +482,21 @@ function addDefaultValueAssignmentForInitializer(parameter: ParameterDeclaration setTextRange( factory.createAssignment( setEmitFlags(factory.cloneNode(name), EmitFlags.NoSourceMap), - setEmitFlags(initializer, EmitFlags.NoSourceMap | getEmitFlags(initializer) | EmitFlags.NoComments) + setEmitFlags(initializer, EmitFlags.NoSourceMap | getEmitFlags(initializer) | EmitFlags.NoComments), ), - parameter + parameter, ), - EmitFlags.NoComments - ) - ) + EmitFlags.NoComments, + ), + ), ]), - parameter + parameter, ), - EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments - ) - ) + EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments, + ), + ), ); - return factory.updateParameterDeclaration(parameter, - parameter.modifiers, - parameter.dotDotDotToken, - parameter.name, - parameter.questionToken, - parameter.type, - /*initializer*/ undefined); + return factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, /*initializer*/ undefined); } /** @@ -624,77 +614,94 @@ type VisitEachChildFunction = (node: T, visitor: Visitor, contex // } // // This is then used as the expected type for `visitEachChildTable`. -type VisitEachChildTable = { [TNode in HasChildren as TNode["kind"]]: VisitEachChildFunction }; +type VisitEachChildTable = { [TNode in HasChildren as TNode["kind"]]: VisitEachChildFunction; }; // NOTE: Before you can add a new method to `visitEachChildTable`, you must first ensure the `Node` subtype you // wish to add is defined in the `HasChildren` union in types.ts. const visitEachChildTable: VisitEachChildTable = { [SyntaxKind.QualifiedName]: function visitEachChildOfQualifiedName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateQualifiedName(node, + return context.factory.updateQualifiedName( + node, Debug.checkDefined(nodeVisitor(node.left, visitor, isEntityName)), - Debug.checkDefined(nodeVisitor(node.right, visitor, isIdentifier))); + Debug.checkDefined(nodeVisitor(node.right, visitor, isIdentifier)), + ); }, [SyntaxKind.ComputedPropertyName]: function visitEachChildOfComputedPropertyName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateComputedPropertyName(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateComputedPropertyName( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, // Signature elements [SyntaxKind.TypeParameter]: function visitEachChildOfTypeParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeParameterDeclaration(node, + return context.factory.updateTypeParameterDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodeVisitor(node.constraint, visitor, isTypeNode), - nodeVisitor(node.default, visitor, isTypeNode)); + nodeVisitor(node.default, visitor, isTypeNode), + ); }, [SyntaxKind.Parameter]: function visitEachChildOfParameterDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateParameterDeclaration(node, + return context.factory.updateParameterDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodeVisitor(node.type, visitor, isTypeNode), - nodeVisitor(node.initializer, visitor, isExpression)); + nodeVisitor(node.initializer, visitor, isExpression), + ); }, [SyntaxKind.Decorator]: function visitEachChildOfDecorator(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateDecorator(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateDecorator( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, // Type elements [SyntaxKind.PropertySignature]: function visitEachChildOfPropertySignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updatePropertySignature(node, + return context.factory.updatePropertySignature( + node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, - nodeVisitor(node.type, visitor, isTypeNode)); + nodeVisitor(node.type, visitor, isTypeNode), + ); }, [SyntaxKind.PropertyDeclaration]: function visitEachChildOfPropertyDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updatePropertyDeclaration(node, + return context.factory.updatePropertyDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), // QuestionToken and ExclamationToken are mutually exclusive in PropertyDeclaration tokenVisitor ? nodeVisitor(node.questionToken ?? node.exclamationToken, tokenVisitor, isQuestionOrExclamationToken) : node.questionToken ?? node.exclamationToken, nodeVisitor(node.type, visitor, isTypeNode), - nodeVisitor(node.initializer, visitor, isExpression)); + nodeVisitor(node.initializer, visitor, isExpression), + ); }, [SyntaxKind.MethodSignature]: function visitEachChildOfMethodSignature(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateMethodSignature(node, + return context.factory.updateMethodSignature( + node, nodesVisitor(node.modifiers, visitor, isModifier), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), - nodeVisitor(node.type, visitor, isTypeNode)); + nodeVisitor(node.type, visitor, isTypeNode), + ); }, [SyntaxKind.MethodDeclaration]: function visitEachChildOfMethodDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateMethodDeclaration(node, + return context.factory.updateMethodDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), @@ -702,163 +709,209 @@ const visitEachChildTable: VisitEachChildTable = { nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), - visitFunctionBody(node.body!, visitor, context, nodeVisitor)); + visitFunctionBody(node.body!, visitor, context, nodeVisitor), + ); }, [SyntaxKind.Constructor]: function visitEachChildOfConstructorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateConstructorDeclaration(node, + return context.factory.updateConstructorDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), visitParameterList(node.parameters, visitor, context, nodesVisitor), - visitFunctionBody(node.body!, visitor, context, nodeVisitor)); + visitFunctionBody(node.body!, visitor, context, nodeVisitor), + ); }, [SyntaxKind.GetAccessor]: function visitEachChildOfGetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateGetAccessorDeclaration(node, + return context.factory.updateGetAccessorDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), - visitFunctionBody(node.body!, visitor, context, nodeVisitor)); + visitFunctionBody(node.body!, visitor, context, nodeVisitor), + ); }, [SyntaxKind.SetAccessor]: function visitEachChildOfSetAccessorDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSetAccessorDeclaration(node, + return context.factory.updateSetAccessorDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), visitParameterList(node.parameters, visitor, context, nodesVisitor), - visitFunctionBody(node.body!, visitor, context, nodeVisitor)); + visitFunctionBody(node.body!, visitor, context, nodeVisitor), + ); }, [SyntaxKind.ClassStaticBlockDeclaration]: function visitEachChildOfClassStaticBlockDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { context.startLexicalEnvironment(); context.suspendLexicalEnvironment(); - return context.factory.updateClassStaticBlockDeclaration(node, - visitFunctionBody(node.body, visitor, context, nodeVisitor)); + return context.factory.updateClassStaticBlockDeclaration( + node, + visitFunctionBody(node.body, visitor, context, nodeVisitor), + ); }, [SyntaxKind.CallSignature]: function visitEachChildOfCallSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateCallSignature(node, + return context.factory.updateCallSignature( + node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), - nodeVisitor(node.type, visitor, isTypeNode)); + nodeVisitor(node.type, visitor, isTypeNode), + ); }, [SyntaxKind.ConstructSignature]: function visitEachChildOfConstructSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateConstructSignature(node, + return context.factory.updateConstructSignature( + node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), - nodeVisitor(node.type, visitor, isTypeNode)); + nodeVisitor(node.type, visitor, isTypeNode), + ); }, [SyntaxKind.IndexSignature]: function visitEachChildOfIndexSignatureDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateIndexSignature(node, + return context.factory.updateIndexSignature( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodesVisitor(node.parameters, visitor, isParameter), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, // Types [SyntaxKind.TypePredicate]: function visitEachChildOfTypePredicateNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypePredicateNode(node, + return context.factory.updateTypePredicateNode( + node, nodeVisitor(node.assertsModifier, visitor, isAssertsKeyword), Debug.checkDefined(nodeVisitor(node.parameterName, visitor, isIdentifierOrThisTypeNode)), - nodeVisitor(node.type, visitor, isTypeNode)); + nodeVisitor(node.type, visitor, isTypeNode), + ); }, [SyntaxKind.TypeReference]: function visitEachChildOfTypeReferenceNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeReferenceNode(node, + return context.factory.updateTypeReferenceNode( + node, Debug.checkDefined(nodeVisitor(node.typeName, visitor, isEntityName)), - nodesVisitor(node.typeArguments, visitor, isTypeNode)); + nodesVisitor(node.typeArguments, visitor, isTypeNode), + ); }, [SyntaxKind.FunctionType]: function visitEachChildOfFunctionTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateFunctionTypeNode(node, + return context.factory.updateFunctionTypeNode( + node, nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.ConstructorType]: function visitEachChildOfConstructorTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateConstructorTypeNode(node, + return context.factory.updateConstructorTypeNode( + node, nodesVisitor(node.modifiers, visitor, isModifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, isParameter), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.TypeQuery]: function visitEachChildOfTypeQueryNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeQueryNode(node, + return context.factory.updateTypeQueryNode( + node, Debug.checkDefined(nodeVisitor(node.exprName, visitor, isEntityName)), - nodesVisitor(node.typeArguments, visitor, isTypeNode)); + nodesVisitor(node.typeArguments, visitor, isTypeNode), + ); }, [SyntaxKind.TypeLiteral]: function visitEachChildOfTypeLiteralNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeLiteralNode(node, - nodesVisitor(node.members, visitor, isTypeElement)); + return context.factory.updateTypeLiteralNode( + node, + nodesVisitor(node.members, visitor, isTypeElement), + ); }, [SyntaxKind.ArrayType]: function visitEachChildOfArrayTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateArrayTypeNode(node, - Debug.checkDefined(nodeVisitor(node.elementType, visitor, isTypeNode))); + return context.factory.updateArrayTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.elementType, visitor, isTypeNode)), + ); }, [SyntaxKind.TupleType]: function visitEachChildOfTupleTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateTupleTypeNode(node, - nodesVisitor(node.elements, visitor, isTypeNode)); + return context.factory.updateTupleTypeNode( + node, + nodesVisitor(node.elements, visitor, isTypeNode), + ); }, [SyntaxKind.OptionalType]: function visitEachChildOfOptionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateOptionalTypeNode(node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + return context.factory.updateOptionalTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.RestType]: function visitEachChildOfRestTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateRestTypeNode(node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + return context.factory.updateRestTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.UnionType]: function visitEachChildOfUnionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateUnionTypeNode(node, - nodesVisitor(node.types, visitor, isTypeNode)); + return context.factory.updateUnionTypeNode( + node, + nodesVisitor(node.types, visitor, isTypeNode), + ); }, [SyntaxKind.IntersectionType]: function visitEachChildOfIntersectionTypeNode(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateIntersectionTypeNode(node, - nodesVisitor(node.types, visitor, isTypeNode)); + return context.factory.updateIntersectionTypeNode( + node, + nodesVisitor(node.types, visitor, isTypeNode), + ); }, [SyntaxKind.ConditionalType]: function visitEachChildOfConditionalTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateConditionalTypeNode(node, + return context.factory.updateConditionalTypeNode( + node, Debug.checkDefined(nodeVisitor(node.checkType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.extendsType, visitor, isTypeNode)), Debug.checkDefined(nodeVisitor(node.trueType, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.falseType, visitor, isTypeNode))); + Debug.checkDefined(nodeVisitor(node.falseType, visitor, isTypeNode)), + ); }, [SyntaxKind.InferType]: function visitEachChildOfInferTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateInferTypeNode(node, - Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration))); + return context.factory.updateInferTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)), + ); }, [SyntaxKind.ImportType]: function visitEachChildOfImportTypeNode(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportTypeNode(node, + return context.factory.updateImportTypeNode( + node, Debug.checkDefined(nodeVisitor(node.argument, visitor, isTypeNode)), nodeVisitor(node.assertions, visitor, isImportTypeAssertionContainer), nodeVisitor(node.qualifier, visitor, isEntityName), nodesVisitor(node.typeArguments, visitor, isTypeNode), - node.isTypeOf + node.isTypeOf, ); }, [SyntaxKind.ImportTypeAssertionContainer]: function visitEachChildOfImportTypeAssertionContainer(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportTypeAssertionContainer(node, + return context.factory.updateImportTypeAssertionContainer( + node, Debug.checkDefined(nodeVisitor(node.assertClause, visitor, isAssertClause)), - node.multiLine + node.multiLine, ); }, [SyntaxKind.NamedTupleMember]: function visitEachChildOfNamedTupleMember(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateNamedTupleMember(node, + return context.factory.updateNamedTupleMember( + node, tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken) : node.questionToken, @@ -867,666 +920,878 @@ const visitEachChildTable: VisitEachChildTable = { }, [SyntaxKind.ParenthesizedType]: function visitEachChildOfParenthesizedType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateParenthesizedType(node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + return context.factory.updateParenthesizedType( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.TypeOperator]: function visitEachChildOfTypeOperatorNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeOperatorNode(node, - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + return context.factory.updateTypeOperatorNode( + node, + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.IndexedAccessType]: function visitEachChildOfIndexedAccessType(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateIndexedAccessTypeNode(node, + return context.factory.updateIndexedAccessTypeNode( + node, Debug.checkDefined(nodeVisitor(node.objectType, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.indexType, visitor, isTypeNode))); + Debug.checkDefined(nodeVisitor(node.indexType, visitor, isTypeNode)), + ); }, [SyntaxKind.MappedType]: function visitEachChildOfMappedType(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateMappedTypeNode(node, + return context.factory.updateMappedTypeNode( + node, tokenVisitor ? nodeVisitor(node.readonlyToken, tokenVisitor, isReadonlyKeywordOrPlusOrMinusToken) : node.readonlyToken, Debug.checkDefined(nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration)), nodeVisitor(node.nameType, visitor, isTypeNode), tokenVisitor ? nodeVisitor(node.questionToken, tokenVisitor, isQuestionOrPlusOrMinusToken) : node.questionToken, nodeVisitor(node.type, visitor, isTypeNode), - nodesVisitor(node.members, visitor, isTypeElement)); + nodesVisitor(node.members, visitor, isTypeElement), + ); }, [SyntaxKind.LiteralType]: function visitEachChildOfLiteralTypeNode(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateLiteralTypeNode(node, - Debug.checkDefined(nodeVisitor(node.literal, visitor, isLiteralTypeLiteral))); + return context.factory.updateLiteralTypeNode( + node, + Debug.checkDefined(nodeVisitor(node.literal, visitor, isLiteralTypeLiteral)), + ); }, [SyntaxKind.TemplateLiteralType]: function visitEachChildOfTemplateLiteralType(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTemplateLiteralType(node, + return context.factory.updateTemplateLiteralType( + node, Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), - nodesVisitor(node.templateSpans, visitor, isTemplateLiteralTypeSpan)); + nodesVisitor(node.templateSpans, visitor, isTemplateLiteralTypeSpan), + ); }, [SyntaxKind.TemplateLiteralTypeSpan]: function visitEachChildOfTemplateLiteralTypeSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTemplateLiteralTypeSpan(node, + return context.factory.updateTemplateLiteralTypeSpan( + node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail))); + Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail)), + ); }, // Binding patterns [SyntaxKind.ObjectBindingPattern]: function visitEachChildOfObjectBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateObjectBindingPattern(node, - nodesVisitor(node.elements, visitor, isBindingElement)); + return context.factory.updateObjectBindingPattern( + node, + nodesVisitor(node.elements, visitor, isBindingElement), + ); }, [SyntaxKind.ArrayBindingPattern]: function visitEachChildOfArrayBindingPattern(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateArrayBindingPattern(node, - nodesVisitor(node.elements, visitor, isArrayBindingElement)); + return context.factory.updateArrayBindingPattern( + node, + nodesVisitor(node.elements, visitor, isArrayBindingElement), + ); }, [SyntaxKind.BindingElement]: function visitEachChildOfBindingElement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateBindingElement(node, + return context.factory.updateBindingElement( + node, tokenVisitor ? nodeVisitor(node.dotDotDotToken, tokenVisitor, isDotDotDotToken) : node.dotDotDotToken, nodeVisitor(node.propertyName, visitor, isPropertyName), Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), - nodeVisitor(node.initializer, visitor, isExpression)); + nodeVisitor(node.initializer, visitor, isExpression), + ); }, // Expression [SyntaxKind.ArrayLiteralExpression]: function visitEachChildOfArrayLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateArrayLiteralExpression(node, - nodesVisitor(node.elements, visitor, isExpression)); + return context.factory.updateArrayLiteralExpression( + node, + nodesVisitor(node.elements, visitor, isExpression), + ); }, [SyntaxKind.ObjectLiteralExpression]: function visitEachChildOfObjectLiteralExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateObjectLiteralExpression(node, - nodesVisitor(node.properties, visitor, isObjectLiteralElementLike)); + return context.factory.updateObjectLiteralExpression( + node, + nodesVisitor(node.properties, visitor, isObjectLiteralElementLike), + ); }, [SyntaxKind.PropertyAccessExpression]: function visitEachChildOfPropertyAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return isPropertyAccessChain(node) ? - context.factory.updatePropertyAccessChain(node, + context.factory.updatePropertyAccessChain( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, - Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName))) : - context.factory.updatePropertyAccessExpression(node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName)), + ) : + context.factory.updatePropertyAccessExpression( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName))); + Debug.checkDefined(nodeVisitor(node.name, visitor, isMemberName)), + ); }, [SyntaxKind.ElementAccessExpression]: function visitEachChildOfElementAccessExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { return isElementAccessChain(node) ? - context.factory.updateElementAccessChain(node, + context.factory.updateElementAccessChain( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, - Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression))) : - context.factory.updateElementAccessExpression(node, + Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression)), + ) : + context.factory.updateElementAccessExpression( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression))); + Debug.checkDefined(nodeVisitor(node.argumentExpression, visitor, isExpression)), + ); }, [SyntaxKind.CallExpression]: function visitEachChildOfCallExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { return isCallChain(node) ? - context.factory.updateCallChain(node, + context.factory.updateCallChain( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), tokenVisitor ? nodeVisitor(node.questionDotToken, tokenVisitor, isQuestionDotToken) : node.questionDotToken, nodesVisitor(node.typeArguments, visitor, isTypeNode), - nodesVisitor(node.arguments, visitor, isExpression)) : - context.factory.updateCallExpression(node, + nodesVisitor(node.arguments, visitor, isExpression), + ) : + context.factory.updateCallExpression( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), - nodesVisitor(node.arguments, visitor, isExpression)); + nodesVisitor(node.arguments, visitor, isExpression), + ); }, [SyntaxKind.NewExpression]: function visitEachChildOfNewExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateNewExpression(node, + return context.factory.updateNewExpression( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), - nodesVisitor(node.arguments, visitor, isExpression)); + nodesVisitor(node.arguments, visitor, isExpression), + ); }, [SyntaxKind.TaggedTemplateExpression]: function visitEachChildOfTaggedTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTaggedTemplateExpression(node, + return context.factory.updateTaggedTemplateExpression( + node, Debug.checkDefined(nodeVisitor(node.tag, visitor, isExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), - Debug.checkDefined(nodeVisitor(node.template, visitor, isTemplateLiteral))); + Debug.checkDefined(nodeVisitor(node.template, visitor, isTemplateLiteral)), + ); }, [SyntaxKind.TypeAssertionExpression]: function visitEachChildOfTypeAssertionExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeAssertion(node, + return context.factory.updateTypeAssertion( + node, Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.ParenthesizedExpression]: function visitEachChildOfParenthesizedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateParenthesizedExpression(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateParenthesizedExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.FunctionExpression]: function visitEachChildOfFunctionExpression(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateFunctionExpression(node, + return context.factory.updateFunctionExpression( + node, nodesVisitor(node.modifiers, visitor, isModifier), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), - visitFunctionBody(node.body, visitor, context, nodeVisitor)); + visitFunctionBody(node.body, visitor, context, nodeVisitor), + ); }, [SyntaxKind.ArrowFunction]: function visitEachChildOfArrowFunction(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateArrowFunction(node, + return context.factory.updateArrowFunction( + node, nodesVisitor(node.modifiers, visitor, isModifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, isEqualsGreaterThanToken)) : node.equalsGreaterThanToken, - visitFunctionBody(node.body, visitor, context, nodeVisitor)); + visitFunctionBody(node.body, visitor, context, nodeVisitor), + ); }, [SyntaxKind.DeleteExpression]: function visitEachChildOfDeleteExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateDeleteExpression(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateDeleteExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.TypeOfExpression]: function visitEachChildOfTypeOfExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeOfExpression(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateTypeOfExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.VoidExpression]: function visitEachChildOfVoidExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateVoidExpression(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateVoidExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.AwaitExpression]: function visitEachChildOfAwaitExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateAwaitExpression(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateAwaitExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.PrefixUnaryExpression]: function visitEachChildOfPrefixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updatePrefixUnaryExpression(node, - Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))); + return context.factory.updatePrefixUnaryExpression( + node, + Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression)), + ); }, [SyntaxKind.PostfixUnaryExpression]: function visitEachChildOfPostfixUnaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updatePostfixUnaryExpression(node, - Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression))); + return context.factory.updatePostfixUnaryExpression( + node, + Debug.checkDefined(nodeVisitor(node.operand, visitor, isExpression)), + ); }, [SyntaxKind.BinaryExpression]: function visitEachChildOfBinaryExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateBinaryExpression(node, + return context.factory.updateBinaryExpression( + node, Debug.checkDefined(nodeVisitor(node.left, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.operatorToken, tokenVisitor, isBinaryOperatorToken)) : node.operatorToken, - Debug.checkDefined(nodeVisitor(node.right, visitor, isExpression))); + Debug.checkDefined(nodeVisitor(node.right, visitor, isExpression)), + ); }, [SyntaxKind.ConditionalExpression]: function visitEachChildOfConditionalExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateConditionalExpression(node, + return context.factory.updateConditionalExpression( + node, Debug.checkDefined(nodeVisitor(node.condition, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.questionToken, tokenVisitor, isQuestionToken)) : node.questionToken, Debug.checkDefined(nodeVisitor(node.whenTrue, visitor, isExpression)), tokenVisitor ? Debug.checkDefined(nodeVisitor(node.colonToken, tokenVisitor, isColonToken)) : node.colonToken, - Debug.checkDefined(nodeVisitor(node.whenFalse, visitor, isExpression))); + Debug.checkDefined(nodeVisitor(node.whenFalse, visitor, isExpression)), + ); }, [SyntaxKind.TemplateExpression]: function visitEachChildOfTemplateExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTemplateExpression(node, + return context.factory.updateTemplateExpression( + node, Debug.checkDefined(nodeVisitor(node.head, visitor, isTemplateHead)), - nodesVisitor(node.templateSpans, visitor, isTemplateSpan)); + nodesVisitor(node.templateSpans, visitor, isTemplateSpan), + ); }, [SyntaxKind.YieldExpression]: function visitEachChildOfYieldExpression(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateYieldExpression(node, + return context.factory.updateYieldExpression( + node, tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, - nodeVisitor(node.expression, visitor, isExpression)); + nodeVisitor(node.expression, visitor, isExpression), + ); }, [SyntaxKind.SpreadElement]: function visitEachChildOfSpreadElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSpreadElement(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateSpreadElement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.ClassExpression]: function visitEachChildOfClassExpression(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateClassExpression(node, + return context.factory.updateClassExpression( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), - nodesVisitor(node.members, visitor, isClassElement)); + nodesVisitor(node.members, visitor, isClassElement), + ); }, [SyntaxKind.ExpressionWithTypeArguments]: function visitEachChildOfExpressionWithTypeArguments(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExpressionWithTypeArguments(node, + return context.factory.updateExpressionWithTypeArguments( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - nodesVisitor(node.typeArguments, visitor, isTypeNode)); + nodesVisitor(node.typeArguments, visitor, isTypeNode), + ); }, [SyntaxKind.AsExpression]: function visitEachChildOfAsExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateAsExpression(node, + return context.factory.updateAsExpression( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.SatisfiesExpression]: function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSatisfiesExpression(node, + return context.factory.updateSatisfiesExpression( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.NonNullExpression]: function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return isOptionalChain(node) ? - context.factory.updateNonNullChain(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))) : - context.factory.updateNonNullExpression(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + context.factory.updateNonNullChain( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ) : + context.factory.updateNonNullExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.MetaProperty]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateMetaProperty(node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); + return context.factory.updateMetaProperty( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + ); }, // Misc [SyntaxKind.TemplateSpan]: function visitEachChildOfTemplateSpan(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTemplateSpan(node, + return context.factory.updateTemplateSpan( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail))); + Debug.checkDefined(nodeVisitor(node.literal, visitor, isTemplateMiddleOrTemplateTail)), + ); }, // Element [SyntaxKind.Block]: function visitEachChildOfBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateBlock(node, - nodesVisitor(node.statements, visitor, isStatement)); + return context.factory.updateBlock( + node, + nodesVisitor(node.statements, visitor, isStatement), + ); }, [SyntaxKind.VariableStatement]: function visitEachChildOfVariableStatement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateVariableStatement(node, + return context.factory.updateVariableStatement( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.declarationList, visitor, isVariableDeclarationList))); + Debug.checkDefined(nodeVisitor(node.declarationList, visitor, isVariableDeclarationList)), + ); }, [SyntaxKind.ExpressionStatement]: function visitEachChildOfExpressionStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExpressionStatement(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateExpressionStatement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.IfStatement]: function visitEachChildOfIfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateIfStatement(node, + return context.factory.updateIfStatement( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), Debug.checkDefined(nodeVisitor(node.thenStatement, visitor, isStatement, context.factory.liftToBlock)), - nodeVisitor(node.elseStatement, visitor, isStatement, context.factory.liftToBlock)); + nodeVisitor(node.elseStatement, visitor, isStatement, context.factory.liftToBlock), + ); }, [SyntaxKind.DoStatement]: function visitEachChildOfDoStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateDoStatement(node, + return context.factory.updateDoStatement( + node, visitIterationBody(node.statement, visitor, context, nodeVisitor), - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.WhileStatement]: function visitEachChildOfWhileStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateWhileStatement(node, + return context.factory.updateWhileStatement( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, visitor, context, nodeVisitor)); + visitIterationBody(node.statement, visitor, context, nodeVisitor), + ); }, [SyntaxKind.ForStatement]: function visitEachChildOfForStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateForStatement(node, + return context.factory.updateForStatement( + node, nodeVisitor(node.initializer, visitor, isForInitializer), nodeVisitor(node.condition, visitor, isExpression), nodeVisitor(node.incrementor, visitor, isExpression), - visitIterationBody(node.statement, visitor, context, nodeVisitor)); + visitIterationBody(node.statement, visitor, context, nodeVisitor), + ); }, [SyntaxKind.ForInStatement]: function visitEachChildOfForInStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateForInStatement(node, + return context.factory.updateForInStatement( + node, Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, visitor, context, nodeVisitor)); + visitIterationBody(node.statement, visitor, context, nodeVisitor), + ); }, [SyntaxKind.ForOfStatement]: function visitEachChildOfForOfStatement(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateForOfStatement(node, + return context.factory.updateForOfStatement( + node, tokenVisitor ? nodeVisitor(node.awaitModifier, tokenVisitor, isAwaitKeyword) : node.awaitModifier, Debug.checkDefined(nodeVisitor(node.initializer, visitor, isForInitializer)), Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - visitIterationBody(node.statement, visitor, context, nodeVisitor)); + visitIterationBody(node.statement, visitor, context, nodeVisitor), + ); }, [SyntaxKind.ContinueStatement]: function visitEachChildOfContinueStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateContinueStatement(node, - nodeVisitor(node.label, visitor, isIdentifier)); + return context.factory.updateContinueStatement( + node, + nodeVisitor(node.label, visitor, isIdentifier), + ); }, [SyntaxKind.BreakStatement]: function visitEachChildOfBreakStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateBreakStatement(node, - nodeVisitor(node.label, visitor, isIdentifier)); + return context.factory.updateBreakStatement( + node, + nodeVisitor(node.label, visitor, isIdentifier), + ); }, [SyntaxKind.ReturnStatement]: function visitEachChildOfReturnStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateReturnStatement(node, - nodeVisitor(node.expression, visitor, isExpression)); + return context.factory.updateReturnStatement( + node, + nodeVisitor(node.expression, visitor, isExpression), + ); }, [SyntaxKind.WithStatement]: function visitEachChildOfWithStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateWithStatement(node, + return context.factory.updateWithStatement( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock))); + Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock)), + ); }, [SyntaxKind.SwitchStatement]: function visitEachChildOfSwitchStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSwitchStatement(node, + return context.factory.updateSwitchStatement( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - Debug.checkDefined(nodeVisitor(node.caseBlock, visitor, isCaseBlock))); + Debug.checkDefined(nodeVisitor(node.caseBlock, visitor, isCaseBlock)), + ); }, [SyntaxKind.LabeledStatement]: function visitEachChildOfLabeledStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateLabeledStatement(node, + return context.factory.updateLabeledStatement( + node, Debug.checkDefined(nodeVisitor(node.label, visitor, isIdentifier)), - Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock))); + Debug.checkDefined(nodeVisitor(node.statement, visitor, isStatement, context.factory.liftToBlock)), + ); }, [SyntaxKind.ThrowStatement]: function visitEachChildOfThrowStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateThrowStatement(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateThrowStatement( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.TryStatement]: function visitEachChildOfTryStatement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTryStatement(node, + return context.factory.updateTryStatement( + node, Debug.checkDefined(nodeVisitor(node.tryBlock, visitor, isBlock)), nodeVisitor(node.catchClause, visitor, isCatchClause), - nodeVisitor(node.finallyBlock, visitor, isBlock)); + nodeVisitor(node.finallyBlock, visitor, isBlock), + ); }, [SyntaxKind.VariableDeclaration]: function visitEachChildOfVariableDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateVariableDeclaration(node, + return context.factory.updateVariableDeclaration( + node, Debug.checkDefined(nodeVisitor(node.name, visitor, isBindingName)), tokenVisitor ? nodeVisitor(node.exclamationToken, tokenVisitor, isExclamationToken) : node.exclamationToken, nodeVisitor(node.type, visitor, isTypeNode), - nodeVisitor(node.initializer, visitor, isExpression)); + nodeVisitor(node.initializer, visitor, isExpression), + ); }, [SyntaxKind.VariableDeclarationList]: function visitEachChildOfVariableDeclarationList(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateVariableDeclarationList(node, - nodesVisitor(node.declarations, visitor, isVariableDeclaration)); + return context.factory.updateVariableDeclarationList( + node, + nodesVisitor(node.declarations, visitor, isVariableDeclaration), + ); }, [SyntaxKind.FunctionDeclaration]: function visitEachChildOfFunctionDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, tokenVisitor) { - return context.factory.updateFunctionDeclaration(node, + return context.factory.updateFunctionDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifier), tokenVisitor ? nodeVisitor(node.asteriskToken, tokenVisitor, isAsteriskToken) : node.asteriskToken, nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, isTypeNode), - visitFunctionBody(node.body, visitor, context, nodeVisitor)); + visitFunctionBody(node.body, visitor, context, nodeVisitor), + ); }, [SyntaxKind.ClassDeclaration]: function visitEachChildOfClassDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateClassDeclaration(node, + return context.factory.updateClassDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.name, visitor, isIdentifier), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), - nodesVisitor(node.members, visitor, isClassElement)); + nodesVisitor(node.members, visitor, isClassElement), + ); }, [SyntaxKind.InterfaceDeclaration]: function visitEachChildOfInterfaceDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateInterfaceDeclaration(node, + return context.factory.updateInterfaceDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, isHeritageClause), - nodesVisitor(node.members, visitor, isTypeElement)); + nodesVisitor(node.members, visitor, isTypeElement), + ); }, [SyntaxKind.TypeAliasDeclaration]: function visitEachChildOfTypeAliasDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateTypeAliasDeclaration(node, + return context.factory.updateTypeAliasDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), nodesVisitor(node.typeParameters, visitor, isTypeParameterDeclaration), - Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode))); + Debug.checkDefined(nodeVisitor(node.type, visitor, isTypeNode)), + ); }, [SyntaxKind.EnumDeclaration]: function visitEachChildOfEnumDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateEnumDeclaration(node, + return context.factory.updateEnumDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - nodesVisitor(node.members, visitor, isEnumMember)); + nodesVisitor(node.members, visitor, isEnumMember), + ); }, [SyntaxKind.ModuleDeclaration]: function visitEachChildOfModuleDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateModuleDeclaration(node, + return context.factory.updateModuleDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleName)), - nodeVisitor(node.body, visitor, isModuleBody)); + nodeVisitor(node.body, visitor, isModuleBody), + ); }, [SyntaxKind.ModuleBlock]: function visitEachChildOfModuleBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateModuleBlock(node, - nodesVisitor(node.statements, visitor, isStatement)); + return context.factory.updateModuleBlock( + node, + nodesVisitor(node.statements, visitor, isStatement), + ); }, [SyntaxKind.CaseBlock]: function visitEachChildOfCaseBlock(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateCaseBlock(node, - nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause)); + return context.factory.updateCaseBlock( + node, + nodesVisitor(node.clauses, visitor, isCaseOrDefaultClause), + ); }, [SyntaxKind.NamespaceExportDeclaration]: function visitEachChildOfNamespaceExportDeclaration(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateNamespaceExportDeclaration(node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); + return context.factory.updateNamespaceExportDeclaration( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + ); }, [SyntaxKind.ImportEqualsDeclaration]: function visitEachChildOfImportEqualsDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportEqualsDeclaration(node, + return context.factory.updateImportEqualsDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), node.isTypeOnly, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - Debug.checkDefined(nodeVisitor(node.moduleReference, visitor, isModuleReference))); + Debug.checkDefined(nodeVisitor(node.moduleReference, visitor, isModuleReference)), + ); }, [SyntaxKind.ImportDeclaration]: function visitEachChildOfImportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportDeclaration(node, + return context.factory.updateImportDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), nodeVisitor(node.importClause, visitor, isImportClause), Debug.checkDefined(nodeVisitor(node.moduleSpecifier, visitor, isExpression)), - nodeVisitor(node.assertClause, visitor, isAssertClause)); + nodeVisitor(node.assertClause, visitor, isAssertClause), + ); }, [SyntaxKind.AssertClause]: function visitEachChildOfAssertClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateAssertClause(node, + return context.factory.updateAssertClause( + node, nodesVisitor(node.elements, visitor, isAssertEntry), - node.multiLine); + node.multiLine, + ); }, [SyntaxKind.AssertEntry]: function visitEachChildOfAssertEntry(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateAssertEntry(node, + return context.factory.updateAssertEntry( + node, Debug.checkDefined(nodeVisitor(node.name, visitor, isAssertionKey)), - Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression))); + Debug.checkDefined(nodeVisitor(node.value, visitor, isExpression)), + ); }, [SyntaxKind.ImportClause]: function visitEachChildOfImportClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportClause(node, + return context.factory.updateImportClause( + node, node.isTypeOnly, nodeVisitor(node.name, visitor, isIdentifier), - nodeVisitor(node.namedBindings, visitor, isNamedImportBindings)); + nodeVisitor(node.namedBindings, visitor, isNamedImportBindings), + ); }, [SyntaxKind.NamespaceImport]: function visitEachChildOfNamespaceImport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateNamespaceImport(node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); + return context.factory.updateNamespaceImport( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + ); }, [SyntaxKind.NamespaceExport]: function visitEachChildOfNamespaceExport(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateNamespaceExport(node, - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); + return context.factory.updateNamespaceExport( + node, + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + ); }, [SyntaxKind.NamedImports]: function visitEachChildOfNamedImports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateNamedImports(node, - nodesVisitor(node.elements, visitor, isImportSpecifier)); + return context.factory.updateNamedImports( + node, + nodesVisitor(node.elements, visitor, isImportSpecifier), + ); }, [SyntaxKind.ImportSpecifier]: function visitEachChildOfImportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateImportSpecifier(node, + return context.factory.updateImportSpecifier( + node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, isIdentifier), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + ); }, [SyntaxKind.ExportAssignment]: function visitEachChildOfExportAssignment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExportAssignment(node, + return context.factory.updateExportAssignment( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.ExportDeclaration]: function visitEachChildOfExportDeclaration(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExportDeclaration(node, + return context.factory.updateExportDeclaration( + node, nodesVisitor(node.modifiers, visitor, isModifierLike), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, isExpression), - nodeVisitor(node.assertClause, visitor, isAssertClause)); + nodeVisitor(node.assertClause, visitor, isAssertClause), + ); }, [SyntaxKind.NamedExports]: function visitEachChildOfNamedExports(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateNamedExports(node, - nodesVisitor(node.elements, visitor, isExportSpecifier)); + return context.factory.updateNamedExports( + node, + nodesVisitor(node.elements, visitor, isExportSpecifier), + ); }, [SyntaxKind.ExportSpecifier]: function visitEachChildOfExportSpecifier(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExportSpecifier(node, + return context.factory.updateExportSpecifier( + node, node.isTypeOnly, nodeVisitor(node.propertyName, visitor, isIdentifier), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + ); }, // Module references [SyntaxKind.ExternalModuleReference]: function visitEachChildOfExternalModuleReference(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateExternalModuleReference(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateExternalModuleReference( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, // JSX [SyntaxKind.JsxElement]: function visitEachChildOfJsxElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxElement(node, + return context.factory.updateJsxElement( + node, Debug.checkDefined(nodeVisitor(node.openingElement, visitor, isJsxOpeningElement)), nodesVisitor(node.children, visitor, isJsxChild), - Debug.checkDefined(nodeVisitor(node.closingElement, visitor, isJsxClosingElement))); + Debug.checkDefined(nodeVisitor(node.closingElement, visitor, isJsxClosingElement)), + ); }, [SyntaxKind.JsxSelfClosingElement]: function visitEachChildOfJsxSelfClosingElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxSelfClosingElement(node, + return context.factory.updateJsxSelfClosingElement( + node, Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), - Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes))); + Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes)), + ); }, [SyntaxKind.JsxOpeningElement]: function visitEachChildOfJsxOpeningElement(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxOpeningElement(node, + return context.factory.updateJsxOpeningElement( + node, Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), nodesVisitor(node.typeArguments, visitor, isTypeNode), - Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes))); + Debug.checkDefined(nodeVisitor(node.attributes, visitor, isJsxAttributes)), + ); }, [SyntaxKind.JsxClosingElement]: function visitEachChildOfJsxClosingElement(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxClosingElement(node, - Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression))); + return context.factory.updateJsxClosingElement( + node, + Debug.checkDefined(nodeVisitor(node.tagName, visitor, isJsxTagNameExpression)), + ); }, [SyntaxKind.JsxNamespacedName]: function forEachChildInJsxNamespacedName(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxNamespacedName(node, + return context.factory.updateJsxNamespacedName( + node, Debug.checkDefined(nodeVisitor(node.namespace, visitor, isIdentifier)), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier))); + Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), + ); }, [SyntaxKind.JsxFragment]: function visitEachChildOfJsxFragment(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxFragment(node, + return context.factory.updateJsxFragment( + node, Debug.checkDefined(nodeVisitor(node.openingFragment, visitor, isJsxOpeningFragment)), nodesVisitor(node.children, visitor, isJsxChild), - Debug.checkDefined(nodeVisitor(node.closingFragment, visitor, isJsxClosingFragment))); + Debug.checkDefined(nodeVisitor(node.closingFragment, visitor, isJsxClosingFragment)), + ); }, [SyntaxKind.JsxAttribute]: function visitEachChildOfJsxAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxAttribute(node, + return context.factory.updateJsxAttribute( + node, Debug.checkDefined(nodeVisitor(node.name, visitor, isJsxAttributeName)), - nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression)); + nodeVisitor(node.initializer, visitor, isStringLiteralOrJsxExpression), + ); }, [SyntaxKind.JsxAttributes]: function visitEachChildOfJsxAttributes(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxAttributes(node, - nodesVisitor(node.properties, visitor, isJsxAttributeLike)); + return context.factory.updateJsxAttributes( + node, + nodesVisitor(node.properties, visitor, isJsxAttributeLike), + ); }, [SyntaxKind.JsxSpreadAttribute]: function visitEachChildOfJsxSpreadAttribute(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxSpreadAttribute(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateJsxSpreadAttribute( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.JsxExpression]: function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateJsxExpression(node, - nodeVisitor(node.expression, visitor, isExpression)); + return context.factory.updateJsxExpression( + node, + nodeVisitor(node.expression, visitor, isExpression), + ); }, // Clauses [SyntaxKind.CaseClause]: function visitEachChildOfCaseClause(node, visitor, context, nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateCaseClause(node, + return context.factory.updateCaseClause( + node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), - nodesVisitor(node.statements, visitor, isStatement)); + nodesVisitor(node.statements, visitor, isStatement), + ); }, [SyntaxKind.DefaultClause]: function visitEachChildOfDefaultClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateDefaultClause(node, - nodesVisitor(node.statements, visitor, isStatement)); + return context.factory.updateDefaultClause( + node, + nodesVisitor(node.statements, visitor, isStatement), + ); }, [SyntaxKind.HeritageClause]: function visitEachChildOfHeritageClause(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateHeritageClause(node, - nodesVisitor(node.types, visitor, isExpressionWithTypeArguments)); + return context.factory.updateHeritageClause( + node, + nodesVisitor(node.types, visitor, isExpressionWithTypeArguments), + ); }, [SyntaxKind.CatchClause]: function visitEachChildOfCatchClause(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateCatchClause(node, + return context.factory.updateCatchClause( + node, nodeVisitor(node.variableDeclaration, visitor, isVariableDeclaration), - Debug.checkDefined(nodeVisitor(node.block, visitor, isBlock))); + Debug.checkDefined(nodeVisitor(node.block, visitor, isBlock)), + ); }, // Property assignments [SyntaxKind.PropertyAssignment]: function visitEachChildOfPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updatePropertyAssignment(node, + return context.factory.updatePropertyAssignment( + node, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - Debug.checkDefined(nodeVisitor(node.initializer, visitor, isExpression))); + Debug.checkDefined(nodeVisitor(node.initializer, visitor, isExpression)), + ); }, [SyntaxKind.ShorthandPropertyAssignment]: function visitEachChildOfShorthandPropertyAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateShorthandPropertyAssignment(node, + return context.factory.updateShorthandPropertyAssignment( + node, Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)), - nodeVisitor(node.objectAssignmentInitializer, visitor, isExpression)); + nodeVisitor(node.objectAssignmentInitializer, visitor, isExpression), + ); }, [SyntaxKind.SpreadAssignment]: function visitEachChildOfSpreadAssignment(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateSpreadAssignment(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updateSpreadAssignment( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, // Enum [SyntaxKind.EnumMember]: function visitEachChildOfEnumMember(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updateEnumMember(node, + return context.factory.updateEnumMember( + node, Debug.checkDefined(nodeVisitor(node.name, visitor, isPropertyName)), - nodeVisitor(node.initializer, visitor, isExpression)); + nodeVisitor(node.initializer, visitor, isExpression), + ); }, // Top-level nodes [SyntaxKind.SourceFile]: function visitEachChildOfSourceFile(node, visitor, context, _nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateSourceFile(node, - visitLexicalEnvironment(node.statements, visitor, context)); + return context.factory.updateSourceFile( + node, + visitLexicalEnvironment(node.statements, visitor, context), + ); }, // Transformation nodes [SyntaxKind.PartiallyEmittedExpression]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { - return context.factory.updatePartiallyEmittedExpression(node, - Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression))); + return context.factory.updatePartiallyEmittedExpression( + node, + Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)), + ); }, [SyntaxKind.CommaListExpression]: function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { - return context.factory.updateCommaListExpression(node, - nodesVisitor(node.elements, visitor, isExpression)); + return context.factory.updateCommaListExpression( + node, + nodesVisitor(node.elements, visitor, isExpression), + ); }, }; diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index a829f95d17fbd..fd4d4a8b6ca28 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -111,7 +111,7 @@ import { const sysFormatDiagnosticsHost: FormatDiagnosticsHost | undefined = sys ? { getCurrentDirectory: () => sys.getCurrentDirectory(), getNewLine: () => sys.newLine, - getCanonicalFileName: createGetCanonicalFileName(sys.useCaseSensitiveFileNames) + getCanonicalFileName: createGetCanonicalFileName(sys.useCaseSensitiveFileNames), } : undefined; /** @@ -141,11 +141,13 @@ export function createDiagnosticReporter(system: System, pretty?: boolean): Diag * @returns Whether the screen was cleared. */ function clearScreenIfNotWatchingForFileChanges(system: System, diagnostic: Diagnostic, options: CompilerOptions): boolean { - if (system.clearScreen && + if ( + system.clearScreen && !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - contains(screenStartingMessageCodes, diagnostic.code)) { + contains(screenStartingMessageCodes, diagnostic.code) + ) { system.clearScreen(); return true; } @@ -228,21 +230,19 @@ export function getErrorCountForSummary(diagnostics: readonly Diagnostic[]) { /** @internal */ export function getFilesInErrorForSummary(diagnostics: readonly Diagnostic[]): (ReportFileInError | undefined)[] { - const filesInError = - filter(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error) - .map( - errorDiagnostic => { - if (errorDiagnostic.file === undefined) return; - return `${errorDiagnostic.file.fileName}`; - }); - return filesInError.map((fileName) => { + const filesInError = filter(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error) + .map( + errorDiagnostic => { + if (errorDiagnostic.file === undefined) return; + return `${errorDiagnostic.file.fileName}`; + }, + ); + return filesInError.map(fileName => { if (fileName === undefined) { return undefined; } - const diagnosticForFileName = find(diagnostics, diagnostic => - diagnostic.file !== undefined && diagnostic.file.fileName === fileName - ); + const diagnosticForFileName = find(diagnostics, diagnostic => diagnostic.file !== undefined && diagnostic.file.fileName === fileName); if (diagnosticForFileName !== undefined) { const { line } = getLineAndCharacterOfPosition(diagnosticForFileName.file!, diagnosticForFileName.start!); @@ -275,7 +275,7 @@ export function getErrorSummaryText( errorCount: number, filesInError: readonly (ReportFileInError | undefined)[], newLine: string, - host: HasCurrentDirectory + host: HasCurrentDirectory, ) { if (errorCount === 0) return ""; const nonNilFiles = filesInError.filter(fileInError => fileInError !== undefined); @@ -289,8 +289,7 @@ export function getErrorSummaryText( messageAndArgs = filesInError[0] !== undefined ? [Diagnostics.Found_1_error_in_0, firstFileReference!] : [Diagnostics.Found_1_error]; } else { - messageAndArgs = - distinctFileNamesWithLines.length === 0 ? [Diagnostics.Found_0_errors, errorCount] : + messageAndArgs = distinctFileNamesWithLines.length === 0 ? [Diagnostics.Found_0_errors, errorCount] : distinctFileNamesWithLines.length === 1 ? [Diagnostics.Found_0_errors_in_the_same_file_starting_at_Colon_1, errorCount, firstFileReference!] : [Diagnostics.Found_0_errors_in_1_files, errorCount, distinctFileNamesWithLines.length]; } @@ -315,7 +314,7 @@ function createTabularErrorsDisplay(filesInError: (ReportFileInError | undefined let tabularData = ""; tabularData += " ".repeat(headerPadding) + headerRow + "\n"; - fileToErrorCount.forEach((row) => { + fileToErrorCount.forEach(row => { const [file, errorCount] = row; const errorCountDigitsLength = Math.log(errorCount) * Math.LOG10E + 1 | 0; const leftPadding = errorCountDigitsLength < leftPaddingGoal ? @@ -368,14 +367,14 @@ export function explainIfFileIsRedirectAndImpliedFormat( (result ??= []).push(chainDiagnosticMessages( /*details*/ undefined, Diagnostics.File_is_output_of_project_reference_source_0, - toFileName(file.originalFileName, fileNameConvertor) + toFileName(file.originalFileName, fileNameConvertor), )); } if (file.redirectInfo) { (result ??= []).push(chainDiagnosticMessages( /*details*/ undefined, Diagnostics.File_redirects_to_file_0, - toFileName(file.redirectInfo.redirectTarget, fileNameConvertor) + toFileName(file.redirectInfo.redirectTarget, fileNameConvertor), )); } if (isExternalOrCommonJsModule(file)) { @@ -385,7 +384,7 @@ export function explainIfFileIsRedirectAndImpliedFormat( (result ??= []).push(chainDiagnosticMessages( /*details*/ undefined, Diagnostics.File_is_ECMAScript_module_because_0_has_field_type_with_value_module, - toFileName(last(file.packageJsonLocations!), fileNameConvertor) + toFileName(last(file.packageJsonLocations!), fileNameConvertor), )); } break; @@ -396,7 +395,7 @@ export function explainIfFileIsRedirectAndImpliedFormat( file.packageJsonScope.contents.packageJsonContent.type ? Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module : Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, - toFileName(last(file.packageJsonLocations!), fileNameConvertor) + toFileName(last(file.packageJsonLocations!), fileNameConvertor), )); } else if (file.packageJsonLocations?.length) { @@ -440,7 +439,7 @@ export function getMatchedIncludeSpec(program: Program, fileName: string) { } /** @internal */ -export function fileIncludeReasonToDiagnostics(program: Program, reason: FileIncludeReason, fileNameConvertor?: (fileName: string) => string,): DiagnosticMessageChain { +export function fileIncludeReasonToDiagnostics(program: Program, reason: FileIncludeReason, fileNameConvertor?: (fileName: string) => string): DiagnosticMessageChain { const options = program.getCompilerOptions(); if (isReferencedFile(reason)) { const referenceLocation = getReferencedFileLocation(path => program.getSourceFileByPath(path), reason); @@ -486,7 +485,7 @@ export function fileIncludeReasonToDiagnostics(program: Program, reason: FileInc message, referenceText, toFileName(referenceLocation.file, fileNameConvertor), - (referenceLocation.packageId && packageIdToString(referenceLocation.packageId))! + (referenceLocation.packageId && packageIdToString(referenceLocation.packageId))!, ); } switch (reason.kind) { @@ -501,12 +500,14 @@ export function fileIncludeReasonToDiagnostics(program: Program, reason: FileInc /*details*/ undefined, Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, - toFileName(options.configFile, fileNameConvertor) + toFileName(options.configFile, fileNameConvertor), ) : // Could be additional files specified as roots or matched by default include - chainDiagnosticMessages(/*details*/ undefined, matchedByInclude ? - Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : - Diagnostics.Root_file_specified_for_compilation + chainDiagnosticMessages( + /*details*/ undefined, + matchedByInclude ? + Diagnostics.Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk : + Diagnostics.Root_file_specified_for_compilation, ); case FileIncludeKind.SourceFromProjectReference: case FileIncludeKind.OutputFromProjectReference: @@ -519,8 +520,8 @@ export function fileIncludeReasonToDiagnostics(program: Program, reason: FileInc Diagnostics.Output_from_referenced_project_0_included_because_1_specified : Diagnostics.Source_from_referenced_project_0_included_because_1_specified : isOutput ? - Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none : - Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, + Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none : + Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor), options.outFile ? "--outFile" : "--out", ); @@ -530,8 +531,8 @@ export function fileIncludeReasonToDiagnostics(program: Program, reason: FileInc [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : [Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions, reason.typeReference] : reason.packageId ? - [Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : - [Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference]; + [Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1, reason.typeReference, packageIdToString(reason.packageId)] : + [Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference]; return chainDiagnosticMessages(/*details*/ undefined, ...messageAndArgs); } @@ -564,7 +565,7 @@ export function emitFilesAndReportErrors( writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, - customTransformers?: CustomTransformers + customTransformers?: CustomTransformers, ): { emitResult: EmitResult; diagnostics: SortedReadonlyArray; @@ -627,7 +628,7 @@ export function emitFilesAndReportErrorsAndGetExitStatus 0) { @@ -665,7 +666,7 @@ export function createWatchHost(system = sys, reportWatchStatus?: WatchStatusRep watchFile: maybeBind(system, system.watchFile) || returnNoopFileWatcher, watchDirectory: maybeBind(system, system.watchDirectory) || returnNoopFileWatcher, setTimeout: maybeBind(system, system.setTimeout) || noop, - clearTimeout: maybeBind(system, system.clearTimeout) || noop + clearTimeout: maybeBind(system, system.clearTimeout) || noop, }; } @@ -698,29 +699,29 @@ export const WatchType: WatchTypeRegistry = { /** @internal */ export interface WatchTypeRegistry { - ConfigFile: "Config file", - ExtendedConfigFile: "Extended config file", - SourceFile: "Source file", - MissingFile: "Missing file", - WildcardDirectory: "Wild card directory", - FailedLookupLocations: "Failed Lookup Locations", - AffectingFileLocation: "File location affecting resolution", - TypeRoots: "Type roots", - ConfigFileOfReferencedProject: "Config file of referened project", - ExtendedConfigOfReferencedProject: "Extended config file of referenced project", - WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project", - PackageJson: "package.json file", + ConfigFile: "Config file"; + ExtendedConfigFile: "Extended config file"; + SourceFile: "Source file"; + MissingFile: "Missing file"; + WildcardDirectory: "Wild card directory"; + FailedLookupLocations: "Failed Lookup Locations"; + AffectingFileLocation: "File location affecting resolution"; + TypeRoots: "Type roots"; + ConfigFileOfReferencedProject: "Config file of referened project"; + ExtendedConfigOfReferencedProject: "Extended config file of referenced project"; + WildcardDirectoryOfReferencedProject: "Wild card directory of referenced project"; + PackageJson: "package.json file"; // Additional tsserver specific watch information - ClosedScriptInfo: "Closed Script info", - ConfigFileForInferredRoot: "Config file for the inferred project root", - NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache", - MissingSourceMapFile: "Missing source map file", - NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root", - MissingGeneratedFile: "Missing generated file", - NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", - TypingInstallerLocationFile: "File location for typing installer", - TypingInstallerLocationDirectory: "Directory location for typing installer", + ClosedScriptInfo: "Closed Script info"; + ConfigFileForInferredRoot: "Config file for the inferred project root"; + NodeModules: "node_modules for closed script infos and package.jsons affecting module specifier cache"; + MissingSourceMapFile: "Missing source map file"; + NoopConfigFileForInferredRoot: "Noop Config file for the inferred project root"; + MissingGeneratedFile: "Missing generated file"; + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation"; + TypingInstallerLocationFile: "File location for typing installer"; + TypingInstallerLocationDirectory: "Directory location for typing installer"; } /** @internal */ @@ -744,14 +745,14 @@ export function createCompilerHostFromProgramHost(host: ProgramHost, getCom getSourceFile: createGetSourceFile( (fileName, encoding) => !encoding ? compilerHost.readFile(fileName) : host.readFile(fileName, encoding), getCompilerOptions, - /*setParentNodes*/ undefined + /*setParentNodes*/ undefined, ), getDefaultLibLocation: maybeBind(host, host.getDefaultLibLocation), getDefaultLibFileName: options => host.getDefaultLibFileName(options), writeFile: createWriteFileMeasuringIO( (path, data, writeByteOrderMark) => host.writeFile!(path, data, writeByteOrderMark), path => host.createDirectory!(path), - path => host.directoryExists!(path) + path => host.directoryExists!(path), ), getCurrentDirectory: memoize(() => host.getCurrentDirectory()), useCaseSensitiveFileNames: () => useCaseSensitiveFileNames, @@ -867,12 +868,13 @@ function createWatchCompilerHost result.onWatchStatusChange!( - createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), - newLine, - compilerOptions, - errorCount - ) + errorCount => + result.onWatchStatusChange!( + createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), + newLine, + compilerOptions, + errorCount, + ), ); }; return result; @@ -907,8 +909,14 @@ export interface CreateWatchCompilerHostOfConfigFileInput({ - configFileName, optionsToExtend, watchOptionsToExtend, extraFileExtensions, - system, createProgram, reportDiagnostic, reportWatchStatus + configFileName, + optionsToExtend, + watchOptionsToExtend, + extraFileExtensions, + system, + createProgram, + reportDiagnostic, + reportWatchStatus, }: CreateWatchCompilerHostOfConfigFileInput): WatchCompilerHostOfConfigFile { const diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); const host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus) as WatchCompilerHostOfConfigFile; @@ -933,8 +941,14 @@ export interface CreateWatchCompilerHostOfFilesAndCompilerOptionsInput({ - rootFiles, options, watchOptions, projectReferences, - system, createProgram, reportDiagnostic, reportWatchStatus + rootFiles, + options, + watchOptions, + projectReferences, + system, + createProgram, + reportDiagnostic, + reportWatchStatus, }: CreateWatchCompilerHostOfFilesAndCompilerOptionsInput): WatchCompilerHostOfFilesAndCompilerOptions { const host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus) as WatchCompilerHostOfFilesAndCompilerOptions; host.rootFiles = rootFiles; @@ -965,7 +979,7 @@ export function performIncrementalCompilation(input: IncrementalCompilationOptio builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), s => host.trace && host.trace(s), - input.reportErrorSummary || input.options.pretty ? (errorCount, filesInError) => system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)) : undefined + input.reportErrorSummary || input.options.pretty ? (errorCount, filesInError) => system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)) : undefined, ); if (input.afterProgramEmitAndDiagnostics) input.afterProgramEmitAndDiagnostics(builderProgram); return exitStatus; diff --git a/src/compiler/watchPublic.ts b/src/compiler/watchPublic.ts index b216c8cb75de0..e963067868d66 100644 --- a/src/compiler/watchPublic.ts +++ b/src/compiler/watchPublic.ts @@ -137,7 +137,12 @@ export interface IncrementalProgramOptions { } export function createIncrementalProgram({ - rootNames, options, configFileParsingDiagnostics, projectReferences, host, createProgram + rootNames, + options, + configFileParsingDiagnostics, + projectReferences, + host, + createProgram, }: IncrementalProgramOptions): T { host = host || createIncrementalCompilerHost(options); createProgram = createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram; @@ -228,7 +233,7 @@ export interface ProgramHost { redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile | undefined, - reusedNames: readonly T[] | undefined + reusedNames: readonly T[] | undefined, ): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[]; /** @internal */ resolveLibrary?( @@ -303,7 +308,7 @@ export interface WatchCompilerHostOfConfigFile extends watchOptionsToExtend?: WatchOptions; - extraFileExtensions?: readonly FileExtensionInfo[] + extraFileExtensions?: readonly FileExtensionInfo[]; /** * Used to generate source file names from the config file and its include, exclude, files rules @@ -420,19 +425,19 @@ export function createWatchProgram(host: WatchCompiler type HostFileInfo = FilePresentOnHost | FileMissingOnHost | FilePresenceUnknownOnHost; let builderProgram: T; - let reloadLevel: ConfigFileProgramReloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc - let missingFilesMap: Map; // Map of file watchers for the missing files + let reloadLevel: ConfigFileProgramReloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + let missingFilesMap: Map; // Map of file watchers for the missing files let watchedWildcardDirectories: Map; // map of watchers for the wild card directories in the config file - let timerToUpdateProgram: any; // timer callback to recompile the program - let timerToInvalidateFailedLookupResolutions: any; // timer callback to invalidate resolutions for changes in failed lookup locations - let parsedConfigs: Map | undefined; // Parsed commandline and watching cached for referenced projects + let timerToUpdateProgram: any; // timer callback to recompile the program + let timerToInvalidateFailedLookupResolutions: any; // timer callback to invalidate resolutions for changes in failed lookup locations + let parsedConfigs: Map | undefined; // Parsed commandline and watching cached for referenced projects let sharedExtendedConfigFileWatchers: Map>; // Map of file watchers for extended files, shared between different referenced projects - let extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation - let reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created + let extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation + let reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created - const sourceFilesCache = new Map(); // Cache that stores the source file and version info - let missingFilePathsRequestedForRelease: Path[] | undefined; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files - let hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + const sourceFilesCache = new Map(); // Cache that stores the source file and version info + let missingFilePathsRequestedForRelease: Path[] | undefined; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files + let hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); const currentDirectory = host.getCurrentDirectory(); @@ -500,11 +505,12 @@ export function createWatchProgram(host: WatchCompiler compilerHost.getParsedCommandLine = getParsedCommandLine; // Cache for the module resolution - const resolutionCache = createResolutionCache(compilerHost, + const resolutionCache = createResolutionCache( + compilerHost, configFileName ? getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) : currentDirectory, - /*logChangesWhenResolvingModule*/ false + /*logChangesWhenResolvingModule*/ false, ); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); @@ -515,7 +521,7 @@ export function createWatchProgram(host: WatchCompiler compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { - compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache); + compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache); } compilerHost.resolveLibrary = !host.resolveLibrary ? resolutionCache.resolveLibrary.bind(resolutionCache) : @@ -610,8 +616,12 @@ export function createWatchProgram(host: WatchCompiler const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); const { - originalReadFile, originalFileExists, originalDirectoryExists, - originalCreateDirectory, originalWriteFile, readFileWithCache + originalReadFile, + originalFileExists, + originalDirectoryExists, + originalCreateDirectory, + originalWriteFile, + readFileWithCache, } = changeCompilerHostLikeToUseCache(compilerHost, toPath); if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, path => getSourceVersion(path, readFileWithCache), fileName => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { @@ -918,14 +928,16 @@ export function createWatchProgram(host: WatchCompiler function parseConfigFile() { Debug.assert(configFileName); - setConfigFileParsingResult(getParsedCommandLineOfConfigFile( - configFileName, - optionsToExtendForConfigFile, - parseConfigFileHost, - extendedConfigCache ||= new Map(), - watchOptionsToExtend, - extraFileExtensions - )!); // TODO: GH#18217 + setConfigFileParsingResult( + getParsedCommandLineOfConfigFile( + configFileName, + optionsToExtendForConfigFile, + parseConfigFileHost, + extendedConfigCache ||= new Map(), + watchOptionsToExtend, + extraFileExtensions, + )!, + ); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult: ParsedCommandLine) { @@ -984,7 +996,7 @@ export function createWatchProgram(host: WatchCompiler /*optionsToExtend*/ undefined, parseConfigFileHost, extendedConfigCache ||= new Map(), - watchOptionsToExtend + watchOptionsToExtend, ); parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = onUnRecoverableConfigFileDiagnostic; return parsedCommandLine; @@ -1007,7 +1019,7 @@ export function createWatchProgram(host: WatchCompiler callback: (fileName: string, eventKind: FileWatcherEventKind, filePath: Path) => void, pollingInterval: PollingInterval, options: WatchOptions | undefined, - watchType: WatchType + watchType: WatchType, ): FileWatcher { return watchFile(file, (fileName, eventKind) => callback(fileName, eventKind, path), pollingInterval, options, watchType); } @@ -1058,7 +1070,7 @@ export function createWatchProgram(host: WatchCompiler updateWatchingWildcardDirectories( watchedWildcardDirectories || (watchedWildcardDirectories = new Map()), new Map(Object.entries(wildcardDirectories)), - watchWildcardDirectory + watchWildcardDirectory, ); } else if (watchedWildcardDirectories) { @@ -1081,19 +1093,21 @@ export function createWatchProgram(host: WatchCompiler } nextSourceFileVersion(fileOrDirectoryPath); - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: toPath(directory), - fileOrDirectory, - fileOrDirectoryPath, - configFileName, - extraFileExtensions, - options: compilerOptions, - program: getCurrentBuilderProgram() || rootFileNames, - currentDirectory, - useCaseSensitiveFileNames, - writeLog, - toPath, - })) return; + if ( + isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + extraFileExtensions, + options: compilerOptions, + program: getCurrentBuilderProgram() || rootFileNames, + currentDirectory, + useCaseSensitiveFileNames, + writeLog, + toPath, + }) + ) return; // Reload is pending, do the reload if (reloadLevel !== ConfigFileProgramReloadLevel.Full) { @@ -1105,7 +1119,7 @@ export function createWatchProgram(host: WatchCompiler }, flags, watchOptions, - WatchType.WildcardDirectory + WatchType.WildcardDirectory, ); } @@ -1114,34 +1128,35 @@ export function createWatchProgram(host: WatchCompiler forProjectPath, options, sharedExtendedConfigFileWatchers ||= new Map(), - (extendedConfigFileName, extendedConfigFilePath) => watchFile( - extendedConfigFileName, - (_fileName, eventKind) => { - updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); - // Update extended config cache - if (extendedConfigCache) cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); - // Update projects - const projects = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)?.projects; - // If there are no referenced projects this extended config file watcher depend on ignore - if (!projects?.size) return; - projects.forEach(projectPath => { - if (configFileName && toPath(configFileName) === projectPath) { - // If this is the config file of the project, reload completely - reloadLevel = ConfigFileProgramReloadLevel.Full; - } - else { - // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed - const config = parsedConfigs?.get(projectPath); - if (config) config.reloadLevel = ConfigFileProgramReloadLevel.Full; - resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); - } - scheduleProgramUpdate(); - }); - }, - PollingInterval.High, - watchOptions, - watchType - ), + (extendedConfigFileName, extendedConfigFilePath) => + watchFile( + extendedConfigFileName, + (_fileName, eventKind) => { + updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); + // Update extended config cache + if (extendedConfigCache) cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath); + // Update projects + const projects = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)?.projects; + // If there are no referenced projects this extended config file watcher depend on ignore + if (!projects?.size) return; + projects.forEach(projectPath => { + if (configFileName && toPath(configFileName) === projectPath) { + // If this is the config file of the project, reload completely + reloadLevel = ConfigFileProgramReloadLevel.Full; + } + else { + // Reload config for the referenced projects and remove the resolutions from referenced projects since the config file changed + const config = parsedConfigs?.get(projectPath); + if (config) config.reloadLevel = ConfigFileProgramReloadLevel.Full; + resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); + } + scheduleProgramUpdate(); + }); + }, + PollingInterval.High, + watchOptions, + watchType, + ), toPath, ); } @@ -1159,50 +1174,53 @@ export function createWatchProgram(host: WatchCompiler }, PollingInterval.High, commandLine.parsedCommandLine?.watchOptions || watchOptions, - WatchType.ConfigFileOfReferencedProject + WatchType.ConfigFileOfReferencedProject, ); // Watch Wild card if (commandLine.parsedCommandLine?.wildcardDirectories) { updateWatchingWildcardDirectories( commandLine.watchedDirectories ||= new Map(), new Map(Object.entries(commandLine.parsedCommandLine?.wildcardDirectories)), - (directory, flags) => watchDirectory( - directory, - fileOrDirectory => { - const fileOrDirectoryPath = toPath(fileOrDirectory); - // Since the file existence changed, update the sourceFiles cache - if (cachedDirectoryStructureHost) { - cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - } - nextSourceFileVersion(fileOrDirectoryPath); - - const config = parsedConfigs?.get(configPath); - if (!config?.parsedCommandLine) return; - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: toPath(directory), - fileOrDirectory, - fileOrDirectoryPath, - configFileName, - options: config.parsedCommandLine.options, - program: config.parsedCommandLine.fileNames, - currentDirectory, - useCaseSensitiveFileNames, - writeLog, - toPath, - })) return; - - // Reload is pending, do the reload - if (config.reloadLevel !== ConfigFileProgramReloadLevel.Full) { - config.reloadLevel = ConfigFileProgramReloadLevel.Partial; - - // Schedule Update the program - scheduleProgramUpdate(); - } - }, - flags, - commandLine.parsedCommandLine?.watchOptions || watchOptions, - WatchType.WildcardDirectoryOfReferencedProject - ) + (directory, flags) => + watchDirectory( + directory, + fileOrDirectory => { + const fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existence changed, update the sourceFiles cache + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + nextSourceFileVersion(fileOrDirectoryPath); + + const config = parsedConfigs?.get(configPath); + if (!config?.parsedCommandLine) return; + if ( + isIgnoredFileFromWildCardWatching({ + watchedDirPath: toPath(directory), + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + options: config.parsedCommandLine.options, + program: config.parsedCommandLine.fileNames, + currentDirectory, + useCaseSensitiveFileNames, + writeLog, + toPath, + }) + ) return; + + // Reload is pending, do the reload + if (config.reloadLevel !== ConfigFileProgramReloadLevel.Full) { + config.reloadLevel = ConfigFileProgramReloadLevel.Partial; + + // Schedule Update the program + scheduleProgramUpdate(); + } + }, + flags, + commandLine.parsedCommandLine?.watchOptions || watchOptions, + WatchType.WildcardDirectoryOfReferencedProject, + ), ); } else if (commandLine.watchedDirectories) { @@ -1214,7 +1232,7 @@ export function createWatchProgram(host: WatchCompiler configPath, commandLine.parsedCommandLine?.options, commandLine.parsedCommandLine?.watchOptions || watchOptions, - WatchType.ExtendedConfigOfReferencedProject + WatchType.ExtendedConfigOfReferencedProject, ); } } diff --git a/src/compiler/watchUtilities.ts b/src/compiler/watchUtilities.ts index 1c7eb04b1193f..7073986dd5951 100644 --- a/src/compiler/watchUtilities.ts +++ b/src/compiler/watchUtilities.ts @@ -93,20 +93,20 @@ export interface CachedDirectoryStructureHost extends DirectoryStructureHost { clearCache(): void; } -type Canonicalized = string & { __canonicalized: void }; +type Canonicalized = string & { __canonicalized: void; }; interface MutableFileSystemEntries { readonly files: string[]; readonly directories: string[]; - sortedAndCanonicalizedFiles?: SortedArray - sortedAndCanonicalizedDirectories?: SortedArray + sortedAndCanonicalizedFiles?: SortedArray; + sortedAndCanonicalizedDirectories?: SortedArray; } interface SortedAndCanonicalizedMutableFileSystemEntries { readonly files: string[]; readonly directories: string[]; - readonly sortedAndCanonicalizedFiles: SortedArray - readonly sortedAndCanonicalizedDirectories: SortedArray + readonly sortedAndCanonicalizedFiles: SortedArray; + readonly sortedAndCanonicalizedDirectories: SortedArray; } /** @internal */ @@ -129,7 +129,7 @@ export function createCachedDirectoryStructureHost(host: DirectoryStructureHost, addOrDeleteFileOrDirectory, addOrDeleteFile, clearCache, - realpath: host.realpath && realpath + realpath: host.realpath && realpath, }; function toPath(fileName: string) { @@ -161,8 +161,8 @@ export function createCachedDirectoryStructureHost(host: DirectoryStructureHost, function createCachedFileSystemEntries(rootDir: string, rootDirPath: Path) { if (!host.realpath || ensureTrailingDirectorySeparator(toPath(host.realpath(rootDir))) === rootDirPath) { const resultFromHost: MutableFileSystemEntries = { - files: map(host.readDirectory!(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories!(rootDir) || [] + files: map(host.readDirectory!(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories!(rootDir) || [], }; cachedReadDirectoryResult.set(ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); @@ -275,8 +275,8 @@ export function createCachedDirectoryStructureHost(host: DirectoryStructureHost, function getFileSystemEntriesFromHost(dir: string, path: Path): FileSystemEntries { if (rootSymLinkResult && path === rootDirPath) return rootSymLinkResult; const result: FileSystemEntries = { - files: map(host.readDirectory!(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/["*.*"]), getBaseNameOfFileName) || emptyArray, - directories: host.getDirectories!(dir) || emptyArray + files: map(host.readDirectory!(dir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || emptyArray, + directories: host.getDirectories!(dir) || emptyArray, }; if (path === rootDirPath) rootSymLinkResult = result; return result; @@ -313,7 +313,7 @@ export function createCachedDirectoryStructureHost(host: DirectoryStructureHost, const baseName = getBaseNameOfFileName(fileOrDirectory); const fsQueryResult: FileAndDirectoryExistence = { fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) + directoryExists: host.directoryExists(fileOrDirectoryPath), }; if (fsQueryResult.directoryExists || hasEntry(parentResult.sortedAndCanonicalizedDirectories, getCanonicalFileName(baseName))) { // Folder added or removed, clear the cache instead of updating the folder and its structure @@ -324,7 +324,6 @@ export function createCachedDirectoryStructureHost(host: DirectoryStructureHost, updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); } return fsQueryResult; - } function addOrDeleteFile(fileName: string, filePath: Path, eventKind: FileWatcherEventKind) { @@ -369,7 +368,7 @@ export enum ConfigFileProgramReloadLevel { /** Update the file name list from the disk */ Partial, /** Reload completely by re-reading contents of config file from disk and updating program */ - Full + Full, } /** @internal */ @@ -468,8 +467,8 @@ export function updatePackageJsonWatch( newMap, { createNewValue: createPackageJsonWatch, - onDeleteValue: closeFileWatcher - } + onDeleteValue: closeFileWatcher, + }, ); } @@ -495,8 +494,8 @@ export function updateMissingFilePathsWatch( createNewValue: createMissingFileWatch, // Files that are no longer missing (e.g. because they are no longer required) // should no longer be watched. - onDeleteValue: closeFileWatcher - } + onDeleteValue: closeFileWatcher, + }, ); } @@ -517,7 +516,7 @@ export interface WildcardDirectoryWatcher { export function updateWatchingWildcardDirectories( existingWatchedForWildcards: Map, wildcardDirectories: Map, - watchDirectory: (directory: string, flags: WatchDirectoryFlags) => FileWatcher + watchDirectory: (directory: string, flags: WatchDirectoryFlags) => FileWatcher, ) { mutateMap( existingWatchedForWildcards, @@ -528,15 +527,15 @@ export function updateWatchingWildcardDirectories( // Close existing watch thats not needed any more onDeleteValue: closeFileWatcherOf, // Close existing watch that doesnt match in the flags - onExistingValue: updateWildcardDirectoryWatcher - } + onExistingValue: updateWildcardDirectoryWatcher, + }, ); function createWildcardDirectoryWatcher(directory: string, flags: WatchDirectoryFlags): WildcardDirectoryWatcher { // Create new watch and recursive info return { watcher: watchDirectory(directory, flags), - flags + flags, }; } @@ -567,10 +566,17 @@ export interface IsIgnoredFileFromWildCardWatchingInput { } /** @internal */ export function isIgnoredFileFromWildCardWatching({ - watchedDirPath, fileOrDirectory, fileOrDirectoryPath, - configFileName, options, program, extraFileExtensions, - currentDirectory, useCaseSensitiveFileNames, - writeLog, toPath, + watchedDirPath, + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + options, + program, + extraFileExtensions, + currentDirectory, + useCaseSensitiveFileNames, + writeLog, + toPath, }: IsIgnoredFileFromWildCardWatchingInput): boolean { const newPath = removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { @@ -612,8 +618,10 @@ export function isIgnoredFileFromWildCardWatching({ const filePathWithoutExtension = removeFileExtension(fileOrDirectoryPath); const realProgram = isArray(program) ? undefined : isBuilderProgram(program) ? program.getProgramOrUndefined() : program; const builderProgram = !realProgram && !isArray(program) ? program as BuilderProgram : undefined; - if (hasSourceFile((filePathWithoutExtension + Extension.Ts) as Path) || - hasSourceFile((filePathWithoutExtension + Extension.Tsx) as Path)) { + if ( + hasSourceFile((filePathWithoutExtension + Extension.Ts) as Path) || + hasSourceFile((filePathWithoutExtension + Extension.Tsx) as Path) + ) { writeLog(`Project: ${configFileName} Detected output file: ${fileOrDirectory}`); return true; } @@ -623,8 +631,8 @@ export function isIgnoredFileFromWildCardWatching({ return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? - builderProgram.getState().fileInfos.has(file) : - !!find(program as readonly string[], rootFile => toPath(rootFile) === file); + builderProgram.getState().fileInfos.has(file) : + !!find(program as readonly string[], rootFile => toPath(rootFile) === file); } } @@ -645,7 +653,7 @@ export function isEmittedFileOfProgram(program: Program | undefined, file: strin export enum WatchLogLevel { None, TriggerOnly, - Verbose + Verbose, } /** @internal */ @@ -674,13 +682,13 @@ export function getWatchFactory(host: WatchFactoryHost, watchL const triggerInvokingFactory: WatchFactory | undefined = watchLogLevel !== WatchLogLevel.None ? { watchFile: createTriggerLoggingAddWatch("watchFile"), - watchDirectory: createTriggerLoggingAddWatch("watchDirectory") + watchDirectory: createTriggerLoggingAddWatch("watchDirectory"), } : undefined; const factory = watchLogLevel === WatchLogLevel.Verbose ? { watchFile: createFileWatcherWithLogging, - watchDirectory: createDirectoryWatcherWithLogging + watchDirectory: createDirectoryWatcherWithLogging, } : triggerInvokingFactory || plainInvokeFactory; const excludeWatcherFactory = watchLogLevel === WatchLogLevel.Verbose ? @@ -689,7 +697,7 @@ export function getWatchFactory(host: WatchFactoryHost, watchL return { watchFile: createExcludeHandlingAddWatch("watchFile"), - watchDirectory: createExcludeHandlingAddWatch("watchDirectory") + watchDirectory: createExcludeHandlingAddWatch("watchDirectory"), }; function createExcludeHandlingAddWatch>(key: T): WatchFactory[T] { @@ -699,10 +707,10 @@ export function getWatchFactory(host: WatchFactoryHost, watchL flags: PollingInterval | WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, - detailInfo2?: Y + detailInfo2?: Y, ) => !matchesExclude(file, key === "watchFile" ? options?.excludeFiles : options?.excludeDirectories, useCaseSensitiveFileNames(), host.getCurrentDirectory?.() || "") ? - factory[key].call(/*thisArgs*/ undefined, file, cb, flags, options, detailInfo1, detailInfo2) : - excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); + factory[key].call(/*thisArgs*/ undefined, file, cb, flags, options, detailInfo1, detailInfo2) : + excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); } function useCaseSensitiveFileNames() { @@ -716,11 +724,11 @@ export function getWatchFactory(host: WatchFactoryHost, watchL flags: PollingInterval | WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, - detailInfo2?: Y + detailInfo2?: Y, ) { log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); return { - close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`) + close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`), }; } @@ -730,7 +738,7 @@ export function getWatchFactory(host: WatchFactoryHost, watchL flags: PollingInterval, options: WatchOptions | undefined, detailInfo1: X, - detailInfo2?: Y + detailInfo2?: Y, ): FileWatcher { log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); const watcher = triggerInvokingFactory!.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); @@ -738,7 +746,7 @@ export function getWatchFactory(host: WatchFactoryHost, watchL close: () => { log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); watcher.close(); - } + }, }; } @@ -748,7 +756,7 @@ export function getWatchFactory(host: WatchFactoryHost, watchL flags: WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, - detailInfo2?: Y + detailInfo2?: Y, ): FileWatcher { const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(watchInfo); @@ -764,7 +772,7 @@ export function getWatchFactory(host: WatchFactoryHost, watchL watcher.close(); const elapsed = timestamp() - start; log(`Elapsed:: ${elapsed}ms ${watchInfo}`); - } + }, }; } @@ -775,15 +783,23 @@ export function getWatchFactory(host: WatchFactoryHost, watchL flags: PollingInterval | WatchDirectoryFlags, options: WatchOptions | undefined, detailInfo1: X, - detailInfo2?: Y - ) => plainInvokeFactory[key].call(/*thisArgs*/ undefined, file, (...args: any[]) => { - const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== undefined ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; - log(triggerredInfo); - const start = timestamp(); - cb.call(/*thisArg*/ undefined, ...args); - const elapsed = timestamp() - start; - log(`Elapsed:: ${elapsed}ms ${triggerredInfo}`); - }, flags, options, detailInfo1, detailInfo2); + detailInfo2?: Y, + ) => plainInvokeFactory[key].call( + /*thisArgs*/ undefined, + file, + (...args: any[]) => { + const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== undefined ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; + log(triggerredInfo); + const start = timestamp(); + cb.call(/*thisArg*/ undefined, ...args); + const elapsed = timestamp() - start; + log(`Elapsed:: ${elapsed}ms ${triggerredInfo}`); + }, + flags, + options, + detailInfo1, + detailInfo2, + ); } function getWatchInfo(file: string, flags: T, options: WatchOptions | undefined, detailInfo1: X, detailInfo2: Y | undefined, getDetailWatchInfo: GetDetailWatchInfo | undefined) { @@ -797,7 +813,7 @@ export function getFallbackOptions(options: WatchOptions | undefined): WatchOpti return { watchFile: fallbackPolling !== undefined ? fallbackPolling as unknown as WatchFileKind : - WatchFileKind.PriorityPollingInterval + WatchFileKind.PriorityPollingInterval, }; } diff --git a/src/deprecatedCompat/5.0/identifierProperties.ts b/src/deprecatedCompat/5.0/identifierProperties.ts index fbbfc5ee55d15..2815b22775df3 100644 --- a/src/deprecatedCompat/5.0/identifierProperties.ts +++ b/src/deprecatedCompat/5.0/identifierProperties.ts @@ -5,7 +5,9 @@ import { identifierToKeywordKind, NodeFlags, } from "../_namespaces/ts"; -import { deprecate } from "../deprecate"; +import { + deprecate, +} from "../deprecate"; declare module "../../compiler/types" { export interface Identifier { @@ -29,8 +31,8 @@ addObjectAllocatorPatcher(objectAllocator => { since: "5.0", warnAfter: "5.1", errorAfter: "5.2", - message: "Use 'identifierToKeywordKind(identifier)' instead." - }) + message: "Use 'identifierToKeywordKind(identifier)' instead.", + }), }); } @@ -44,8 +46,8 @@ addObjectAllocatorPatcher(objectAllocator => { since: "5.0", warnAfter: "5.1", errorAfter: "5.2", - message: "Use '.parent' or the surrounding context to determine this instead." - }) + message: "Use '.parent' or the surrounding context to determine this instead.", + }), }); } }); diff --git a/src/deprecatedCompat/deprecate.ts b/src/deprecatedCompat/deprecate.ts index cc6b2f31c31ed..0bb11bfd228ab 100644 --- a/src/deprecatedCompat/deprecate.ts +++ b/src/deprecatedCompat/deprecate.ts @@ -45,7 +45,7 @@ function createWarningDeprecation(name: string, errorAfter: Version | undefined, }; } -export function createDeprecation(name: string, options: DeprecationOptions & { error: true }): () => never; +export function createDeprecation(name: string, options: DeprecationOptions & { error: true; }): () => never; export function createDeprecation(name: string, options?: DeprecationOptions): () => void; export function createDeprecation(name: string, options: DeprecationOptions = {}) { const version = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : options.typeScriptVersion ?? getTypeScriptVersion(); diff --git a/src/deprecatedCompat/deprecations.ts b/src/deprecatedCompat/deprecations.ts index 8682631b07830..84310b22a55c2 100644 --- a/src/deprecatedCompat/deprecations.ts +++ b/src/deprecatedCompat/deprecations.ts @@ -3,7 +3,9 @@ import { UnionToIntersection, Version, } from "./_namespaces/ts"; -import { deprecate } from "./deprecate"; +import { + deprecate, +} from "./deprecate"; /** @internal */ export interface DeprecationOptions { @@ -16,7 +18,6 @@ export interface DeprecationOptions { name?: string; } - // The following are deprecations for the public API. Deprecated exports are removed from the compiler itself // and compatible implementations are added here, along with an appropriate deprecation warning using // the `@deprecated` JSDoc tag as well as the `deprecate` API. @@ -145,9 +146,9 @@ export function buildOverload(name: string): OverloadBuilder { bind: binder => ({ finish: () => createOverload(name, overloads, binder), deprecate: deprecations => ({ - finish: () => createOverload(name, overloads, binder, deprecations) - }) - }) - }) + finish: () => createOverload(name, overloads, binder, deprecations), + }), + }), + }), }; } diff --git a/src/executeCommandLine/executeCommandLine.ts b/src/executeCommandLine/executeCommandLine.ts index 660effc571d48..075cbae2c3be8 100644 --- a/src/executeCommandLine/executeCommandLine.ts +++ b/src/executeCommandLine/executeCommandLine.ts @@ -149,7 +149,7 @@ function getCountKey(program: Program, file: SourceFile) { function updateReportDiagnostic( sys: System, existing: DiagnosticReporter, - options: CompilerOptions | BuildOptions + options: CompilerOptions | BuildOptions, ): DiagnosticReporter { return shouldBePretty(sys, options) ? createDiagnosticReporter(sys, /*pretty*/ true) : @@ -185,7 +185,7 @@ function createColors(sys: System) { bold: (str: string) => str, blue: (str: string) => str, blueBackground: (str: string) => str, - brightWhite: (str: string) => str + brightWhite: (str: string) => str, }; } @@ -226,7 +226,7 @@ function createColors(sys: System) { bold, blue, brightWhite, - blueBackground + blueBackground, }; } @@ -249,13 +249,12 @@ function generateOptionOutput(sys: System, option: CommandLineOption, rightAlign // value type and possible value const valueCandidates = getValueCandidate(option); - const defaultValueDescription = - typeof option.defaultValueDescription === "object" - ? getDiagnosticText(option.defaultValueDescription) - : formatDefaultValue( - option.defaultValueDescription, - option.type === "list" || option.type === "listOrElement" ? option.element.type : option.type - ); + const defaultValueDescription = typeof option.defaultValueDescription === "object" + ? getDiagnosticText(option.defaultValueDescription) + : formatDefaultValue( + option.defaultValueDescription, + option.type === "list" || option.type === "listOrElement" ? option.element.type : option.type, + ); const terminalWidth = sys.getWidthOfTerminal?.() ?? 0; // Note: child_process might return `terminalWidth` as undefined. @@ -300,14 +299,14 @@ function generateOptionOutput(sys: System, option: CommandLineOption, rightAlign function formatDefaultValue( defaultValue: CommandLineOption["defaultValueDescription"], - type: CommandLineOption["type"] + type: CommandLineOption["type"], ) { return defaultValue !== undefined && typeof type === "object" // e.g. ScriptTarget.ES2015 -> "es6/es2015" ? arrayFrom(type.entries()) - .filter(([, value]) => value === defaultValue) - .map(([name]) => name) - .join("/") + .filter(([, value]) => value === defaultValue) + .map(([name]) => name) + .join("/") : String(defaultValue); } @@ -361,7 +360,7 @@ function generateOptionOutput(sys: System, option: CommandLineOption, rightAlign return { valueType: getValueType(option), - possibleValues: getPossibleValues(option) + possibleValues: getPossibleValues(option), }; function getValueType(option: CommandLineOption) { @@ -396,7 +395,7 @@ function generateOptionOutput(sys: System, option: CommandLineOption, rightAlign default: // Map // Group synonyms: es6/es2015 - const inverted: { [value: string]: string[] } = {}; + const inverted: { [value: string]: string[]; } = {}; option.type.forEach((value, name) => { (inverted[value] ||= []).push(name); }); @@ -469,7 +468,7 @@ function generateSectionOptionsOutput(sys: System, sectionName: string, options: function printEasyHelp(sys: System, simpleOptions: readonly CommandLineOption[]) { const colors = createColors(sys); - let output: string[] = [...getHeader(sys,`${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; + let output: string[] = [...getHeader(sys, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; output.push(colors.bold(getDiagnosticText(Diagnostics.COMMON_COMMANDS)) + sys.newLine + sys.newLine); example("tsc", Diagnostics.Compiles_the_current_project_tsconfig_json_in_the_working_directory); @@ -486,7 +485,7 @@ function printEasyHelp(sys: System, simpleOptions: readonly CommandLineOption[]) output = [ ...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.COMMAND_LINE_FLAGS), cliCommands, /*subCategory*/ false, /*beforeOptionsDescription*/ undefined, /*afterOptionsDescription*/ undefined), - ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.COMMON_COMPILER_OPTIONS), configOpts, /*subCategory*/ false, /*beforeOptionsDescription*/ undefined, formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc")) + ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.COMMON_COMPILER_OPTIONS), configOpts, /*subCategory*/ false, /*beforeOptionsDescription*/ undefined, formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc")), ]; for (const line of output) { @@ -503,7 +502,7 @@ function printEasyHelp(sys: System, simpleOptions: readonly CommandLineOption[]) } function printAllHelp(sys: System, compilerOptions: readonly CommandLineOption[], buildOptions: readonly CommandLineOption[], watchOptions: readonly CommandLineOption[]) { - let output: string[] = [...getHeader(sys,`${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; + let output: string[] = [...getHeader(sys, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.ALL_COMPILER_OPTIONS), compilerOptions, /*subCategory*/ true, /*beforeOptionsDescription*/ undefined, formatMessage(Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsc"))]; output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.WATCH_OPTIONS), watchOptions, /*subCategory*/ false, getDiagnosticText(Diagnostics.Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_config_watch_mode_with_Colon))]; output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.BUILD_OPTIONS), buildOptions, /*subCategory*/ false, formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds"))]; @@ -513,7 +512,7 @@ function printAllHelp(sys: System, compilerOptions: readonly CommandLineOption[] } function printBuildHelp(sys: System, buildOptions: readonly CommandLineOption[]) { - let output: string[] = [...getHeader(sys,`${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; + let output: string[] = [...getHeader(sys, `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)]; output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.BUILD_OPTIONS), buildOptions, /*subCategory*/ false, formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds"))]; for (const line of output) { sys.write(line); @@ -637,7 +636,7 @@ function executeCommandLineWorker( const currentDirectory = sys.getCurrentDirectory(); const commandLineOptions = convertToOptionsWithAbsolutePaths( commandLine.options, - fileName => getNormalizedAbsolutePath(fileName, currentDirectory) + fileName => getNormalizedAbsolutePath(fileName, currentDirectory), ); if (configFileName) { const extendedConfigCache = new Map(); @@ -647,7 +646,7 @@ function executeCommandLineWorker( reportDiagnostic = updateReportDiagnostic( sys, reportDiagnostic, - configParseResult.options + configParseResult.options, ); configParseResult.errors.forEach(reportDiagnostic); return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); @@ -659,7 +658,7 @@ function executeCommandLineWorker( reportDiagnostic = updateReportDiagnostic( sys, reportDiagnostic, - configParseResult.options + configParseResult.options, ); if (isWatchSet(configParseResult.options)) { if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) return; @@ -678,7 +677,7 @@ function executeCommandLineWorker( sys, cb, reportDiagnostic, - configParseResult + configParseResult, ); } else { @@ -686,7 +685,7 @@ function executeCommandLineWorker( sys, cb, reportDiagnostic, - configParseResult + configParseResult, ); } } @@ -699,7 +698,7 @@ function executeCommandLineWorker( reportDiagnostic = updateReportDiagnostic( sys, reportDiagnostic, - commandLineOptions + commandLineOptions, ); if (isWatchSet(commandLineOptions)) { if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) return; @@ -717,7 +716,7 @@ function executeCommandLineWorker( sys, cb, reportDiagnostic, - { ...commandLine, options: commandLineOptions } + { ...commandLine, options: commandLineOptions }, ); } else { @@ -725,7 +724,7 @@ function executeCommandLineWorker( sys, cb, reportDiagnostic, - { ...commandLine, options: commandLineOptions } + { ...commandLine, options: commandLineOptions }, ); } } @@ -748,14 +747,15 @@ export function executeCommandLine( if (isBuild(commandLineArgs)) { const { buildOptions, watchOptions, projects, errors } = parseBuildCommand(commandLineArgs.slice(1)); if (buildOptions.generateCpuProfile && system.enableCPUProfiler) { - system.enableCPUProfiler(buildOptions.generateCpuProfile, () => performBuild( - system, - cb, - buildOptions, - watchOptions, - projects, - errors - )); + system.enableCPUProfiler(buildOptions.generateCpuProfile, () => + performBuild( + system, + cb, + buildOptions, + watchOptions, + projects, + errors, + )); } else { return performBuild( @@ -764,18 +764,19 @@ export function executeCommandLine( buildOptions, watchOptions, projects, - errors + errors, ); } } const commandLine = parseCommandLine(commandLineArgs, path => system.readFile(path)); if (commandLine.options.generateCpuProfile && system.enableCPUProfiler) { - system.enableCPUProfiler(commandLine.options.generateCpuProfile, () => executeCommandLineWorker( - system, - cb, - commandLine, - )); + system.enableCPUProfiler(commandLine.options.generateCpuProfile, () => + executeCommandLineWorker( + system, + cb, + commandLine, + )); } else { return executeCommandLineWorker(system, cb, commandLine); @@ -797,13 +798,13 @@ function performBuild( buildOptions: BuildOptions, watchOptions: WatchOptions | undefined, projects: string[], - errors: Diagnostic[] + errors: Diagnostic[], ) { // Update to pretty if host supports it const reportDiagnostic = updateReportDiagnostic( sys, createDiagnosticReporter(sys), - buildOptions + buildOptions, ); if (buildOptions.locale) { @@ -839,7 +840,7 @@ function performBuild( /*createProgram*/ undefined, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty(sys, buildOptions)), - createWatchStatusReporter(sys, buildOptions) + createWatchStatusReporter(sys, buildOptions), ); const solutionPerformance = enableSolutionPerformance(sys, buildOptions); updateSolutionBuilderHost(sys, cb, buildHost, solutionPerformance); @@ -847,10 +848,12 @@ function performBuild( let reportBuildStatistics = false; buildHost.onWatchStatusChange = (d, newLine, options, errorCount) => { onWatchStatusChange?.(d, newLine, options, errorCount); - if (reportBuildStatistics && ( - d.code === Diagnostics.Found_0_errors_Watching_for_file_changes.code || - d.code === Diagnostics.Found_1_error_Watching_for_file_changes.code - )) { + if ( + reportBuildStatistics && ( + d.code === Diagnostics.Found_0_errors_Watching_for_file_changes.code || + d.code === Diagnostics.Found_1_error_Watching_for_file_changes.code + ) + ) { reportSolutionBuilderTimes(builder, solutionPerformance); } }; @@ -866,7 +869,7 @@ function performBuild( /*createProgram*/ undefined, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty(sys, buildOptions)), - createReportErrorSummary(sys, buildOptions) + createReportErrorSummary(sys, buildOptions), ); const solutionPerformance = enableSolutionPerformance(sys, buildOptions); updateSolutionBuilderHost(sys, cb, buildHost, solutionPerformance); @@ -887,7 +890,7 @@ function performCompilation( sys: System, cb: ExecuteCommandLineCallbacks, reportDiagnostic: DiagnosticReporter, - config: ParsedCommandLine + config: ParsedCommandLine, ) { const { fileNames, options, projectReferences } = config; const host = createCompilerHostWorker(options, /*setParentNodes*/ undefined, sys); @@ -901,14 +904,14 @@ function performCompilation( options, projectReferences, host, - configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config) + configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config), }; const program = createProgram(programOptions); const exitStatus = emitFilesAndReportErrorsAndGetExitStatus( program, reportDiagnostic, s => sys.write(s + sys.newLine), - createReportErrorSummary(sys, options) + createReportErrorSummary(sys, options), ); reportStatistics(sys, program, /*solutionPerformance*/ undefined); cb(program); @@ -919,7 +922,7 @@ function performIncrementalCompilation( sys: System, cb: ExecuteCommandLineCallbacks, reportDiagnostic: DiagnosticReporter, - config: ParsedCommandLine + config: ParsedCommandLine, ) { const { options, fileNames, projectReferences } = config; enableStatisticsAndTracing(sys, options, /*isBuildMode*/ false); @@ -936,7 +939,7 @@ function performIncrementalCompilation( afterProgramEmitAndDiagnostics: builderProgram => { reportStatistics(sys, builderProgram.getProgram(), /*solutionPerformance*/ undefined); cb(builderProgram); - } + }, }); return sys.exit(exitStatus); } @@ -1003,7 +1006,7 @@ function createWatchOfConfigFile( watchOptionsToExtend, system, reportDiagnostic, - reportWatchStatus: createWatchStatusReporter(system, configParseResult.options) + reportWatchStatus: createWatchStatusReporter(system, configParseResult.options), }); updateWatchCompilationHost(system, cb, watchCompilerHost); watchCompilerHost.configFileParsingResult = configParseResult; @@ -1025,7 +1028,7 @@ function createWatchOfFilesAndCompilerOptions( watchOptions, system, reportDiagnostic, - reportWatchStatus: createWatchStatusReporter(system, options) + reportWatchStatus: createWatchStatusReporter(system, options), }); updateWatchCompilationHost(system, cb, watchCompilerHost); return createWatchProgram(watchCompilerHost); @@ -1074,7 +1077,8 @@ function createSolutionPerfomrance(): SolutionPerformance { function reportSolutionBuilderTimes( builder: SolutionBuilder, - solutionPerformance: SolutionPerformance | undefined) { + solutionPerformance: SolutionPerformance | undefined, +) { if (!solutionPerformance) return; if (!performance.isEnabled()) { @@ -1128,8 +1132,7 @@ function enableStatisticsAndTracing(system: System, compilerOptions: CompilerOpt } if (canTrace(system, compilerOptions)) { - startTracing(isBuildMode ? "build" : "project", - compilerOptions.generateTrace!, compilerOptions.configFilePath); + startTracing(isBuildMode ? "build" : "project", compilerOptions.generateTrace!, compilerOptions.configFilePath); } } @@ -1280,7 +1283,7 @@ function writeConfigFile( sys: System, reportDiagnostic: DiagnosticReporter, options: CompilerOptions, - fileNames: string[] + fileNames: string[], ) { const currentDirectory = sys.getCurrentDirectory(); const file = normalizePath(combinePaths(currentDirectory, "tsconfig.json")); @@ -1289,7 +1292,7 @@ function writeConfigFile( } else { sys.writeFile(file, generateTSConfig(options, fileNames, sys.newLine)); - const output: string[] = [sys.newLine, ...getHeader(sys,"Created a new tsconfig.json with:")]; + const output: string[] = [sys.newLine, ...getHeader(sys, "Created a new tsconfig.json with:")]; output.push(getCompilerOptionsDiffValue(options, sys.newLine) + sys.newLine + sys.newLine); output.push(`You can learn more at https://aka.ms/tsconfig` + sys.newLine); for (const line of output) { diff --git a/src/harness/client.ts b/src/harness/client.ts index 76004edf58f10..6f3a3cf9bbac5 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -149,7 +149,7 @@ export class SessionClient implements LanguageService { const lineOffset = computeLineAndCharacterOfPosition(this.getLineMap(fileName), position); return { line: lineOffset.line + 1, - offset: lineOffset.character + 1 + offset: lineOffset.character + 1, }; } @@ -162,7 +162,7 @@ export class SessionClient implements LanguageService { seq: this.sequence, type: "request", arguments: args, - command + command, }; this.sequence++; @@ -263,7 +263,7 @@ export class SessionClient implements LanguageService { textSpan: this.decodeSpan(body, fileName), displayParts: [{ kind: "text", text: body.displayString }], documentation: typeof body.documentation === "string" ? [{ kind: "text", text: body.documentation }] : body.documentation, - tags: this.decodeLinkDisplayParts(body.tags) + tags: this.decodeLinkDisplayParts(body.tags), }; } @@ -275,7 +275,7 @@ export class SessionClient implements LanguageService { return { configFileName: response.body!.configFileName, // TODO: GH#18217 - fileNames: response.body!.fileNames + fileNames: response.body!.fileNames, }; } @@ -296,8 +296,8 @@ export class SessionClient implements LanguageService { return res; } - return entry as { name: string, kind: ScriptElementKind, kindModifiers: string, sortText: string }; // TODO: GH#18217 - }) + return entry as { name: string; kind: ScriptElementKind; kindModifiers: string; sortText: string; }; // TODO: GH#18217 + }), }; } @@ -317,7 +317,7 @@ export class SessionClient implements LanguageService { getNavigateToItems(searchValue: string): NavigateToItem[] { const args: protocol.NavtoRequestArgs = { searchValue, - file: this.host.getScriptFileNames()[0] + file: this.host.getScriptFileNames()[0], }; const request = this.processRequest(protocol.CommandTypes.Navto, args); @@ -339,7 +339,6 @@ export class SessionClient implements LanguageService { getFormattingEditsForRange(file: string, start: number, end: number, _options: FormatCodeOptions): TextChange[] { const args: protocol.FormatRequestArgs = this.createFileLocationRequestArgsWithEndLineAndOffset(file, start, end); - // TODO: handle FormatCodeOptions const request = this.processRequest(protocol.CommandTypes.Format, args); const response = this.processResponse(request); @@ -373,7 +372,7 @@ export class SessionClient implements LanguageService { fileName: entry.file, textSpan: this.decodeSpan(entry), kind: ScriptElementKind.unknown, - name: "" + name: "", })); } @@ -394,7 +393,7 @@ export class SessionClient implements LanguageService { name: "", unverified: entry.unverified, })), - textSpan: this.decodeSpan(body.textSpan, request.arguments.file) + textSpan: this.decodeSpan(body.textSpan, request.arguments.file), }; } @@ -410,7 +409,7 @@ export class SessionClient implements LanguageService { fileName: entry.file, textSpan: this.decodeSpan(entry), kind: ScriptElementKind.unknown, - name: "" + name: "", })); } @@ -441,7 +440,7 @@ export class SessionClient implements LanguageService { fileName: entry.file, textSpan: this.decodeSpan(entry), kind: ScriptElementKind.unknown, - displayParts: [] + displayParts: [], })); } @@ -501,8 +500,7 @@ export class SessionClient implements LanguageService { const fakeSourceFile = { fileName: file, text: sourceText } as SourceFile; // Warning! This is a huge lie! return (response.body as protocol.DiagnosticWithLinePosition[]).map((entry): DiagnosticWithLocation => { - const category = firstDefined(Object.keys(DiagnosticCategory), id => - isString(id) && entry.category === id.toLowerCase() ? (DiagnosticCategory as any)[id] : undefined); + const category = firstDefined(Object.keys(DiagnosticCategory), id => isString(id) && entry.category === id.toLowerCase() ? (DiagnosticCategory as any)[id] : undefined); return { file: fakeSourceFile, start: entry.start, @@ -537,7 +535,7 @@ export class SessionClient implements LanguageService { ...(contextStart !== undefined ? { contextSpan: this.decodeSpan({ start: contextStart, end: contextEnd! }, fileName) } : undefined), - ...prefixSuffixText + ...prefixSuffixText, }); } } @@ -571,25 +569,27 @@ export class SessionClient implements LanguageService { } findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, preferences: UserPreferences | boolean | undefined): RenameLocation[] { - if (!this.lastRenameEntry || + if ( + !this.lastRenameEntry || this.lastRenameEntry.inputs.fileName !== fileName || this.lastRenameEntry.inputs.position !== position || this.lastRenameEntry.inputs.findInStrings !== findInStrings || - this.lastRenameEntry.inputs.findInComments !== findInComments) { + this.lastRenameEntry.inputs.findInComments !== findInComments + ) { const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences?.providePrefixAndSuffixTextForRename; const quotePreference = typeof preferences === "boolean" ? undefined : preferences?.quotePreference; if (providePrefixAndSuffixTextForRename !== undefined || quotePreference !== undefined) { // User preferences have to be set through the `Configure` command this.configure({ providePrefixAndSuffixTextForRename, quotePreference }); // Options argument is not used, so don't pass in options - this.getRenameInfo(fileName, position, /*preferences*/{}, findInStrings, findInComments); + this.getRenameInfo(fileName, position, /*preferences*/ {}, findInStrings, findInComments); // Restore previous user preferences if (this.preferences) { this.configure(this.preferences); } } else { - this.getRenameInfo(fileName, position, /*preferences*/{}, findInStrings, findInComments); + this.getRenameInfo(fileName, position, /*preferences*/ {}, findInStrings, findInComments); } } @@ -609,7 +609,7 @@ export class SessionClient implements LanguageService { childItems: this.decodeNavigationBarItems(item.childItems, fileName, lineMap), indent: item.indent, bolded: false, - grayed: false + grayed: false, })); } @@ -628,7 +628,7 @@ export class SessionClient implements LanguageService { kindModifiers: tree.kindModifiers, spans: tree.spans.map(span => this.decodeSpan(span, fileName, lineMap)), nameSpan: tree.nameSpan && this.decodeSpan(tree.nameSpan, fileName, lineMap), - childItems: map(tree.childItems, item => this.decodeNavigationTree(item, fileName, lineMap)) + childItems: map(tree.childItems, item => this.decodeNavigationTree(item, fileName, lineMap)), }; } @@ -640,9 +640,9 @@ export class SessionClient implements LanguageService { return this.decodeNavigationTree(response.body!, file, lineMap); // TODO: GH#18217 } - private decodeSpan(span: protocol.TextSpan & { file: string }): TextSpan; + private decodeSpan(span: protocol.TextSpan & { file: string; }): TextSpan; private decodeSpan(span: protocol.TextSpan, fileName: string, lineMap?: number[]): TextSpan; - private decodeSpan(span: protocol.TextSpan & { file: string }, fileName?: string, lineMap?: number[]): TextSpan { + private decodeSpan(span: protocol.TextSpan & { file: string; }, fileName?: string, lineMap?: number[]): TextSpan { if (span.start.line === 1 && span.start.offset === 1 && span.end.line === 1 && span.end.offset === 1) { return { start: 0, length: 0 }; } @@ -650,14 +650,17 @@ export class SessionClient implements LanguageService { lineMap = lineMap || this.getLineMap(fileName); return createTextSpanFromBounds( this.lineOffsetToPosition(fileName, span.start, lineMap), - this.lineOffsetToPosition(fileName, span.end, lineMap)); + this.lineOffsetToPosition(fileName, span.end, lineMap), + ); } private decodeLinkDisplayParts(tags: (protocol.JSDocTagInfo | JSDocTagInfo)[]): JSDocTagInfo[] { - return tags.map(tag => typeof tag.text === "string" ? { - ...tag, - text: [textPart(tag.text)] - } : (tag as JSDocTagInfo)); + return tags.map(tag => + typeof tag.text === "string" ? { + ...tag, + text: [textPart(tag.text)], + } : (tag as JSDocTagInfo) + ); } getNameOrDottedNameSpan(_fileName: string, _startPos: number, _endPos: number): TextSpan { @@ -696,7 +699,7 @@ export class SessionClient implements LanguageService { fileName: item.file, highlightSpans: item.highlightSpans.map(span => ({ textSpan: this.decodeSpan(span, item.file), - kind: span.kind + kind: span.kind, })), })); } @@ -710,7 +713,7 @@ export class SessionClient implements LanguageService { hintSpan: this.decodeSpan(item.hintSpan, file), bannerText: item.bannerText, autoCollapse: item.autoCollapse, - kind: item.kind + kind: item.kind, })); } @@ -745,7 +748,7 @@ export class SessionClient implements LanguageService { const response = this.processResponse(request); return response.body!.map(({ fixName, description, changes, commands, fixId, fixAllDescription }) => // TODO: GH#18217 - ({ fixName, description, changes: this.convertChanges(changes, file), commands: commands as CodeActionCommand[], fixId, fixAllDescription })); + ({ fixName, description, changes: this.convertChanges(changes, file), commands: commands as CodeActionCommand[], fixId, fixAllDescription })); } getCombinedCodeFix = notImplemented; @@ -772,7 +775,7 @@ export class SessionClient implements LanguageService { start: this.lineOffsetToPosition(span.file, span.start), length: this.lineOffsetToPosition(span.file, span.end) - this.lineOffsetToPosition(span.file, span.start), }, - file: span && span.file + file: span && span.file, })), }); }); @@ -795,7 +798,7 @@ export class SessionClient implements LanguageService { return { file, startLine, startOffset, endLine, endOffset }; } - private createFileLocationRequestArgsWithEndLineAndOffset(file: string, start: number, end: number): protocol.FileLocationRequestArgs & { endLine: number, endOffset: number } { + private createFileLocationRequestArgsWithEndLineAndOffset(file: string, start: number, end: number): protocol.FileLocationRequestArgs & { endLine: number; endOffset: number; } { const { line, offset } = this.positionToOneBasedLineOffset(file, start); const { line: endLine, offset: endOffset } = this.positionToOneBasedLineOffset(file, end); return { file, line, offset, endLine, endOffset }; @@ -807,7 +810,8 @@ export class SessionClient implements LanguageService { preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string, - includeInteractiveActions?: boolean): ApplicableRefactorInfo[] { + includeInteractiveActions?: boolean, + ): ApplicableRefactorInfo[] { if (preferences) { // Temporarily set preferences this.configure(preferences); } @@ -828,7 +832,7 @@ export class SessionClient implements LanguageService { const request = this.processRequest(protocol.CommandTypes.GetMoveToRefactoringFileSuggestions, args); const response = this.processResponse(request); - return { newFileName: response.body?.newFileName, files:response.body?.files }!; + return { newFileName: response.body?.newFileName, files: response.body?.files }!; } getEditsForRefactor( @@ -838,12 +842,12 @@ export class SessionClient implements LanguageService { refactorName: string, actionName: string, preferences: UserPreferences | undefined, - interactiveRefactorArguments?: InteractiveRefactorArguments): RefactorEditInfo { + interactiveRefactorArguments?: InteractiveRefactorArguments, + ): RefactorEditInfo { if (preferences) { // Temporarily set preferences this.configure(preferences); } - const args = - this.createFileLocationOrRangeRequestArgs(positionOrRange, fileName) as protocol.GetEditsForRefactorRequestArgs; + const args = this.createFileLocationOrRangeRequestArgs(positionOrRange, fileName) as protocol.GetEditsForRefactorRequestArgs; args.refactor = refactorName; args.action = actionName; args.interactiveRefactorArguments = interactiveRefactorArguments; @@ -888,7 +892,7 @@ export class SessionClient implements LanguageService { const fileName = edit.fileName; return { fileName, - textChanges: edit.textChanges.map(t => this.convertTextChangeToCodeEdit(t, fileName)) + textChanges: edit.textChanges.map(t => this.convertTextChangeToCodeEdit(t, fileName)), }; }); } @@ -896,14 +900,14 @@ export class SessionClient implements LanguageService { private convertChanges(changes: protocol.FileCodeEdits[], fileName: string): FileTextChanges[] { return changes.map(change => ({ fileName: change.fileName, - textChanges: change.textChanges.map(textChange => this.convertTextChangeToCodeEdit(textChange, fileName)) + textChanges: change.textChanges.map(textChange => this.convertTextChangeToCodeEdit(textChange, fileName)), })); } convertTextChangeToCodeEdit(change: protocol.CodeEdit, fileName: string): TextChange { return { span: this.decodeSpan(change, fileName), - newText: change.newText ? change.newText : "" + newText: change.newText ? change.newText : "", }; } @@ -951,7 +955,7 @@ export class SessionClient implements LanguageService { kindModifiers: item.kindModifiers, containerName: item.containerName, span: this.decodeSpan(item.span, item.file), - selectionSpan: this.decodeSpan(item.selectionSpan, item.file) + selectionSpan: this.decodeSpan(item.selectionSpan, item.file), }; } @@ -965,7 +969,7 @@ export class SessionClient implements LanguageService { private convertCallHierarchyIncomingCall(item: protocol.CallHierarchyIncomingCall): CallHierarchyIncomingCall { return { from: this.convertCallHierarchyItem(item.from), - fromSpans: item.fromSpans.map(span => this.decodeSpan(span, item.from.file)) + fromSpans: item.fromSpans.map(span => this.decodeSpan(span, item.from.file)), }; } @@ -979,7 +983,7 @@ export class SessionClient implements LanguageService { private convertCallHierarchyOutgoingCall(file: string, item: protocol.CallHierarchyOutgoingCall): CallHierarchyOutgoingCall { return { to: this.convertCallHierarchyItem(item.to), - fromSpans: item.fromSpans.map(span => this.decodeSpan(span, file)) + fromSpans: item.fromSpans.map(span => this.decodeSpan(span, file)), }; } diff --git a/src/harness/collectionsImpl.ts b/src/harness/collectionsImpl.ts index cc43361489205..9f3b88cfb13ac 100644 --- a/src/harness/collectionsImpl.ts +++ b/src/harness/collectionsImpl.ts @@ -44,9 +44,9 @@ export class SortedMap { return index >= 0 ? this._values[index] : undefined; } - public getEntry(key: K): [ K, V ] | undefined { + public getEntry(key: K): [K, V] | undefined { const index = ts.binarySearch(this._keys, key, ts.identity, this._comparer); - return index >= 0 ? [ this._keys[index], this._values[index] ] : undefined; + return index >= 0 ? [this._keys[index], this._values[index]] : undefined; } public set(key: K, value: V) { @@ -112,7 +112,7 @@ export class SortedMap { } } - public * keys() { + public *keys() { const keys = this._keys; const indices = this.getIterationOrder(); const version = this._version; @@ -134,7 +134,7 @@ export class SortedMap { } } - public * values() { + public *values() { const values = this._values; const indices = this.getIterationOrder(); const version = this._version; @@ -156,7 +156,7 @@ export class SortedMap { } } - public * entries() { + public *entries() { const keys = this._keys; const values = this._values; const indices = this.getIterationOrder(); @@ -230,7 +230,7 @@ function insertAt(array: T[], index: number, value: T): void { export class Metadata { private static readonly _undefinedValue = {}; private _parent: Metadata | undefined; - private _map: { [key: string]: any }; + private _map: { [key: string]: any; }; private _version = 0; private _size = -1; private _parentVersion: number | undefined; diff --git a/src/harness/compilerImpl.ts b/src/harness/compilerImpl.ts index f60a429fc567f..1a37603da1e41 100644 --- a/src/harness/compilerImpl.ts +++ b/src/harness/compilerImpl.ts @@ -22,7 +22,7 @@ export function readProject(host: fakes.ParseConfigHost, project: string | undef } else { [project] = host.vfs.scanSync(".", "ancestors-or-self", { - accept: (path, stats) => stats.isFile() && host.vfs.stringComparer(vpath.basename(path), "tsconfig.json") === 0 + accept: (path, stats) => stats.isFile() && host.vfs.stringComparer(vpath.basename(path), "tsconfig.json") === 0, }); } @@ -109,7 +109,7 @@ export class CompilationResult { inputs, js: js.get(outFile), dts: dts.get(vpath.changeExtension(outFile, ".d.ts")), - map: maps.get(outFile + ".map") + map: maps.get(outFile + ".map"), }; if (outputs.js) this._inputsAndOutputs.set(outputs.js.file, outputs); @@ -131,7 +131,7 @@ export class CompilationResult { inputs: [input], js: js.get(this.getOutputPath(sourceFile.fileName, extname)), dts: dts.get(this.getOutputPath(sourceFile.fileName, ts.getDeclarationEmitExtensionForPath(sourceFile.fileName))), - map: maps.get(this.getOutputPath(sourceFile.fileName, extname + ".map")) + map: maps.get(this.getOutputPath(sourceFile.fileName, extname + ".map")), }; this._inputsAndOutputs.set(sourceFile.fileName, outputs); @@ -273,22 +273,23 @@ export function compileFiles(host: fakes.CompilerHost, rootFiles: string[] | und const postErrors = ts.getPreEmitDiagnostics(program); const longerErrors = ts.length(preErrors) > postErrors.length ? preErrors : postErrors; const shorterErrors = longerErrors === preErrors ? postErrors : preErrors; - const errors = preErrors && (preErrors.length !== postErrors.length) ? [...shorterErrors!, + const errors = preErrors && (preErrors.length !== postErrors.length) ? [ + ...shorterErrors!, ts.addRelatedInfo( ts.createCompilerDiagnostic({ category: ts.DiagnosticCategory.Error, code: -1, key: "-1", - message: `Pre-emit (${preErrors.length}) and post-emit (${postErrors.length}) diagnostic counts do not match! This can indicate that a semantic _error_ was added by the emit resolver - such an error may not be reflected on the command line or in the editor, but may be captured in a baseline here!` + message: `Pre-emit (${preErrors.length}) and post-emit (${postErrors.length}) diagnostic counts do not match! This can indicate that a semantic _error_ was added by the emit resolver - such an error may not be reflected on the command line or in the editor, but may be captured in a baseline here!`, }), ts.createCompilerDiagnostic({ category: ts.DiagnosticCategory.Error, code: -1, key: "-1", - message: `The excess diagnostics are:` + message: `The excess diagnostics are:`, }), - ...ts.filter(longerErrors!, p => !ts.some(shorterErrors, p2 => ts.compareDiagnostics(p, p2) === ts.Comparison.EqualTo)) - ) + ...ts.filter(longerErrors!, p => !ts.some(shorterErrors, p2 => ts.compareDiagnostics(p, p2) === ts.Comparison.EqualTo)), + ), ] : postErrors; return new CompilationResult(host, compilerOptions, program, emitResult, errors); } diff --git a/src/harness/documentsUtil.ts b/src/harness/documentsUtil.ts index fa00ff2d06213..c538ae3931ec9 100644 --- a/src/harness/documentsUtil.ts +++ b/src/harness/documentsUtil.ts @@ -27,7 +27,8 @@ export class TextDocument { file.unitName, file.content, file.fileOptions && Object.keys(file.fileOptions) - .reduce((meta, key) => meta.set(key, file.fileOptions[key]), new Map())); + .reduce((meta, key) => meta.set(key, file.fileOptions[key]), new Map()), + ); } public asTestFile() { @@ -35,7 +36,7 @@ export class TextDocument { unitName: this.file, content: this.text, fileOptions: ts.arrayFrom(this.meta) - .reduce((obj, [key, value]) => (obj[key] = value, obj), {} as Record) + .reduce((obj, [key, value]) => (obj[key] = value, obj), {} as Record), }); } } diff --git a/src/harness/evaluatorImpl.ts b/src/harness/evaluatorImpl.ts index 00a4d80e90c73..c6edef27fb07c 100644 --- a/src/harness/evaluatorImpl.ts +++ b/src/harness/evaluatorImpl.ts @@ -33,23 +33,26 @@ for (const symbolName of symbolNames) { } } -export function evaluateTypeScript(source: string | { files: vfs.FileSet, rootFiles: string[], main: string }, options?: ts.CompilerOptions, globals?: Record) { +export function evaluateTypeScript(source: string | { files: vfs.FileSet; rootFiles: string[]; main: string; }, options?: ts.CompilerOptions, globals?: Record) { if (typeof source === "string") source = { files: { [sourceFile]: source }, rootFiles: [sourceFile], main: sourceFile }; const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { files: source.files }); const compilerOptions: ts.CompilerOptions = { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS, lib: ["lib.esnext.d.ts", "lib.dom.d.ts"], - ...options + ...options, }; const host = new fakes.CompilerHost(fs, compilerOptions); const result = compiler.compileFiles(host, source.rootFiles, compilerOptions); if (ts.some(result.diagnostics)) { - assert.ok(/*value*/ false, "Syntax error in evaluation source text:\n" + ts.formatDiagnostics(result.diagnostics, { - getCanonicalFileName: file => file, - getCurrentDirectory: () => "", - getNewLine: () => "\n" - })); + assert.ok( + /*value*/ false, + "Syntax error in evaluation source text:\n" + ts.formatDiagnostics(result.diagnostics, { + getCanonicalFileName: file => file, + getCurrentDirectory: () => "", + getNewLine: () => "\n", + }), + ); } const output = result.getOutput(source.main, "js")!; @@ -256,7 +259,7 @@ class SystemLoader extends Loader { dependers: [], setters: [], hasExports: false, - state: SystemModuleState.Uninstantiated + state: SystemModuleState.Uninstantiated, }; } @@ -294,7 +297,7 @@ class SystemLoader extends Loader { } } const localSystem: SystemGlobal = { - register: (dependencies, declare) => this.instantiateModule(module, dependencies, declare) + register: (dependencies, declare) => this.instantiateModule(module, dependencies, declare), }; const evaluateText = `(function (System, ${globalNames.join(", ")}) { ${text}\n})`; try { @@ -330,10 +333,12 @@ class SystemLoader extends Loader { } const context: SystemModuleContext = { - import: (_id) => { throw new Error("Dynamic import not implemented."); }, + import: _id => { + throw new Error("Dynamic import not implemented."); + }, meta: { - url: ts.isUrl(module.file) ? module.file : `file:///${ts.normalizeSlashes(module.file).replace(/^\//, "").split("/").map(encodeURIComponent).join("/")}` - } + url: ts.isUrl(module.file) ? module.file : `file:///${ts.normalizeSlashes(module.file).replace(/^\//, "").split("/").map(encodeURIComponent).join("/")}`, + }, }; module.requestedDependencies = dependencies; diff --git a/src/harness/fakesHosts.ts b/src/harness/fakesHosts.ts index 6155a2622b13f..390d69d93ce67 100644 --- a/src/harness/fakesHosts.ts +++ b/src/harness/fakesHosts.ts @@ -386,9 +386,11 @@ export class CompilerHost implements ts.CompilerHost { while (fs.shadowRoot) { try { const shadowRootStats = fs.shadowRoot.existsSync(canonicalFileName) ? fs.shadowRoot.statSync(canonicalFileName) : undefined!; // TODO: GH#18217 - if (shadowRootStats.dev !== stats.dev || + if ( + shadowRootStats.dev !== stats.dev || shadowRootStats.ino !== stats.ino || - shadowRootStats.mtimeMs !== stats.mtimeMs) { + shadowRootStats.mtimeMs !== stats.mtimeMs + ) { break; } @@ -425,7 +427,7 @@ export interface ExpectedDiagnosticRelatedInformation extends ExpectedDiagnostic export enum DiagnosticKind { Error = "Error", - Status = "Status" + Status = "Status", } export interface ExpectedErrorDiagnostic extends ExpectedDiagnosticRelatedInformation { relatedInformation?: ExpectedDiagnosticRelatedInformation[]; @@ -491,7 +493,7 @@ function expectedDiagnosticToText(errorOrStatus: ExpectedDiagnostic) { expectedErrorDiagnosticToText(errorOrStatus); } -function diagnosticMessageChainToText({ messageText, next}: ts.DiagnosticMessageChain, indent = 0) { +function diagnosticMessageChainToText({ messageText, next }: ts.DiagnosticMessageChain, indent = 0) { let text = indentedText(indent, messageText); if (next) { indent++; @@ -588,18 +590,26 @@ export class SolutionBuilderHost extends CompilerHost implements ts.SolutionBuil assertDiagnosticMessages(...expectedDiagnostics: ExpectedDiagnostic[]) { const actual = this.diagnostics.slice().map(diagnosticToText); const expected = expectedDiagnostics.map(expectedDiagnosticToText); - assert.deepEqual(actual, expected, `Diagnostic arrays did not match: + assert.deepEqual( + actual, + expected, + `Diagnostic arrays did not match: Actual: ${JSON.stringify(actual, /*replacer*/ undefined, " ")} -Expected: ${JSON.stringify(expected, /*replacer*/ undefined, " ")}`); +Expected: ${JSON.stringify(expected, /*replacer*/ undefined, " ")}`, + ); } assertErrors(...expectedDiagnostics: ExpectedErrorDiagnostic[]) { const actual = this.diagnostics.filter(d => d.kind === DiagnosticKind.Error).map(diagnosticToText); const expected = expectedDiagnostics.map(expectedDiagnosticToText); - assert.deepEqual(actual, expected, `Diagnostics arrays did not match: + assert.deepEqual( + actual, + expected, + `Diagnostics arrays did not match: Actual: ${JSON.stringify(actual, /*replacer*/ undefined, " ")} Expected: ${JSON.stringify(expected, /*replacer*/ undefined, " ")} -Actual All:: ${JSON.stringify(this.diagnostics.slice().map(diagnosticToText), /*replacer*/ undefined, " ")}`); +Actual All:: ${JSON.stringify(this.diagnostics.slice().map(diagnosticToText), /*replacer*/ undefined, " ")}`, + ); } printDiagnostics(header = "== Diagnostics ==") { @@ -614,4 +624,3 @@ Actual All:: ${JSON.stringify(this.diagnostics.slice().map(diagnosticToText), /* return this.sys.now(); } } - diff --git a/src/harness/findUpDir.ts b/src/harness/findUpDir.ts index 52f6d766668ca..4cbd0f8638827 100644 --- a/src/harness/findUpDir.ts +++ b/src/harness/findUpDir.ts @@ -1,4 +1,6 @@ -import { existsSync } from "fs"; +import { + existsSync, +} from "fs"; import { dirname, join, @@ -19,5 +21,4 @@ export function findUpFile(name: string): string { } } -export const findUpRoot: { (): string; cached?: string; } = () => - findUpRoot.cached ||= dirname(findUpFile("Herebyfile.mjs")); +export const findUpRoot: { (): string; cached?: string; } = () => findUpRoot.cached ||= dirname(findUpFile("Herebyfile.mjs")); diff --git a/src/harness/fourslashImpl.ts b/src/harness/fourslashImpl.ts index 634a80bdf0871..351f103c2f394 100644 --- a/src/harness/fourslashImpl.ts +++ b/src/harness/fourslashImpl.ts @@ -12,7 +12,7 @@ export const enum FourSlashTestType { Native, Shims, ShimsWithPreprocess, - Server + Server, } // Represents a parsed source file with metadata @@ -86,9 +86,9 @@ export interface TextSpan { // Add cases into convertGlobalOptionsToCompilationsSettings function for the compiler to acknowledge such option from meta data const enum MetadataOptionNames { baselineFile = "baselinefile", - emitThisFile = "emitthisfile", // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project + emitThisFile = "emitthisfile", // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project fileName = "filename", - resolveReference = "resolvereference", // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file + resolveReference = "resolvereference", // This flag is used to specify entry file for resolve file references. The flag is only allow once per test file symlink = "symlink", } @@ -199,7 +199,7 @@ function createScriptSnapShot(sourceText: string): ts.IScriptSnapshot { const enum CallHierarchyItemDirection { Root, Incoming, - Outgoing + Outgoing, } export class TestState { @@ -224,7 +224,7 @@ export class TestState { public formatCodeSettings: ts.FormatCodeSettings; - private inputFiles = new Map(); // Map between inputFile's fileName and its content for easily looking up when resolving references + private inputFiles = new Map(); // Map between inputFile's fileName and its content for easily looking up when resolving references private static getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[] | undefined) { let result = ""; @@ -370,8 +370,7 @@ export class TestState { // Check if no-default-lib flag is false and if so add default library if (!resolvedResult.isLibFile) { - this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, - Harness.Compiler.getDefaultLibrarySourceFile()!.text, /*isRootFile*/ false); + this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.getDefaultLibrarySourceFile()!.text, /*isRootFile*/ false); compilationOptions.lib?.forEach(fileName => { const libFile = Harness.Compiler.getDefaultLibrarySourceFile(fileName); @@ -447,16 +446,17 @@ export class TestState { } const memo = Utils.memoize( (_version: number, _active: string, _caret: number, _selectEnd: number, _marker: string | undefined, ...args: any[]) => (ls[key] as (...args: any[]) => any)(...args), - (...args) => args.map(a => a && typeof a === "object" ? JSON.stringify(a) : a).join("|,|") - ); - proxy[key] = (...args: any[]) => memo( - target.languageServiceAdapterHost.getScriptInfo(target.activeFile.fileName)!.version, - target.activeFile.fileName, - target.currentCaretPosition, - target.selectionEnd, - target.lastKnownMarker, - ...args + (...args) => args.map(a => a && typeof a === "object" ? JSON.stringify(a) : a).join("|,|"), ); + proxy[key] = (...args: any[]) => + memo( + target.languageServiceAdapterHost.getScriptInfo(target.activeFile.fileName)!.version, + target.activeFile.fileName, + target.currentCaretPosition, + target.selectionEnd, + target.lastKnownMarker, + ...args, + ); } return proxy; } @@ -570,8 +570,7 @@ export class TestState { public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, shouldExist: boolean) { const startMarker = this.getMarkerByName(startMarkerName); const endMarker = this.getMarkerByName(endMarkerName); - const predicate = (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) => - ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false; + const predicate = (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) => ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false; const exists = this.anyErrorInRange(predicate, startMarker, endMarker); @@ -627,12 +626,10 @@ export class TestState { let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) => boolean; if (after) { - predicate = (errorMinChar: number, errorLimChar: number, startPos: number) => - ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false; + predicate = (errorMinChar: number, errorLimChar: number, startPos: number) => ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false; } else { - predicate = (errorMinChar: number, errorLimChar: number, startPos: number) => - ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false; + predicate = (errorMinChar: number, errorLimChar: number, startPos: number) => ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false; } const exists = this.anyErrorInRange(predicate, marker); @@ -645,8 +642,7 @@ export class TestState { } private anyErrorInRange(predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number | undefined) => boolean, startMarker: Marker, endMarker?: Marker): boolean { - return this.getDiagnostics(startMarker.fileName).some(({ start, length }) => - predicate(start!, start! + length!, startMarker.position, endMarker === undefined ? undefined : endMarker.position)); // TODO: GH#18217 + return this.getDiagnostics(startMarker.fileName).some(({ start, length }) => predicate(start!, start! + length!, startMarker.position, endMarker === undefined ? undefined : endMarker.position)); // TODO: GH#18217 } private printErrorLog(expectErrors: boolean, errors: readonly ts.Diagnostic[]): void { @@ -658,8 +654,10 @@ export class TestState { } for (const { start, length, messageText, file } of errors) { - Harness.IO.log(" " + this.formatRange(file, start!, length!) + // TODO: GH#18217 - ", message: " + ts.flattenDiagnosticMessageText(messageText, Harness.IO.newLine()) + "\n"); + Harness.IO.log( + " " + this.formatRange(file, start!, length!) + // TODO: GH#18217 + ", message: " + ts.flattenDiagnosticMessageText(messageText, Harness.IO.newLine()) + "\n", + ); } } @@ -687,11 +685,13 @@ export class TestState { public verifyNoErrors() { ts.forEachKey(this.inputFiles, fileName => { - if (!ts.isAnySupportedFileExtension(fileName) + if ( + !ts.isAnySupportedFileExtension(fileName) || Harness.getConfigNameFromFileName(fileName) // Can't get a Program in Server tests || this.testType !== FourSlashTestType.Server && !ts.getAllowJSCompilerOption(this.getProgram().getCompilerOptions()) && !ts.resolutionExtensionIsTSOrJson(ts.extensionFromPath(fileName)) - || ts.getBaseFileName(fileName) === "package.json") return; + || ts.getBaseFileName(fileName) === "package.json" + ) return; const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion); if (errors.length) { this.printErrorLog(/*expectErrors*/ false, errors); @@ -710,7 +710,8 @@ export class TestState { code === code && (!expectedMessage || expectedMessage === messageText) && ts.isNumber(start) && ts.isNumber(length) && - ts.textSpansEqual(span, { start, length })); + ts.textSpansEqual(span, { start, length }), + ); if (!hasMatchingError) { this.raiseError(`No error with code ${code} found at provided range.`); @@ -749,7 +750,7 @@ export class TestState { return this.languageService.getDefinitionAndBoundSpan(this.activeFile.fileName, this.currentCaretPosition)!; } - private renderMarkers(markers: { text: string, fileName: string, position: number }[], useTerminalBoldSequence = true) { + private renderMarkers(markers: { text: string; fileName: string; position: number; }[], useTerminalBoldSequence = true) { const filesToDisplay = ts.deduplicate(markers.map(m => m.fileName), ts.equateValues); return filesToDisplay.map(fileName => { const markersToRender = markers.filter(m => m.fileName === fileName).sort((a, b) => b.position - a.position); @@ -790,13 +791,17 @@ export class TestState { baseline += "\n\n"; baseline += indentJsonBaseline( "// === Details ===\n" + - JSON.stringify(definitions.map(def => ({ - defId: defIdMap.get(def), - ...def, - fileName: undefined, - textSpan: undefined, - contextSpan: undefined, - })), undefined, " ") + JSON.stringify( + definitions.map(def => ({ + defId: defIdMap.get(def), + ...def, + fileName: undefined, + textSpan: undefined, + contextSpan: undefined, + })), + undefined, + " ", + ), ); } return baseline; @@ -822,8 +827,10 @@ export class TestState { }); } - public baselineInlayHints(span: ts.TextSpan = { start: 0, length: this.activeFile.content.length }, preferences?: ts.UserPreferences): void{ - interface HasPosition { position: number; } + public baselineInlayHints(span: ts.TextSpan = { start: 0, length: this.activeFile.content.length }, preferences?: ts.UserPreferences): void { + interface HasPosition { + position: number; + } const sortHints = (a: HasPosition, b: HasPosition) => { return a.position - b.position; }; @@ -860,7 +867,7 @@ export class TestState { return { andApplyCodeAction: () => { this.raiseError(`Cannot apply code action when multiple markers are specified.`); - } + }, }; } this.goToMarker(options.marker); @@ -890,7 +897,8 @@ export class TestState { assert.deepEqual( actualCompletions.optionalReplacementSpan && actualCompletions.optionalReplacementSpan, options.optionalReplacementSpan && ts.createTextSpanFromRange(options.optionalReplacementSpan), - "Expected 'optionalReplacementSpan' properties to match"); + "Expected 'optionalReplacementSpan' properties to match", + ); } const nameToEntries = new Map(); @@ -901,13 +909,15 @@ export class TestState { nameToEntries.set(entry.name, [entry]); } else { - if (entries.some(e => - e.source === entry.source && - e.data?.exportName === entry.data?.exportName && - e.data?.fileName === entry.data?.fileName && - e.data?.moduleSpecifier === entry.data?.moduleSpecifier && - e.data?.ambientModuleName === entry.data?.ambientModuleName - )) { + if ( + entries.some(e => + e.source === entry.source && + e.data?.exportName === entry.data?.exportName && + e.data?.fileName === entry.data?.fileName && + e.data?.moduleSpecifier === entry.data?.moduleSpecifier && + e.data?.ambientModuleName === entry.data?.ambientModuleName + ) + ) { this.raiseError(`Duplicate completions for ${entry.name}`); } entries.push(entry); @@ -967,11 +977,11 @@ export class TestState { return { andApplyCodeAction: (options: { - name: string, - source: string, - description: string, - newFileContent?: string, - newRangeContent?: string, + name: string; + source: string; + description: string; + newFileContent?: string; + newRangeContent?: string; }) => { const { name, source, description, newFileContent, newRangeContent } = options; const data = nameAndSourceToData.get(`${options.name}|${options.source}`); @@ -982,7 +992,7 @@ export class TestState { this.raiseError(`No completion entry found for '${options.name}' from '${options.source}'`); } this.applyCodeActionFromCompletion(/*markerName*/ undefined, { name, source, data, description, newFileContent, newRangeContent, preferences }); - } + }, }; } @@ -1020,15 +1030,18 @@ export class TestState { assert.equal( actual.filterText, expected.filterText, - `At entry ${actual.name}: Completion 'filterText' not match: ${showTextDiff(expected.filterText || "", actual.filterText || "")}`); + `At entry ${actual.name}: Completion 'filterText' not match: ${showTextDiff(expected.filterText || "", actual.filterText || "")}`, + ); assert.equal( actual.labelDetails?.description, expected.labelDetails?.description, - `At entry ${actual.name}: Completion 'labelDetails.description' did not match: ${showTextDiff(expected.labelDetails?.description || "", actual.labelDetails?.description || "")}`); + `At entry ${actual.name}: Completion 'labelDetails.description' did not match: ${showTextDiff(expected.labelDetails?.description || "", actual.labelDetails?.description || "")}`, + ); assert.equal( actual.labelDetails?.detail, expected.labelDetails?.detail, - `At entry ${actual.name}: Completion 'labelDetails.detail' did not match: ${showTextDiff(expected.labelDetails?.detail || "", actual.labelDetails?.detail || "")}`); + `At entry ${actual.name}: Completion 'labelDetails.detail' did not match: ${showTextDiff(expected.labelDetails?.detail || "", actual.labelDetails?.detail || "")}`, + ); assert.equal(actual.hasAction, expected.hasAction, `At entry ${actual.name}: Expected 'hasAction' properties to match`); assert.equal(actual.isRecommended, expected.isRecommended, `At entry ${actual.name}: Expected 'isRecommended' properties to match'`); assert.equal(actual.isSnippet, expected.isSnippet, `At entry ${actual.name}: Expected 'isSnippet' properties to match`); @@ -1079,7 +1092,8 @@ export class TestState { assert.deepEqual( plusArgument, expected.filter(entry => plusArgument.includes(entry)), - `At marker ${JSON.stringify(marker)}: Argument to '${plusFunctionName}' was incorrectly sorted.`); + `At marker ${JSON.stringify(marker)}: Argument to '${plusFunctionName}' was incorrectly sorted.`, + ); } } @@ -1188,8 +1202,7 @@ export class TestState { done = baselineArrayOrSingle(command, command.markerOrRange, worker); } if (command.rangeText !== undefined) { - toArray(command.rangeText).forEach(text => - done = baselineArrayOrSingle(command, this.rangesByText().get(text)!, worker) || done); + toArray(command.rangeText).forEach(text => done = baselineArrayOrSingle(command, this.rangesByText().get(text)!, worker) || done); } if (!done) { baselineArrayOrSingle(command, this.getRanges(), worker); @@ -1216,20 +1229,22 @@ export class TestState { case "goToDefinition": return baselineEachMarkerOrRange( command, - markerOrRange => this.baselineGoToDefs( - "/*GOTO DEF*/", - markerOrRange, - () => this.getGoToDefinitionAndBoundSpan(), - ), + markerOrRange => + this.baselineGoToDefs( + "/*GOTO DEF*/", + markerOrRange, + () => this.getGoToDefinitionAndBoundSpan(), + ), ); case "getDefinitionAtPosition": return baselineEachMarkerOrRange( command, - markerOrRange => this.baselineGoToDefs( - "/*GOTO DEF POS*/", - markerOrRange, - () => this.getGoToDefinition(), - ), + markerOrRange => + this.baselineGoToDefs( + "/*GOTO DEF POS*/", + markerOrRange, + () => this.getGoToDefinition(), + ), ); case "goToSourceDefinition": if (this.testType !== FourSlashTestType.Server) { @@ -1237,30 +1252,34 @@ export class TestState { } return baselineEachMarkerOrRange( command, - markerOrRange => this.baselineGoToDefs( - "/*GOTO SOURCE DEF*/", - markerOrRange, - () => (this.languageService as ts.server.SessionClient) - .getSourceDefinitionAndBoundSpan(this.activeFile.fileName, this.currentCaretPosition), - ), + markerOrRange => + this.baselineGoToDefs( + "/*GOTO SOURCE DEF*/", + markerOrRange, + () => + (this.languageService as ts.server.SessionClient) + .getSourceDefinitionAndBoundSpan(this.activeFile.fileName, this.currentCaretPosition), + ), ); case "goToType": return baselineEachMarkerOrRange( command, - markerOrRange => this.baselineGoToDefs( - "/*GOTO TYPE*/", - markerOrRange, - () => this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition), - ), + markerOrRange => + this.baselineGoToDefs( + "/*GOTO TYPE*/", + markerOrRange, + () => this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition), + ), ); case "goToImplementation": return baselineEachMarkerOrRange( command, - markerOrRange => this.baselineGoToDefs( - "/*GOTO IMPL*/", - markerOrRange, - () => this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition), - ), + markerOrRange => + this.baselineGoToDefs( + "/*GOTO IMPL*/", + markerOrRange, + () => this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition), + ), ); case "documentHighlights": return baselineEachMarkerOrRange( @@ -1318,23 +1337,27 @@ export class TestState { baseline += "\n\n"; baseline += indentJsonBaseline( "// === Definitions ===\n" + - this.getBaselineForDocumentSpansWithFileContents( - references.map(r => r.definition), - { - markerInfo, - documentSpanId: defIdMap.size ? def => `defId: ${defIdMap.get(def)}` : undefined, - skipDocumentSpanDetails: true, - skipDocumentContainingOnlyMarker: true, - } - ) + - "\n\n// === Details ===\n" + - JSON.stringify(references.map(r => ({ - defId: defIdMap.get(r.definition), - ...r.definition, - fileName: undefined, - textSpan: undefined, - contextSpan: undefined, - })), undefined, " ") + this.getBaselineForDocumentSpansWithFileContents( + references.map(r => r.definition), + { + markerInfo, + documentSpanId: defIdMap.size ? def => `defId: ${defIdMap.get(def)}` : undefined, + skipDocumentSpanDetails: true, + skipDocumentContainingOnlyMarker: true, + }, + ) + + "\n\n// === Details ===\n" + + JSON.stringify( + references.map(r => ({ + defId: defIdMap.get(r.definition), + ...r.definition, + fileName: undefined, + textSpan: undefined, + contextSpan: undefined, + })), + undefined, + " ", + ), ); } return baseline; @@ -1374,8 +1397,8 @@ export class TestState { ts.isString(markerInfo.markerOrRange) ? this.getMarkerByName(markerInfo.markerOrRange) : isMarker(markerInfo.markerOrRange) ? - markerInfo.markerOrRange : - { fileName: markerInfo.markerOrRange.fileName, position: markerInfo.markerOrRange.pos } : + markerInfo.markerOrRange : + { fileName: markerInfo.markerOrRange.fileName, position: markerInfo.markerOrRange.pos } : undefined; const fileBaselines: string[] = []; let foundMarker = false; @@ -1537,7 +1560,7 @@ export class TestState { }); } const lineStarts = ts.computeLineStarts(content); - let posLineInfo: { pos: number, line: number } | undefined; + let posLineInfo: { pos: number; line: number; } | undefined; // Our preferred way to write marker is // /*MARKER*/[| some text |] // [| some /*MARKER*/ text |] @@ -1551,8 +1574,10 @@ export class TestState { // If this is marker position and its same as textEnd and/or contextEnd we want to write marker after those for (let matchingEndPosIndex = index + 1; matchingEndPosIndex < sortedDetails.length; matchingEndPosIndex++) { // Defer after the location if its same as rangeEnd - if (sortedDetails[matchingEndPosIndex].location === location && - sortedDetails[matchingEndPosIndex].type!.endsWith("End")) { + if ( + sortedDetails[matchingEndPosIndex].location === location && + sortedDetails[matchingEndPosIndex].type!.endsWith("End") + ) { deferredMarkerIndex = matchingEndPosIndex; } // Dont defer further than already determined @@ -1627,8 +1652,10 @@ export class TestState { // first nLinesContext and last nLinesContext if (locationLine - posLine > nLines) { if (newContent) { - readableContents = readableContents + "\n" + readableJsoncBaseline(newContent + content.slice(pos, lineStarts[posLine + TestState.nLinesContext]) + - `--- (line: ${isLibFile ? "--" : posLine + TestState.nLinesContext + 1}) skipped ---`); + readableContents = readableContents + "\n" + readableJsoncBaseline( + newContent + content.slice(pos, lineStarts[posLine + TestState.nLinesContext]) + + `--- (line: ${isLibFile ? "--" : posLine + TestState.nLinesContext + 1}) skipped ---`, + ); if (location !== undefined) readableContents += "\n"; newContent = ""; } @@ -1681,7 +1708,6 @@ export class TestState { this.raiseError(`${msgPrefix} ${displayExpectedAndActualString(stringify(fullExpected), stringify(fullActual))}`); } recur(fullActual, fullExpected, ""); - } private configure(preferences: ts.UserPreferences) { @@ -1698,7 +1724,8 @@ export class TestState { this.activeFile.fileName, this.currentCaretPosition, options, - this.formatCodeSettings); + this.formatCodeSettings, + ); } private getCompletionEntryDetails(entryName: string, source: string | undefined, data: ts.CompletionEntryData | undefined, preferences?: ts.UserPreferences): ts.CompletionEntryDetails | undefined { @@ -1727,30 +1754,33 @@ export class TestState { } private testDiagnostics(expected: readonly FourSlashInterface.Diagnostic[], diagnostics: readonly ts.Diagnostic[], category: string) { - assert.deepEqual(ts.realizeDiagnostics(diagnostics, "\n"), expected.map((e): ts.RealizedDiagnostic => { - const range = e.range || this.getRangesInFile()[0]; - if (!range) { - this.raiseError("Must provide a range for each expected diagnostic, or have one range in the fourslash source."); - } - return { - message: e.message, - category, - code: e.code, - ...ts.createTextSpanFromRange(range), - reportsUnnecessary: e.reportsUnnecessary, - reportsDeprecated: e.reportsDeprecated - }; - })); + assert.deepEqual( + ts.realizeDiagnostics(diagnostics, "\n"), + expected.map((e): ts.RealizedDiagnostic => { + const range = e.range || this.getRangesInFile()[0]; + if (!range) { + this.raiseError("Must provide a range for each expected diagnostic, or have one range in the fourslash source."); + } + return { + message: e.message, + category, + code: e.code, + ...ts.createTextSpanFromRange(range), + reportsUnnecessary: e.reportsUnnecessary, + reportsDeprecated: e.reportsDeprecated, + }; + }), + ); } - public verifyQuickInfoAt(markerName: string | Range, expectedText: string, expectedDocumentation?: string, expectedTags?: {name: string; text: string;}[]) { + public verifyQuickInfoAt(markerName: string | Range, expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]) { if (typeof markerName === "string") this.goToMarker(markerName); else this.goToRangeStart(markerName); this.verifyQuickInfoString(expectedText, expectedDocumentation, expectedTags); } - public verifyQuickInfos(namesAndTexts: { [name: string]: string | [string, string] }) { + public verifyQuickInfos(namesAndTexts: { [name: string]: string | [string, string]; }) { for (const name in namesAndTexts) { if (ts.hasProperty(namesAndTexts, name)) { const text = namesAndTexts[name]; @@ -1791,12 +1821,7 @@ export class TestState { } } - public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan, - displayParts: ts.SymbolDisplayPart[], - documentation: ts.SymbolDisplayPart[], - tags: ts.JSDocTagInfo[] | undefined - ) { - + public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[] | undefined) { const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind")); assert.equal(actualQuickInfo.kindModifiers, kindModifiers, this.messageAtLastKnownMarker("QuickInfo kindModifiers")); @@ -1819,13 +1844,13 @@ export class TestState { const { fileName, position } = ts.isString(markerOrRange) ? this.getMarkerByName(markerOrRange) : isMarker(markerOrRange) ? - markerOrRange : - { fileName: markerOrRange.fileName, position: markerOrRange.pos }; + markerOrRange : + { fileName: markerOrRange.fileName, position: markerOrRange.pos }; const { findInStrings = false, findInComments = false, providePrefixAndSuffixTextForRename = true, - quotePreference = "double" + quotePreference = "double", } = options || {}; const locations = this.languageService.findRenameLocations( fileName, @@ -1854,7 +1879,7 @@ export class TestState { startMarkerPrefix: span => span.prefixText ? `/*START PREFIX*/${span.prefixText}` : "", endMarkerSuffix: span => span.suffixText ? `${span.suffixText}/*END SUFFIX*/` : "", ignoredDocumentSpanProperties: ["prefixText", "suffixText"], - } + }, ); } @@ -1922,8 +1947,10 @@ export class TestState { if (options.text !== undefined) { assert.equal( ts.displayPartsToString(selectedItem.prefixDisplayParts) + - selectedItem.parameters.map(p => ts.displayPartsToString(p.displayParts)).join(ts.displayPartsToString(selectedItem.separatorDisplayParts)) + - ts.displayPartsToString(selectedItem.suffixDisplayParts), options.text); + selectedItem.parameters.map(p => ts.displayPartsToString(p.displayParts)).join(ts.displayPartsToString(selectedItem.separatorDisplayParts)) + + ts.displayPartsToString(selectedItem.suffixDisplayParts), + options.text, + ); } if (options.parameterName !== undefined) { assert.equal(currentParameter!.name, options.parameterName); @@ -1945,7 +1972,7 @@ export class TestState { const actualTags = selectedItem.tags; assert.equal(actualTags.length, (options.tags || ts.emptyArray).length, this.assertionMessageAtLastKnownMarker("signature help tags")); - ts.zipWith((options.tags || ts.emptyArray), actualTags, (expectedTag, actualTag) => { + ts.zipWith(options.tags || ts.emptyArray, actualTags, (expectedTag, actualTag) => { assert.equal(actualTag.name, expectedTag.name); assert.deepEqual(actualTag.text, expectedTag.text, this.assertionMessageAtLastKnownMarker("signature help tag " + actualTag.name)); }); @@ -1963,7 +1990,7 @@ export class TestState { "isVariadic", "tags", "argumentCount", - "overrideSelectedItemIndex" + "overrideSelectedItemIndex", ]; for (const key in options) { if (!ts.contains(allKeys, key)) { @@ -1985,7 +2012,8 @@ export class TestState { kindModifiers: string | undefined, fileToRename: string | undefined, expectedRange: Range | undefined, - preferences: ts.UserPreferences | undefined): void { + preferences: ts.UserPreferences | undefined, + ): void { const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition, preferences || { allowRenameOfImportPath: true }); if (!renameInfo.canRename) { throw this.raiseError("Rename did not succeed"); @@ -2004,10 +2032,14 @@ export class TestState { expectedRange = this.getRanges()[0]; } - if (renameInfo.triggerSpan.start !== expectedRange.pos || - ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) { - this.raiseError("Expected triggerSpan [" + expectedRange.pos + "," + expectedRange.end + "). Got [" + - renameInfo.triggerSpan.start + "," + ts.textSpanEnd(renameInfo.triggerSpan) + ") instead."); + if ( + renameInfo.triggerSpan.start !== expectedRange.pos || + ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end + ) { + this.raiseError( + "Expected triggerSpan [" + expectedRange.pos + "," + expectedRange.end + "). Got [" + + renameInfo.triggerSpan.start + "," + ts.textSpanEnd(renameInfo.triggerSpan) + ") instead.", + ); } } @@ -2173,7 +2205,7 @@ export class TestState { private getEmitFiles(): readonly FourSlashFile[] { // Find file to be emitted - const emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on + const emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on const allFourSlashFiles = this.testData.files; for (const file of allFourSlashFiles) { @@ -2254,7 +2286,8 @@ export class TestState { private getCompilerTestFiles() { return ts.map(this.testData.files, ({ content, fileName }) => ({ - content, unitName: fileName + content, + unitName: fileName, })); } @@ -2268,9 +2301,7 @@ export class TestState { } private getSyntacticDiagnosticBaselineText(files: Harness.Compiler.TestFile[]) { - const diagnostics = ts.flatMap(files, - file => this.languageService.getSyntacticDiagnostics(file.unitName) - ); + const diagnostics = ts.flatMap(files, file => this.languageService.getSyntacticDiagnostics(file.unitName)); const result = `Syntactic Diagnostics for file '${this.originalInputFileName}':` + Harness.IO.newLine() + Harness.Compiler.getErrorBaseline(files, diagnostics, /*pretty*/ false); @@ -2278,9 +2309,7 @@ export class TestState { } private getSemanticDiagnosticBaselineText(files: Harness.Compiler.TestFile[]) { - const diagnostics = ts.flatMap(files, - file => this.languageService.getSemanticDiagnostics(file.unitName) - ); + const diagnostics = ts.flatMap(files, file => this.languageService.getSemanticDiagnostics(file.unitName)); const result = `Semantic Diagnostics for file '${this.originalInputFileName}':` + Harness.IO.newLine() + Harness.Compiler.getErrorBaseline(files, diagnostics, /*pretty*/ false); @@ -2291,7 +2320,7 @@ export class TestState { const baselineFile = this.getBaselineFileNameForContainingTestFile(); const result = ts.arrayFrom(this.testData.markerPositions.entries(), ([name, marker]) => ({ marker: { ...marker, name }, - item: this.languageService.getQuickInfoAtPosition(marker.fileName, marker.position) + item: this.languageService.getQuickInfoAtPosition(marker.fileName, marker.position), })); const annotations = this.annotateContentWithTooltips( result, @@ -2300,8 +2329,9 @@ export class TestState { ({ displayParts, documentation, tags }) => [ ...(displayParts ? displayParts.map(p => p.text).join("").split("\n") : []), ...(documentation?.length ? documentation.map(p => p.text).join("").split("\n") : []), - ...(tags?.length ? tags.map(p => `@${p.name} ${p.text?.map(dp => dp.text).join("") ?? ""}`).join("\n").split("\n") : []) - ]); + ...(tags?.length ? tags.map(p => `@${p.name} ${p.text?.map(dp => dp.text).join("") ?? ""}`).join("\n").split("\n") : []), + ], + ); Harness.Baseline.runBaseline(baselineFile, annotations + "\n\n" + stringify(result)); } @@ -2309,7 +2339,7 @@ export class TestState { const baselineFile = this.getBaselineFileNameForContainingTestFile(); const result = ts.arrayFrom(this.testData.markerPositions.entries(), ([name, marker]) => ({ marker: { ...marker, name }, - item: this.languageService.getSignatureHelpItems(marker.fileName, marker.position, /*options*/ undefined) + item: this.languageService.getSignatureHelpItems(marker.fileName, marker.position, /*options*/ undefined), })); const annotations = this.annotateContentWithTooltips( result, @@ -2335,7 +2365,7 @@ export class TestState { } } return tooltip; - } + }, ); Harness.Baseline.runBaseline(baselineFile, annotations + "\n\n" + stringify(result)); } @@ -2351,19 +2381,22 @@ export class TestState { ...completions, entries: completions?.entries.map(entry => ({ ...entry, - ...this.getCompletionEntryDetails(entry.name, entry.source, entry.data, preferences) + ...this.getCompletionEntryDetails(entry.name, entry.source, entry.data, preferences), })), - } + }, }; }); const annotations = this.annotateContentWithTooltips( result, "completions", item => item.optionalReplacementSpan, - item => item.entries?.flatMap( - entry => entry.displayParts - ? entry.displayParts.map(p => p.text).join("").split("\n") - : [`(${entry.kindModifiers}${entry.kind}) ${entry.name}`]) + item => + item.entries?.flatMap( + entry => + entry.displayParts + ? entry.displayParts.map(p => p.text).join("").split("\n") + : [`(${entry.kindModifiers}${entry.kind}) ${entry.name}`], + ), ); for (const r of result) { for (const entry of r.item.entries ?? ts.emptyArray) { @@ -2381,36 +2414,43 @@ export class TestState { } } } - Harness.Baseline.runBaseline(baselineFile, annotations + "\n\n" + stringify(result, (key, value) => { - return key === "exportMapKey" - ? value.replace(/\|[0-9]+/g, "|*") - : value; - })); + Harness.Baseline.runBaseline( + baselineFile, + annotations + "\n\n" + stringify(result, (key, value) => { + return key === "exportMapKey" + ? value.replace(/\|[0-9]+/g, "|*") + : value; + }), + ); } - private annotateContentWithTooltips( + name: string; + kind: string; + kindModifiers?: string; + displayParts?: unknown; + }[]; + }, + >( items: ({ - marker: Marker & { name: string }, - item: T | undefined + marker: Marker & { name: string; }; + item: T | undefined; })[], opName: "completions" | "quickinfo" | "signature help", getSpan: (t: T) => ts.TextSpan | undefined, - getToolTipContents: (t: T, prev: T | undefined) => string[] | undefined): string { + getToolTipContents: (t: T, prev: T | undefined) => string[] | undefined, + ): string { const bar = "-".repeat(70); const sorted = items.slice(); // sort by file, then *backwards* by position in the file so I can insert multiple times on a line without counting sorted.sort((q1, q2) => q1.marker.fileName === q1.marker.fileName - ? (q1.marker.position > q2.marker.position ? -1 : 1) - : (q1.marker.fileName > q1.marker.fileName ? 1 : -1)); + ? (q1.marker.position > q2.marker.position ? -1 : 1) + : (q1.marker.fileName > q1.marker.fileName ? 1 : -1) + ); const files = new Map(); let previous: T | undefined; for (const { marker, item } of sorted) { @@ -2493,15 +2533,16 @@ export class TestState { errorList.forEach(err => { Harness.IO.log( "start: " + err.start + - ", length: " + err.length + - ", message: " + ts.flattenDiagnosticMessageText(err.messageText, Harness.IO.newLine())); + ", length: " + err.length + + ", message: " + ts.flattenDiagnosticMessageText(err.messageText, Harness.IO.newLine()), + ); }); } } public printCurrentFileState(showWhitespace: boolean, makeCaretVisible: boolean) { for (const file of this.testData.files) { - const active = (this.activeFile === file); + const active = this.activeFile === file; Harness.IO.log(`=== Script (${file.fileName}) ${(active ? "(active, cursor at |)" : "")} ===`); let content = this.getFileContent(file.fileName); if (active) { @@ -2531,7 +2572,7 @@ export class TestState { private getSignatureHelp({ triggerReason }: FourSlashInterface.VerifySignatureHelpOptions): ts.SignatureHelpItems | undefined { return this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition, { - triggerReason + triggerReason, }); } @@ -2645,8 +2686,8 @@ export class TestState { this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset, { triggerReason: { kind: "characterTyped", - triggerCharacter: ch - } + triggerCharacter: ch, + }, }); } else if (prevChar === " " && /A-Za-z_/.test(ch)) { @@ -2686,7 +2727,6 @@ export class TestState { } } - this.checkPostEditInvariants(); } @@ -2711,12 +2751,17 @@ export class TestState { ts.toPath(this.activeFile.fileName, this.languageServiceAdapterHost.sys.getCurrentDirectory(), ts.hostGetCanonicalFileName(this.languageServiceAdapterHost)), /*packageJsonInfoCache*/ undefined, this.languageServiceAdapterHost, - this.languageService.getProgram()?.getCompilerOptions() || {} + this.languageService.getProgram()?.getCompilerOptions() || {}, ), setExternalModuleIndicator: ts.getSetExternalModuleIndicator(this.languageService.getProgram()?.getCompilerOptions() || {}), }; const referenceSourceFile = ts.createLanguageServiceSourceFile( - this.activeFile.fileName, createScriptSnapShot(content), options, /*version:*/ "0", /*setNodeParents*/ false); + this.activeFile.fileName, + createScriptSnapShot(content), + options, + /*version:*/ "0", + /*setNodeParents*/ false, + ); const referenceSyntaxDiagnostics = referenceSourceFile.parseDiagnostics; Utils.assertDiagnosticsEquals(incrementalSyntaxDiagnostics, referenceSyntaxDiagnostics); @@ -2917,7 +2962,7 @@ export class TestState { public verifyCurrentNameOrDottedNameSpanText(text: string) { const span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition); if (!span) { - return this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + displayExpectedAndActualString("\"" + text + "\"", "undefined")); + return this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + displayExpectedAndActualString('"' + text + '"', "undefined")); } const actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span)); @@ -2933,15 +2978,15 @@ export class TestState { public baselineCurrentFileNameOrDottedNameSpans() { Harness.Baseline.runBaseline( this.testData.globalOptions[MetadataOptionNames.baselineFile], - this.baselineCurrentFileLocations(pos => this.getNameOrDottedNameSpan(pos)!)); + this.baselineCurrentFileLocations(pos => this.getNameOrDottedNameSpan(pos)!), + ); } public printNameOrDottedNameSpans(pos: number) { Harness.IO.log(this.spanInfoToString(this.getNameOrDottedNameSpan(pos)!, "**")); } - private classificationToIdentifier(classification: number){ - + private classificationToIdentifier(classification: number) { const tokenTypes: string[] = []; tokenTypes[ts.classifier.v2020.TokenType.class] = "class"; tokenTypes[ts.classifier.v2020.TokenType.enum] = "enum"; @@ -2964,7 +3009,6 @@ export class TestState { tokenModifiers[ts.classifier.v2020.TokenModifier.local] = "local"; tokenModifiers[ts.classifier.v2020.TokenModifier.defaultLibrary] = "defaultLibrary"; - function getTokenTypeFromClassification(tsClassification: number): number | undefined { if (tsClassification > ts.classifier.v2020.TokenEncodingConsts.modifierMask) { return (tsClassification >> ts.classifier.v2020.TokenEncodingConsts.typeOffset) - 1; @@ -2982,22 +3026,26 @@ export class TestState { return [tokenTypes[typeIdx], ...tokenModifiers.filter((_, i) => modSet & 1 << i)].join("."); } - private verifyClassifications(expected: { classificationType: string | number, text?: string; textSpan?: TextSpan }[], actual: (ts.ClassifiedSpan | ts.ClassifiedSpan2020)[] , sourceFileText: string) { + private verifyClassifications(expected: { classificationType: string | number; text?: string; textSpan?: TextSpan; }[], actual: (ts.ClassifiedSpan | ts.ClassifiedSpan2020)[], sourceFileText: string) { if (actual.length !== expected.length) { - this.raiseError("verifyClassifications failed - expected total classifications to be " + expected.length + - ", but was " + actual.length + - jsonMismatchString()); + this.raiseError( + "verifyClassifications failed - expected total classifications to be " + expected.length + + ", but was " + actual.length + + jsonMismatchString(), + ); } ts.zipWith(expected, actual, (expectedClassification, actualClassification) => { const expectedType = expectedClassification.classificationType; - const actualType = typeof actualClassification.classificationType === "number" ? this.classificationToIdentifier(actualClassification.classificationType) : actualClassification.classificationType; + const actualType = typeof actualClassification.classificationType === "number" ? this.classificationToIdentifier(actualClassification.classificationType) : actualClassification.classificationType; if (expectedType !== actualType) { - this.raiseError("verifyClassifications failed - expected classifications type to be " + - expectedType + ", but was " + - actualType + - jsonMismatchString()); + this.raiseError( + "verifyClassifications failed - expected classifications type to be " + + expectedType + ", but was " + + actualType + + jsonMismatchString(), + ); } const expectedSpan = expectedClassification.textSpan; @@ -3007,25 +3055,28 @@ export class TestState { const expectedLength = expectedSpan.end - expectedSpan.start; if (expectedSpan.start !== actualSpan.start || expectedLength !== actualSpan.length) { - this.raiseError("verifyClassifications failed - expected span of text to be " + - "{start=" + expectedSpan.start + ", length=" + expectedLength + "}, but was " + - "{start=" + actualSpan.start + ", length=" + actualSpan.length + "}" + - jsonMismatchString()); + this.raiseError( + "verifyClassifications failed - expected span of text to be " + + "{start=" + expectedSpan.start + ", length=" + expectedLength + "}, but was " + + "{start=" + actualSpan.start + ", length=" + actualSpan.length + "}" + + jsonMismatchString(), + ); } } const actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length); if (expectedClassification.text !== actualText) { - this.raiseError("verifyClassifications failed - expected classified text to be " + - expectedClassification.text + ", but was " + - actualText + - jsonMismatchString()); + this.raiseError( + "verifyClassifications failed - expected classified text to be " + + expectedClassification.text + ", but was " + + actualText + + jsonMismatchString(), + ); } }); function jsonMismatchString() { - const showActual = actual.map(({ classificationType, textSpan }) => - ({ classificationType, text: sourceFileText.slice(textSpan.start, textSpan.start + textSpan.length) })); + const showActual = actual.map(({ classificationType, textSpan }) => ({ classificationType, text: sourceFileText.slice(textSpan.start, textSpan.start + textSpan.length) })); return Harness.IO.newLine() + "expected: '" + Harness.IO.newLine() + stringify(expected) + "'" + Harness.IO.newLine() + "actual: '" + Harness.IO.newLine() + stringify(showActual) + "'"; @@ -3036,21 +3087,20 @@ export class TestState { if (this.testType === FourSlashTestType.Server) { const actual = (this.languageService as ts.server.SessionClient).getProjectInfo( this.activeFile.fileName, - /*needFileNameList*/ true + /*needFileNameList*/ true, ); assert.equal( expected.join(","), actual.fileNames!.map(file => { return file.replace(this.basePath + "/", ""); - }).join(",") + }).join(","), ); } } public replaceWithSemanticClassifications(format: ts.SemanticClassificationFormat.TwentyTwenty) { - const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, - ts.createTextSpan(0, this.activeFile.content.length), format); - const replacement = [`const c2 = classification("2020");`,`verify.semanticClassificationsAre("2020",`]; + const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length), format); + const replacement = [`const c2 = classification("2020");`, `verify.semanticClassificationsAre("2020",`]; for (const a of actual) { const identifier = this.classificationToIdentifier(a.classificationType as number); const text = this.activeFile.content.slice(a.textSpan.start, a.textSpan.start + a.textSpan.length); @@ -3081,15 +3131,13 @@ export class TestState { } } - public verifySemanticClassifications(format: ts.SemanticClassificationFormat, expected: { classificationType: string | number; text?: string }[]) { - const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, - ts.createTextSpan(0, this.activeFile.content.length), format); + public verifySemanticClassifications(format: ts.SemanticClassificationFormat, expected: { classificationType: string | number; text?: string; }[]) { + const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length), format); this.verifyClassifications(expected, actual, this.activeFile.content); } - public verifySyntacticClassifications(expected: { classificationType: string; text: string }[]) { - const actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, - ts.createTextSpan(0, this.activeFile.content.length)); + public verifySyntacticClassifications(expected: { classificationType: string; text: string; }[]) { + const actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual, this.activeFile.content); } @@ -3102,7 +3150,7 @@ export class TestState { } private printOutliningSpansInline(spans: ts.OutliningSpan[]) { - const allSpanInsets = [] as { text: string, pos: number }[]; + const allSpanInsets = [] as { text: string; pos: number; }[]; let annotated = this.activeFile.content; ts.forEach(spans, span => { allSpanInsets.push({ text: "[|", pos: span.textSpan.start }); @@ -3111,7 +3159,7 @@ export class TestState { const reverseSpans = allSpanInsets.sort((l, r) => r.pos - l.pos); ts.forEach(reverseSpans, span => { - annotated = annotated.slice(0, span.pos) + span.text + annotated.slice(span.pos); + annotated = annotated.slice(0, span.pos) + span.text + annotated.slice(span.pos); }); Harness.IO.log(`\nMockup:\n${annotated}`); } @@ -3149,8 +3197,7 @@ export class TestState { } public verifyTodoComments(descriptors: string[], spans: Range[]) { - const actual = this.languageService.getTodoComments(this.activeFile.fileName, - descriptors.map(d => ({ text: d, priority: 0 }))); + const actual = this.languageService.getTodoComments(this.activeFile.fileName, descriptors.map(d => ({ text: d, priority: 0 }))); if (actual.length !== spans.length) { this.raiseError(`verifyTodoComments failed - expected total spans to be ${spans.length}, but was ${actual.length}`); @@ -3248,8 +3295,7 @@ export class TestState { public verifyCodeFixAll({ fixId, fixAllDescription, newFileContent, commands: expectedCommands }: FourSlashInterface.VerifyCodeFixAllOptions): void { const fixWithId = ts.find(this.getCodeFixes(this.activeFile.fileName), a => a.fixId === fixId); - ts.Debug.assert(fixWithId !== undefined, "No available code fix has the expected id. Fix All is not available if there is only one potentially fixable diagnostic present.", () => - `Expected '${fixId}'. Available actions:\n${ts.mapDefined(this.getCodeFixes(this.activeFile.fileName), a => `${a.fixName} (${a.fixId || "no fix id"})`).join("\n")}`); + ts.Debug.assert(fixWithId !== undefined, "No available code fix has the expected id. Fix All is not available if there is only one potentially fixable diagnostic present.", () => `Expected '${fixId}'. Available actions:\n${ts.mapDefined(this.getCodeFixes(this.activeFile.fileName), a => `${a.fixName} (${a.fixId || "no fix id"})`).join("\n")}`); ts.Debug.assertEqual(fixWithId.fixAllDescription, fixAllDescription); const { changes, commands } = this.languageService.getCombinedCodeFix({ type: "file", fileName: this.activeFile.fileName }, fixId, this.formatCodeSettings, ts.emptyOptions); @@ -3361,7 +3407,7 @@ export class TestState { const diagnosticsForCodeFix = this.getDiagnostics(fileName, /*includeSuggestions*/ true).map(diagnostic => ({ start: diagnostic.start, length: diagnostic.length, - code: diagnostic.code + code: diagnostic.code, })); return ts.flatMap(ts.deduplicate(diagnosticsForCodeFix, ts.equalOwnProperties), diagnostic => { @@ -3477,7 +3523,6 @@ export class TestState { } public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) { - const openBraceMap = new Map(Object.entries({ "(": ts.CharacterCodes.openParen, "{": ts.CharacterCodes.openBrace, @@ -3485,7 +3530,7 @@ export class TestState { "'": ts.CharacterCodes.singleQuote, '"': ts.CharacterCodes.doubleQuote, "`": ts.CharacterCodes.backtick, - "<": ts.CharacterCodes.lessThan + "<": ts.CharacterCodes.lessThan, })); const charCode = openBraceMap.get(openingBrace); @@ -3514,7 +3559,7 @@ export class TestState { includeCompletionsWithInsertText: true, allowIncompleteCompletions: true, includeCompletionsWithSnippetText: true, - ...preferences + ...preferences, }; this.goToMarker(marker); @@ -3579,7 +3624,7 @@ export class TestState { Harness.Baseline.runBaseline(baselineFile, baselineText); } - public verifyJsxClosingTag(map: { [markerName: string]: ts.JsxClosingTagInfo | undefined }): void { + public verifyJsxClosingTag(map: { [markerName: string]: ts.JsxClosingTagInfo | undefined; }): void { for (const markerName in map) { this.goToMarker(markerName); const actual = this.languageService.getJsxClosingTagAtPosition(this.activeFile.fileName, this.currentCaretPosition); @@ -3587,7 +3632,7 @@ export class TestState { } } - public verifyLinkedEditingRange(map: { [markerName: string]: ts.LinkedEditingInfo | undefined }): void { + public verifyLinkedEditingRange(map: { [markerName: string]: ts.LinkedEditingInfo | undefined; }): void { for (const markerName in map) { this.goToMarker(markerName); const actual = this.languageService.getLinkedEditingRangeAtPosition(this.activeFile.fileName, this.currentCaretPosition); @@ -3615,7 +3660,7 @@ export class TestState { // get linkedEdit at every position in the file, then group positions by their linkedEdit const linkedEditsInFile = new Map(); - for(let pos = 0; pos < activeFile.content.length; pos++) { + for (let pos = 0; pos < activeFile.content.length; pos++) { const linkedEditAtPosition = languageService.getLinkedEditingRangeAtPosition(fileName, pos); if (!linkedEditAtPosition) continue; @@ -3629,7 +3674,7 @@ export class TestState { return { baselineContent: baselineContent + activeFile.content + `\n\n--No linked edits found--`, offset }; } - let inlineLinkedEditBaselines: { start: number, end: number, index: number }[] = []; + let inlineLinkedEditBaselines: { start: number; end: number; index: number; }[] = []; let linkedEditInfoBaseline = ""; for (const edit of linkedEditsByRange) { const [linkedEdit, positions] = edit; @@ -3713,29 +3758,32 @@ export class TestState { public verifyNavigateTo(options: readonly FourSlashInterface.VerifyNavigateToOptions[]): void { for (const { pattern, expected, fileName } of options) { const items = this.languageService.getNavigateToItems(pattern, /*maxResultCount*/ undefined, fileName); - this.assertObjectsEqual(items, expected.map((e): ts.NavigateToItem => ({ - name: e.name, - kind: e.kind, - kindModifiers: e.kindModifiers || "", - matchKind: e.matchKind || "exact", - isCaseSensitive: e.isCaseSensitive === undefined ? true : e.isCaseSensitive, - fileName: e.range.fileName, - textSpan: ts.createTextSpanFromRange(e.range), - containerName: e.containerName || "", - containerKind: e.containerKind || ts.ScriptElementKind.unknown, - }))); + this.assertObjectsEqual( + items, + expected.map((e): ts.NavigateToItem => ({ + name: e.name, + kind: e.kind, + kindModifiers: e.kindModifiers || "", + matchKind: e.matchKind || "exact", + isCaseSensitive: e.isCaseSensitive === undefined ? true : e.isCaseSensitive, + fileName: e.range.fileName, + textSpan: ts.createTextSpanFromRange(e.range), + containerName: e.containerName || "", + containerKind: e.containerKind || ts.ScriptElementKind.unknown, + })), + ); } } - public verifyNavigationBar(json: any, options: { checkSpans?: boolean } | undefined) { + public verifyNavigationBar(json: any, options: { checkSpans?: boolean; } | undefined) { this.verifyNavigationTreeOrBar(json, this.languageService.getNavigationBarItems(this.activeFile.fileName), "Bar", options); } - public verifyNavigationTree(json: any, options: { checkSpans?: boolean } | undefined) { + public verifyNavigationTree(json: any, options: { checkSpans?: boolean; } | undefined) { this.verifyNavigationTreeOrBar(json, this.languageService.getNavigationTree(this.activeFile.fileName), "Tree", options); } - private verifyNavigationTreeOrBar(json: any, tree: any, name: "Tree" | "Bar", options: { checkSpans?: boolean } | undefined) { + private verifyNavigationTreeOrBar(json: any, tree: any, name: "Tree" | "Bar", options: { checkSpans?: boolean; } | undefined) { if (JSON.stringify(tree, replacer) !== JSON.stringify(json)) { this.raiseError(`verifyNavigation${name} failed - \n${showTextDiff(stringify(json), stringify(tree, replacer))}`); } @@ -3833,7 +3881,7 @@ export class TestState { `Expected to find a fix with the name '${fixName}', but none exists.` + availableFixes.length ? ` Available fixes: ${availableFixes.map(fix => `${fix.fixName} (${fix.fixId ? "with" : "without"} fix-all)`).join(", ")}` - : "" + : "", ); } } @@ -3851,7 +3899,7 @@ export class TestState { private getSelection(): ts.TextRange { return { pos: this.currentCaretPosition, - end: this.selectionEnd === -1 ? this.currentCaretPosition : this.selectionEnd + end: this.selectionEnd === -1 ? this.currentCaretPosition : this.selectionEnd, }; } @@ -3946,7 +3994,6 @@ export class TestState { ts.Debug.assert(rp === undefined); } this.verifyFileContent(fileName, newContent); - } if (renamePosition === undefined) { @@ -3962,7 +4009,7 @@ export class TestState { } } - private static parseNewContent(newContentWithRenameMarker: string): { readonly renamePosition: number | undefined, readonly newContent: string } { + private static parseNewContent(newContentWithRenameMarker: string): { readonly renamePosition: number | undefined; readonly newContent: string; } { const renamePosition = newContentWithRenameMarker.indexOf("/*RENAME*/"); if (renamePosition === -1) { return { renamePosition: undefined, newContent: newContentWithRenameMarker }; @@ -4009,7 +4056,7 @@ export class TestState { this.verifyNewContent({ newFileContent: options.newFileContents }, editInfo.edits); } - private testNewFileContents(edits: readonly ts.FileTextChanges[], newFileContents: { [fileName: string]: string }, description: string): void { + private testNewFileContents(edits: readonly ts.FileTextChanges[], newFileContents: { [fileName: string]: string; }, description: string): void { for (const { fileName, textChanges } of edits) { const newContent = newFileContents[fileName]; if (newContent === undefined) { @@ -4042,8 +4089,8 @@ export class TestState { expectedContent: string, refactorNameToApply: string, actionName: string, - formattingOptions?: ts.FormatCodeSettings) { - + formattingOptions?: ts.FormatCodeSettings, + ) { formattingOptions = formattingOptions || this.formatCodeSettings; const marker = this.getMarkerByName(markerName); @@ -4097,15 +4144,13 @@ export class TestState { const alreadySeen = seen.has(key); seen.set(key, true); - const incomingCalls = - direction === CallHierarchyItemDirection.Outgoing ? { result: "skip" } as const : - alreadySeen ? { result: "seen" } as const : - { result: "show", values: this.languageService.provideCallHierarchyIncomingCalls(callHierarchyItem.file, callHierarchyItem.selectionSpan.start) } as const; + const incomingCalls = direction === CallHierarchyItemDirection.Outgoing ? { result: "skip" } as const : + alreadySeen ? { result: "seen" } as const : + { result: "show", values: this.languageService.provideCallHierarchyIncomingCalls(callHierarchyItem.file, callHierarchyItem.selectionSpan.start) } as const; - const outgoingCalls = - direction === CallHierarchyItemDirection.Incoming ? { result: "skip" } as const : - alreadySeen ? { result: "seen" } as const : - { result: "show", values: this.languageService.provideCallHierarchyOutgoingCalls(callHierarchyItem.file, callHierarchyItem.selectionSpan.start) } as const; + const outgoingCalls = direction === CallHierarchyItemDirection.Incoming ? { result: "skip" } as const : + alreadySeen ? { result: "seen" } as const : + { result: "show", values: this.languageService.provideCallHierarchyOutgoingCalls(callHierarchyItem.file, callHierarchyItem.selectionSpan.start) } as const; let text = ""; text += `${prefix}╭ name: ${callHierarchyItem.name}\n`; @@ -4117,9 +4162,13 @@ export class TestState { text += `${prefix}├ span:\n`; text += this.formatCallHierarchyItemSpan(file, callHierarchyItem.span, `${prefix}│ `); text += `${prefix}├ selectionSpan:\n`; - text += this.formatCallHierarchyItemSpan(file, callHierarchyItem.selectionSpan, `${prefix}│ `, + text += this.formatCallHierarchyItemSpan( + file, + callHierarchyItem.selectionSpan, + `${prefix}│ `, incomingCalls.result !== "skip" || outgoingCalls.result !== "skip" ? `${prefix}│ ` : - `${trailingPrefix}╰ `); + `${trailingPrefix}╰ `, + ); if (incomingCalls.result === "seen") { if (outgoingCalls.result === "skip") { @@ -4146,10 +4195,14 @@ export class TestState { text += `${prefix}│ ╭ from:\n`; text += this.formatCallHierarchyItem(file, incomingCall.from, CallHierarchyItemDirection.Incoming, seen, `${prefix}│ │ `); text += `${prefix}│ ├ fromSpans:\n`; - text += this.formatCallHierarchyItemSpans(file, incomingCall.fromSpans, `${prefix}│ │ `, + text += this.formatCallHierarchyItemSpans( + file, + incomingCall.fromSpans, + `${prefix}│ │ `, i < incomingCalls.values.length - 1 ? `${prefix}│ ╰ ` : outgoingCalls.result !== "skip" ? `${prefix}│ ╰ ` : - `${trailingPrefix}╰ ╰ `); + `${trailingPrefix}╰ ╰ `, + ); } } } @@ -4168,9 +4221,13 @@ export class TestState { text += `${prefix}│ ╭ to:\n`; text += this.formatCallHierarchyItem(this.findFile(outgoingCall.to.file), outgoingCall.to, CallHierarchyItemDirection.Outgoing, seen, `${prefix}│ │ `); text += `${prefix}│ ├ fromSpans:\n`; - text += this.formatCallHierarchyItemSpans(file, outgoingCall.fromSpans, `${prefix}│ │ `, + text += this.formatCallHierarchyItemSpans( + file, + outgoingCall.fromSpans, + `${prefix}│ │ `, i < outgoingCalls.values.length - 1 ? `${prefix}│ ╰ ` : - `${trailingPrefix}╰ ╰ `); + `${trailingPrefix}╰ ╰ `, + ); } } } @@ -4222,10 +4279,12 @@ export class TestState { // Get the text of the entire line the caret is currently at private getCurrentLineContent() { - return this.getLineContent(this.languageServiceAdapterHost.positionToLineAndCharacter( - this.activeFile.fileName, - this.currentCaretPosition, - ).line); + return this.getLineContent( + this.languageServiceAdapterHost.positionToLineAndCharacter( + this.activeFile.fileName, + this.currentCaretPosition, + ).line, + ); } private findFile(indexOrName: string | number): FourSlashFile { @@ -4280,7 +4339,7 @@ export class TestState { public getMarkerByName(markerName: string) { const markerPos = this.testData.markerPositions.get(markerName); if (markerPos === undefined) { - throw new Error(`Unknown marker "${markerName}" Available markers: ${this.getMarkerNames().map(m => "\"" + m + "\"").join(", ")}`); + throw new Error(`Unknown marker "${markerName}" Available markers: ${this.getMarkerNames().map(m => '"' + m + '"').join(", ")}`); } else { return markerPos; @@ -4296,7 +4355,7 @@ export class TestState { } public getEditsForFileRename({ oldPath, newPath, newFileContents, preferences }: FourSlashInterface.GetEditsForFileRenameOptions): void { - const test = (fileContents: { readonly [fileName: string]: string }, description: string): void => { + const test = (fileContents: { readonly [fileName: string]: string; }, description: string): void => { const changes = this.languageService.getEditsForFileRename(oldPath, newPath, this.formatCodeSettings, preferences); this.testNewFileContents(changes, fileContents, description); }; @@ -4402,11 +4461,11 @@ function forEachTextChange(changes: readonly ts.TextChange[], cb: (change: ts.Te function updatePosition(position: number, editStart: number, editEnd: number, { length }: string): number { // If inside the edit, return -1 to mark as invalid - return position <= editStart ? position : position < editEnd ? -1 : position + length - + (editEnd - editStart); + return position <= editStart ? position : position < editEnd ? -1 : position + length - +(editEnd - editStart); } -function renameKeys(obj: { readonly [key: string]: T }, renameKey: (key: string) => string): { readonly [key: string]: T } { - const res: { [key: string]: T } = {}; +function renameKeys(obj: { readonly [key: string]: T; }, renameKey: (key: string) => string): { readonly [key: string]: T; } { + const res: { [key: string]: T; } = {}; for (const key in obj) { res[renameKey(key)] = obj[key]; } @@ -4441,7 +4500,7 @@ function runCode(code: string, state: TestState, fileName: string): void { type SourceMapSupportModule = typeof import("source-map-support") & { // TODO(rbuckton): This is missing from the DT definitions and needs to be added. - resetRetrieveHandlers(): void + resetRetrieveHandlers(): void; }; // Provide the content of the current test to 'source-map-support' so that it can give us the correct source positions @@ -4458,7 +4517,7 @@ function runCode(code: string, state: TestState, fileName: string): void { retrieveFile: path => { return path === generatedFile ? wrappedCode : undefined!; - } + }, }); try { @@ -4520,7 +4579,7 @@ function parseTestData(basePath: string, contents: string, fileName: string): Fo let currentFileContent: string | undefined; let currentFileName = fileName; let currentFileSymlinks: string[] | undefined; - let currentFileOptions: { [s: string]: string } = {}; + let currentFileOptions: { [s: string]: string; } = {}; function nextFile() { if (currentFileContent === undefined) return; @@ -4614,7 +4673,7 @@ function parseTestData(basePath: string, contents: string, fileName: string): Fo globalOptions, files, symlinks, - ranges + ranges, }; } @@ -4626,7 +4685,7 @@ function getNonFileNameOptionInFileList(files: FourSlashFile[]): string | undefi return ts.forEach(files, f => getNonFileNameOptionInObject(f.fileOptions)); } -function getNonFileNameOptionInObject(optionObject: { [s: string]: string }): string | undefined { +function getNonFileNameOptionInObject(optionObject: { [s: string]: string; }): string | undefined { for (const option in optionObject) { switch (option) { case MetadataOptionNames.fileName: @@ -4643,7 +4702,7 @@ function getNonFileNameOptionInObject(optionObject: { [s: string]: string }): st const enum State { none, inSlashStarMarker, - inObjectMarker + inObjectMarker, } function reportError(fileName: string, line: number, col: number, message: string): never { @@ -4655,7 +4714,7 @@ function recordObjectMarker(fileName: string, location: LocationInformation, tex let markerValue; try { // Attempt to parse the marker value as JSON - markerValue = JSON.parse("{ " + text + " }") as { name?: unknown }; + markerValue = JSON.parse("{ " + text + " }") as { name?: unknown; }; } catch (e) { reportError(fileName, location.sourceLine, location.sourceColumn, "Unable to parse marker text " + e.message); @@ -4668,7 +4727,7 @@ function recordObjectMarker(fileName: string, location: LocationInformation, tex const marker: Marker = { fileName, position: location.position, - data: markerValue + data: markerValue, }; // Object markers can be anonymous @@ -4684,7 +4743,7 @@ function recordObjectMarker(fileName: string, location: LocationInformation, tex function recordMarker(fileName: string, location: LocationInformation, name: string, markerMap: Map, markers: Marker[]): Marker | undefined { const marker: Marker = { fileName, - position: location.position + position: location.position, }; // Verify markers for uniqueness @@ -4764,7 +4823,7 @@ function parseFileContent(content: string, fileName: string, markerMap: Map { const closestIndex = ranges[ranges.length - 1]; @@ -4954,9 +5013,9 @@ function rangesOfDiffBetweenTwoStrings(source: string, target: string) { if (doesAddToIndex) { closestIndex.length = closestIndex.length + 1; } - else { - ranges.push({ start: index - 1, length: 1 }); - } + else { + ranges.push({ start: index - 1, length: 1 }); + } } else { ranges.push({ start: index - 1, length: 1 }); @@ -4983,7 +5042,7 @@ function highlightDifferenceBetweenStrings(source: string, target: string) { const before = emTarget.slice(0, range.start + 1 + additionalOffset); const between = emTarget.slice( range.start + 1 + additionalOffset, - range.start + range.length + 1 + additionalOffset + range.start + range.length + 1 + additionalOffset, ); const after = emTarget.slice(range.start + range.length + 1 + additionalOffset, emTarget.length); emTarget = before + lhs + between + rhs + after; diff --git a/src/harness/fourslashInterfaceImpl.ts b/src/harness/fourslashInterfaceImpl.ts index a97341d5eeecb..6a15ca0a3ff09 100644 --- a/src/harness/fourslashInterfaceImpl.ts +++ b/src/harness/fourslashInterfaceImpl.ts @@ -80,7 +80,6 @@ export class GoTo { this.state.goToEachMarker(markers, typeof a === "function" ? a : b!); } - public rangeStart(range: FourSlash.Range) { this.state.goToRangeStart(range); } @@ -173,11 +172,11 @@ export class VerifyNegatable { this.state.verifyBraceCompletionAtPosition(this.negative, openingBrace); } - public jsxClosingTag(map: { [markerName: string]: ts.JsxClosingTagInfo | undefined }): void { + public jsxClosingTag(map: { [markerName: string]: ts.JsxClosingTagInfo | undefined; }): void { this.state.verifyJsxClosingTag(map); } - public linkedEditing(map: { [markerName: string]: ts.LinkedEditingInfo | undefined }): void { + public linkedEditing(map: { [markerName: string]: ts.LinkedEditingInfo | undefined; }): void { this.state.verifyLinkedEditingRange(map); } @@ -273,7 +272,7 @@ export class Verify extends VerifyNegatable { this.state.verifyQuickInfoAt(markerName, expectedText, expectedDocumentation, expectedTags); } - public quickInfos(namesAndTexts: { [name: string]: string }) { + public quickInfos(namesAndTexts: { [name: string]: string; }) { this.state.verifyQuickInfos(namesAndTexts); } @@ -520,11 +519,11 @@ export class Verify extends VerifyNegatable { this.state.baselineAutoImports(marker, fullNamesForCodeFix, options); } - public navigationBar(json: any, options?: { checkSpans?: boolean }) { + public navigationBar(json: any, options?: { checkSpans?: boolean; }) { this.state.verifyNavigationBar(json, options); } - public navigationTree(json: any, options?: { checkSpans?: boolean }) { + public navigationTree(json: any, options?: { checkSpans?: boolean; }) { this.state.verifyNavigationTree(json, options); } @@ -535,7 +534,7 @@ export class Verify extends VerifyNegatable { /** * This method *requires* a contiguous, complete, and ordered stream of classifications for a file. */ - public syntacticClassificationsAre(...classifications: { classificationType: string; text: string }[]) { + public syntacticClassificationsAre(...classifications: { classificationType: string; text: string; }[]) { this.state.verifySyntacticClassifications(classifications); } @@ -565,7 +564,8 @@ export class Verify extends VerifyNegatable { kindModifiers?: string, fileToRename?: string, expectedRange?: FourSlash.Range, - preferences?: ts.UserPreferences) { + preferences?: ts.UserPreferences, + ) { this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers, fileToRename, expectedRange, preferences); } @@ -581,8 +581,7 @@ export class Verify extends VerifyNegatable { this.state.verifyBaselineCommands({ type: "findRenameLocations", rangeText, options }); } - public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: FourSlash.TextSpan, - displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[]) { + public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: FourSlash.TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[]) { this.state.verifyQuickInfoDisplayParts(kind, kindModifiers, textSpan, displayParts, documentation, tags); } @@ -824,17 +823,16 @@ interface ModernClassification { type Classification = OlderClassification | ModernClassification; export function classification(format: ts.SemanticClassificationFormat) { - function semanticToken(identifier: string, text: string, _position: number): Classification { return { classificationType: identifier, - text - }; + text, + }; } if (format === ts.SemanticClassificationFormat.TwentyTwenty) { return { - semanticToken + semanticToken, }; } @@ -961,7 +959,7 @@ export function classification(format: ts.SemanticClassificationFormat) { jsxAttribute, jsxText, jsxAttributeStringLiteralValue, - getClassification + getClassification, }; } @@ -1000,7 +998,7 @@ export namespace Completion { name, kind: "function", kindModifiers: "declare", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }); const deprecatedFunctionEntry = (name: string): ExpectedCompletionEntryObject => ({ name, @@ -1012,24 +1010,24 @@ export namespace Completion { name, kind: "var", kindModifiers: "declare", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }); const moduleEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "module", kindModifiers: "declare", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }); const keywordEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "keyword", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }); const methodEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "method", kindModifiers: "declare", - sortText: SortText.LocationPriority + sortText: SortText.LocationPriority, }); const deprecatedMethodEntry = (name: string): ExpectedCompletionEntryObject => ({ name, @@ -1041,19 +1039,19 @@ export namespace Completion { name, kind: "property", kindModifiers: "declare", - sortText: SortText.LocationPriority + sortText: SortText.LocationPriority, }); const interfaceEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "interface", kindModifiers: "declare", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }); const typeEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "type", kindModifiers: "declare", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }); const res: ExpectedCompletionEntryObject[] = []; @@ -1061,7 +1059,7 @@ export namespace Completion { res.push({ name: ts.Debug.checkDefined(ts.tokenToString(i)), kind: "keyword", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }); } export const keywordsWithUndefined: readonly ExpectedCompletionEntryObject[] = res; @@ -1234,19 +1232,18 @@ export namespace Completion { export const globalThisEntry: ExpectedCompletionEntry = { name: "globalThis", kind: "module", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }; export const globalTypes = globalTypesPlus([]); export function globalTypesPlus(plus: readonly ExpectedCompletionEntry[]) { return combineExpectedCompletionEntries( "globalTypesPlus", [globalThisEntry, ...globalTypeDecls, ...typeKeywords], - plus + plus, ); } - export const typeAssertionKeywords: readonly ExpectedCompletionEntry[] = - globalTypesPlus([keywordEntry("const")]); + export const typeAssertionKeywords: readonly ExpectedCompletionEntry[] = globalTypesPlus([keywordEntry("const")]); function getInJsKeywords(keywords: readonly ExpectedCompletionEntryObject[]): readonly ExpectedCompletionEntryObject[] { return keywords.filter(keyword => { @@ -1303,12 +1300,11 @@ export namespace Completion { export const classElementInJsKeywords = getInJsKeywords(classElementKeywords); - export const constructorParameterKeywords: readonly ExpectedCompletionEntryObject[] = - ["override", "private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({ - name, - kind: "keyword", - sortText: SortText.GlobalsOrKeywords - })); + export const constructorParameterKeywords: readonly ExpectedCompletionEntryObject[] = ["override", "private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({ + name, + kind: "keyword", + sortText: SortText.GlobalsOrKeywords, + })); export const functionMembers: readonly ExpectedCompletionEntryObject[] = [ methodEntry("apply"), @@ -1548,29 +1544,31 @@ export namespace Completion { export const undefinedVarEntry: ExpectedCompletionEntryObject = { name: "undefined", kind: "var", - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }; // TODO: many of these are inappropriate to always provide - export const globalsInsideFunction = (plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean }): readonly ExpectedCompletionEntry[] => [ - { name: "arguments", kind: "local var" }, - ...plus, - globalThisEntry, - ...options?.noLib ? [] : globalsVars, - undefinedVarEntry, - ...globalKeywordsInsideFunction, - ].sort(compareExpectedCompletionEntries); + export const globalsInsideFunction = (plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean; }): readonly ExpectedCompletionEntry[] => + [ + { name: "arguments", kind: "local var" }, + ...plus, + globalThisEntry, + ...options?.noLib ? [] : globalsVars, + undefinedVarEntry, + ...globalKeywordsInsideFunction, + ].sort(compareExpectedCompletionEntries); const globalInJsKeywordsInsideFunction = getInJsKeywords(globalKeywordsInsideFunction); // TODO: many of these are inappropriate to always provide - export const globalsInJsInsideFunction = (plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean }): readonly ExpectedCompletionEntry[] => [ - { name: "arguments", kind: "local var" }, - globalThisEntry, - ...options?.noLib ? [] : globalsVars, - ...plus, - undefinedVarEntry, - ...globalInJsKeywordsInsideFunction, - ].sort(compareExpectedCompletionEntries); + export const globalsInJsInsideFunction = (plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean; }): readonly ExpectedCompletionEntry[] => + [ + { name: "arguments", kind: "local var" }, + globalThisEntry, + ...options?.noLib ? [] : globalsVars, + ...plus, + undefinedVarEntry, + ...globalInJsKeywordsInsideFunction, + ].sort(compareExpectedCompletionEntries); // TODO: many of these are inappropriate to always provide export const globalKeywords: readonly ExpectedCompletionEntryObject[] = [ @@ -1697,17 +1695,17 @@ export namespace Completion { globalThisEntry, ...globalsVars, undefinedVarEntry, - ...globalKeywords + ...globalKeywords, ].sort(compareExpectedCompletionEntries); export const globalsInJs: readonly ExpectedCompletionEntryObject[] = [ globalThisEntry, ...globalsVars, undefinedVarEntry, - ...globalInJsKeywords + ...globalInJsKeywords, ].sort(compareExpectedCompletionEntries); - export function globalsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean }) { + export function globalsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean; }) { return combineExpectedCompletionEntries("globalsPlus", [ globalThisEntry, ...options?.noLib ? [] : globalsVars, @@ -1716,7 +1714,7 @@ export namespace Completion { ], plus); } - export function globalsInJsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean }) { + export function globalsInJsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean; }) { return combineExpectedCompletionEntries("globalsInJsPlus", [ globalThisEntry, ...options?.noLib ? [] : globalsVars, @@ -1731,7 +1729,7 @@ export interface ReferenceGroup { ranges: FourSlash.Range[]; } -export type ReferenceGroupDefinition = string | { text: string, range: FourSlash.Range }; +export type ReferenceGroupDefinition = string | { text: string; range: FourSlash.Range; }; export interface ApplyRefactorOptions { refactorName: string; @@ -1769,8 +1767,8 @@ export interface ExpectedCompletionEntryLabelDetails { } export type ExpectedExactCompletionsPlus = readonly ExpectedCompletionEntry[] & { - plusFunctionName: string, - plusArgument: readonly ExpectedCompletionEntry[] + plusFunctionName: string; + plusArgument: readonly ExpectedCompletionEntry[]; }; export interface VerifyCompletionsOptions { @@ -1846,7 +1844,7 @@ export interface VerifyDocumentHighlightsOptions { filesToSearch: readonly string[]; } -export type NewFileContent = string | { readonly [filename: string]: string }; +export type NewFileContent = string | { readonly [filename: string]: string; }; export interface NewContentOptions { // Exactly one of these should be defined. @@ -1900,17 +1898,17 @@ export interface Diagnostic { export interface GetEditsForFileRenameOptions { readonly oldPath: string; readonly newPath: string; - readonly newFileContents: { readonly [fileName: string]: string }; + readonly newFileContents: { readonly [fileName: string]: string; }; readonly preferences?: ts.UserPreferences; } export interface MoveToNewFileOptions { - readonly newFileContents: { readonly [fileName: string]: string }; + readonly newFileContents: { readonly [fileName: string]: string; }; readonly preferences?: ts.UserPreferences; } export interface MoveToFileOptions { - readonly newFileContents: { readonly [fileName: string]: string }; + readonly newFileContents: { readonly [fileName: string]: string; }; readonly interactiveRefactorArguments: ts.InteractiveRefactorArguments; readonly preferences?: ts.UserPreferences; } @@ -1922,9 +1920,9 @@ export type RenameLocationsOptions = readonly RenameLocationOptions[] | { readonly providePrefixAndSuffixTextForRename?: boolean; }; export interface DiagnosticIgnoredInterpolations { - template: string + template: string; } -export type RenameLocationOptions = FourSlash.Range | { readonly range: FourSlash.Range, readonly prefixText?: string, readonly suffixText?: string }; +export type RenameLocationOptions = FourSlash.Range | { readonly range: FourSlash.Range; readonly prefixText?: string; readonly suffixText?: string; }; export interface RenameOptions { readonly findInStrings?: boolean; readonly findInComments?: boolean; diff --git a/src/harness/harnessGlobals.ts b/src/harness/harnessGlobals.ts index 9de9537181f49..a83bff41287ba 100644 --- a/src/harness/harnessGlobals.ts +++ b/src/harness/harnessGlobals.ts @@ -27,7 +27,7 @@ globalThis.assert = chai.assert; assertDeepImpl(a, b, msg); function arrayExtraKeysObject(a: readonly unknown[]): object { - const obj: { [key: string]: unknown } = {}; + const obj: { [key: string]: unknown; } = {}; for (const key in a) { if (Number.isNaN(Number(key))) { obj[key] = a[key]; diff --git a/src/harness/harnessIO.ts b/src/harness/harnessIO.ts index d727cd82e928d..880a591fb2780 100644 --- a/src/harness/harnessIO.ts +++ b/src/harness/harnessIO.ts @@ -26,7 +26,7 @@ export interface IO { directoryExists(path: string): boolean; deleteFile(fileName: string): void; enumerateTestFiles(runner: RunnerBase): (string | FileBasedTest)[]; - listFiles(path: string, filter?: RegExp, options?: { recursive?: boolean }): string[]; + listFiles(path: string, filter?: RegExp, options?: { recursive?: boolean; }): string[]; log(text: string): void; args(): string[]; getExecutingFilePath(): string; @@ -37,7 +37,7 @@ export interface IO { tryEnableSourceMapsForHost?(): void; getEnvironmentVariable?(name: string): string; getMemoryUsage?(): number | undefined; - joinPath(...components: string[]): string + joinPath(...components: string[]): string; } export let IO: IO; @@ -84,7 +84,7 @@ function createNodeIO(): IO { return runner.getTestFiles(); } - function listFiles(path: string, spec: RegExp, options: { recursive?: boolean } = {}) { + function listFiles(path: string, spec: RegExp, options: { recursive?: boolean; } = {}) { function filesInFolder(folder: string): string[] { let paths: string[] = []; @@ -174,7 +174,7 @@ function createNodeIO(): IO { tryEnableSourceMapsForHost: () => ts.sys.tryEnableSourceMapsForHost && ts.sys.tryEnableSourceMapsForHost(), getMemoryUsage: () => ts.sys.getMemoryUsage && ts.sys.getMemoryUsage(), getEnvironmentVariable: name => ts.sys.getEnvironmentVariable(name), - joinPath + joinPath, }; } @@ -220,12 +220,12 @@ export namespace Compiler { public Write(str: string) { // out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later - this.currentLine = [(this.currentLine || ""), str].join(""); + this.currentLine = [this.currentLine || "", str].join(""); } public WriteLine(str: string) { // out of memory usage concerns avoid using + or += if we're going to do any manipulation of this string later - this.lines.push([(this.currentLine || ""), str].join("")); + this.lines.push([this.currentLine || "", str].join("")); this.currentLine = undefined!; } @@ -243,7 +243,8 @@ export namespace Compiler { export function createSourceFileAndAssertInvariants( fileName: string, sourceText: string, - languageVersion: ts.ScriptTarget) { + languageVersion: ts.ScriptTarget, + ) { // We'll only assert invariants outside of light mode. const shouldAssertInvariants = !lightMode; @@ -270,7 +271,7 @@ export namespace Compiler { if (!libFileNameSourceFileMap) { libFileNameSourceFileMap = new Map(Object.entries({ - [defaultLibFileName]: createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts")!, /*languageVersion*/ ts.ScriptTarget.Latest) + [defaultLibFileName]: createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts")!, /*languageVersion*/ ts.ScriptTarget.Latest), })); } @@ -403,7 +404,7 @@ export namespace Compiler { compilerOptions: ts.CompilerOptions | undefined, // Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file currentDirectory: string | undefined, - symlinks?: vfs.FileSet + symlinks?: vfs.FileSet, ): compiler.CompilationResult { const options: ts.CompilerOptions & HarnessOptions = compilerOptions ? ts.cloneCompilerOptions(compilerOptions) : { noResolve: false }; options.target = ts.getEmitScriptTarget(options); @@ -465,14 +466,15 @@ export namespace Compiler { currentDirectory: string; } - export function prepareDeclarationCompilationContext(inputFiles: readonly TestFile[], + export function prepareDeclarationCompilationContext( + inputFiles: readonly TestFile[], otherFiles: readonly TestFile[], result: compiler.CompilationResult, harnessSettings: TestCaseParser.CompilerSettings & HarnessOptions, options: ts.CompilerOptions, // Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file - currentDirectory: string | undefined): DeclarationCompilationContext | undefined { - + currentDirectory: string | undefined, + ): DeclarationCompilationContext | undefined { if (options.declaration && result.diagnostics.length === 0) { if (options.emitDeclarationOnly) { if (result.js.size > 0 || result.dts.size === 0) { @@ -503,7 +505,7 @@ export namespace Compiler { if (declFile && !findUnit(declFile.file, declInputFiles) && !findUnit(declFile.file, declOtherFiles)) { dtsFiles.push({ unitName: declFile.file, - content: Utils.removeByteOrderMark(declFile.text) + content: Utils.removeByteOrderMark(declFile.text), }); } } @@ -568,7 +570,7 @@ export namespace Compiler { export const diagnosticSummaryMarker = "__diagnosticSummary"; export const globalErrorsMarker = "__globalErrors"; - export function *iterateErrorBaseline(inputFiles: readonly TestFile[], diagnostics: readonly ts.Diagnostic[], options?: { pretty?: boolean, caseSensitive?: boolean, currentDirectory?: string }): IterableIterator<[string, string, number]> { + export function* iterateErrorBaseline(inputFiles: readonly TestFile[], diagnostics: readonly ts.Diagnostic[], options?: { pretty?: boolean; caseSensitive?: boolean; currentDirectory?: string; }): IterableIterator<[string, string, number]> { diagnostics = ts.sort(diagnostics, ts.compareDiagnostics); let outputLines = ""; // Count up all errors that were found in files other than lib.d.ts so we don't miss any @@ -609,7 +611,7 @@ export namespace Compiler { errLines.push(`!!! related TS${info.code}${location}: ${ts.flattenDiagnosticMessageText(info.messageText, IO.newLine())}`); } } - errLines.forEach(e => outputLines += (newLine() + e)); + errLines.forEach(e => outputLines += newLine() + e); errorsReported++; // do not count errors from lib.d.ts here, they are computed separately as numLibraryDiagnostics @@ -645,9 +647,8 @@ export namespace Compiler { return !!errFn && ts.comparePaths(Utils.removeTestPathPrefixes(errFn.fileName), Utils.removeTestPathPrefixes(inputFile.unitName), options && options.currentDirectory || "", !(options && options.caseSensitive)) === ts.Comparison.EqualTo; }); - // Header - outputLines += (newLine() + "==== " + Utils.removeTestPathPrefixes(inputFile.unitName) + " (" + fileErrors.length + " errors) ===="); + outputLines += newLine() + "==== " + Utils.removeTestPathPrefixes(inputFile.unitName) + " (" + fileErrors.length + " errors) ===="; // Make sure we emit something for every error let markedErrorCount = 0; @@ -676,7 +677,7 @@ export namespace Compiler { nextLineStart = lineStarts[lineIndex + 1]; } // Emit this line from the original file - outputLines += (newLine() + " " + line); + outputLines += newLine() + " " + line; fileErrors.forEach(errDiagnostic => { const err = errDiagnostic as ts.TextSpan; // TODO: GH#18217 // Does any error start or continue on to this line? Emit squiggles @@ -689,7 +690,7 @@ export namespace Compiler { // Calculate the start of the squiggle const squiggleStart = Math.max(0, relativeOffset); // TODO/REVIEW: this doesn't work quite right in the browser if a multi file test has files whose names are just the right length relative to one another - outputLines += (newLine() + " " + line.substr(0, squiggleStart).replace(/[^\s]/g, " ") + new Array(Math.min(length, line.length - squiggleStart) + 1).join("~")); + outputLines += newLine() + " " + line.substr(0, squiggleStart).replace(/[^\s]/g, " ") + new Array(Math.min(length, line.length - squiggleStart) + 1).join("~"); // If the error ended here, or we're at the end of the file, emit its message if ((lineIndex === lines.length - 1) || nextLineStart > end) { @@ -730,11 +731,10 @@ export namespace Compiler { } export function doErrorBaseline(baselinePath: string, inputFiles: readonly TestFile[], errors: readonly ts.Diagnostic[], pretty?: boolean) { - Baseline.runBaseline(baselinePath.replace(/\.tsx?$/, ".errors.txt"), - !errors || (errors.length === 0) ? null : getErrorBaseline(inputFiles, errors, pretty)); // eslint-disable-line no-null/no-null + Baseline.runBaseline(baselinePath.replace(/\.tsx?$/, ".errors.txt"), !errors || (errors.length === 0) ? null : getErrorBaseline(inputFiles, errors, pretty)); // eslint-disable-line no-null/no-null } - export function doTypeAndSymbolBaseline(baselinePath: string, header: string, program: ts.Program, allFiles: {unitName: string, content: string}[], opts?: Baseline.BaselineOptions, multifile?: boolean, skipTypeBaselines?: boolean, skipSymbolBaselines?: boolean, hasErrorBaseline?: boolean) { + export function doTypeAndSymbolBaseline(baselinePath: string, header: string, program: ts.Program, allFiles: { unitName: string; content: string; }[], opts?: Baseline.BaselineOptions, multifile?: boolean, skipTypeBaselines?: boolean, skipSymbolBaselines?: boolean, hasErrorBaseline?: boolean) { // The full walker simulates the types that you would get from doing a full // compile. The pull walker simulates the types you get when you just do // a type query for a random node (like how the LS would do it). Most of the @@ -812,7 +812,7 @@ export namespace Compiler { return result ? (`//// [${header}] ////\r\n\r\n` + result) : null; // eslint-disable-line no-null/no-null } - function *iterateBaseLine(isSymbolBaseline: boolean, skipBaseline?: boolean): IterableIterator<[string, string]> { + function* iterateBaseLine(isSymbolBaseline: boolean, skipBaseline?: boolean): IterableIterator<[string, string]> { if (skipBaseline) { return; } @@ -898,7 +898,7 @@ export namespace Compiler { const anyUnfoundSources = ts.contains(sourceTDs, /*value*/ undefined); if (anyUnfoundSources) return ""; - const hash = "#base64," + ts.map([outputJSFile.text, sourcemap].concat(sourceTDs.map(td => td!.text)), (s) => ts.convertToBase64(decodeURIComponent(encodeURIComponent(s)))).join(","); + const hash = "#base64," + ts.map([outputJSFile.text, sourcemap].concat(sourceTDs.map(td => td!.text)), s => ts.convertToBase64(decodeURIComponent(encodeURIComponent(s)))).join(","); return "\n//// https://sokra.github.io/source-map-visualization" + hash + "\n"; } @@ -940,7 +940,12 @@ export namespace Compiler { } const declFileContext = prepareDeclarationCompilationContext( - toBeCompiled, otherFiles, result, harnessSettings, options, /*currentDirectory*/ undefined + toBeCompiled, + otherFiles, + result, + harnessSettings, + options, + /*currentDirectory*/ undefined, ); const declFileCompilationResult = compileDeclarationFiles(declFileContext, result.symlinks); @@ -1048,7 +1053,7 @@ function splitVaryBySettingValue(text: string, varyBy: string): string[] | undef return undefined; } - const variations: { key: string, value?: string | number }[] = []; + const variations: { key: string; value?: string | number; }[] = []; const values = getVaryByStarSettingValues(varyBy); // add (and deduplicate) all included entries @@ -1110,7 +1115,7 @@ function getVaryByStarSettingValues(varyBy: string): ReadonlyMap\s*([^\r\n]*)/gm; // multiple matches on multiple lines + const optionRegex = /^[/]{2}\s*@(\w+)\s*:\s*([^\r\n]*)/gm; // multiple matches on multiple lines + const linkRegex = /^[/]{2}\s*@link\s*:\s*([^\r\n]*)\s*->\s*([^\r\n]*)/gm; // multiple matches on multiple lines export function parseSymlinkFromTest(line: string, symlinks: vfs.FileSet | undefined, absoluteRootDir?: string) { const linkMetaData = linkRegex.exec(line); @@ -1242,7 +1247,7 @@ export namespace TestCaseParser { name: currentFileName, fileOptions: currentFileOptions, originalFilePath: fileName, - references: refs + references: refs, }; testUnitData.push(newTestFile); @@ -1280,7 +1285,7 @@ export namespace TestCaseParser { name: currentFileName, fileOptions: currentFileOptions, originalFilePath: fileName, - references: refs + references: refs, }; testUnitData.push(newTestFile2); @@ -1308,11 +1313,10 @@ export namespace TestCaseParser { } } return { files, directories: ts.arrayFrom(directories) }; - }, ts.identity); }, fileExists: fileName => testUnitData.some(data => data.name.toLowerCase() === fileName.toLowerCase()), - readFile: (name) => ts.forEach(testUnitData, data => data.name.toLowerCase() === name.toLowerCase() ? data.content : undefined) + readFile: name => ts.forEach(testUnitData, data => data.name.toLowerCase() === name.toLowerCase() ? data.content : undefined), }; // check if project has tsconfig.json in the list of files @@ -1375,7 +1379,7 @@ export namespace Baseline { } } - const fileCache: { [idx: string]: boolean } = {}; + const fileCache: { [idx: string]: boolean; } = {}; function compareToBaseline(actual: string | null, relativeFileName: string, opts: BaselineOptions | undefined) { // actual is now either undefined (the generator had an error), null (no file requested), @@ -1442,7 +1446,7 @@ export namespace Baseline { } else { if (!IO.fileExists(expected)) { - throw new Error(`New baseline created at ${IO.joinPath("tests", "baselines","local", relativeFileName)}`); + throw new Error(`New baseline created at ${IO.joinPath("tests", "baselines", "local", relativeFileName)}`); } else { throw new Error(errorMessage); @@ -1458,7 +1462,7 @@ export namespace Baseline { export function runBaseline(relativeFileName: string, actual: string | null, opts?: BaselineOptions): void { const actualFileName = localPath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder); if (actual === undefined) { - throw new Error("The generated content was \"undefined\". Return \"null\" if no baselining is required.\""); + throw new Error('The generated content was "undefined". Return "null" if no baselining is required."'); } const comparison = compareToBaseline(actual, relativeFileName, opts); writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, opts); diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index e059aad96f1f5..96db9786a565b 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -6,10 +6,14 @@ import { virtualFileSystemRoot, } from "./_namespaces/Harness"; import * as ts from "./_namespaces/ts"; -import { getNewLineCharacter } from "./_namespaces/ts"; +import { + getNewLineCharacter, +} from "./_namespaces/ts"; import * as vfs from "./_namespaces/vfs"; import * as vpath from "./_namespaces/vpath"; -import { incrementalVerifier } from "./incrementalUtils"; +import { + incrementalVerifier, +} from "./incrementalUtils"; export function makeDefaultProxy(info: ts.server.PluginCreateInfo): ts.LanguageService { const proxy = Object.create(/*o*/ null); // eslint-disable-line no-null/no-null @@ -59,7 +63,9 @@ export class ScriptInfo { this.editRanges.push({ length: this.content.length, textChangeRange: ts.createTextChangeRange( - ts.createTextSpanFromBounds(start, end), newText.length) + ts.createTextSpanFromBounds(start, end), + newText.length, + ), }); // Update version # @@ -141,8 +147,7 @@ export abstract class LanguageServiceAdapterHost { public typesRegistry: Map | undefined; private scriptInfos: collections.SortedMap; - constructor(protected cancellationToken = DefaultHostCancellationToken.instance, - protected settings = ts.getDefaultCompilerOptions()) { + constructor(protected cancellationToken = DefaultHostCancellationToken.instance, protected settings = ts.getDefaultCompilerOptions()) { this.scriptInfos = new collections.SortedMap({ comparer: this.vfs.stringComparer, sort: "insertion" }); } @@ -234,7 +239,7 @@ export abstract class LanguageServiceAdapterHost { throw new Error("No script with name '" + fileName + "'"); } - public openFile(_fileName: string, _content?: string, _scriptKindName?: string): void { /*overridden*/ } + public openFile(_fileName: string, _content?: string, _scriptKindName?: string): void {/*overridden*/} /** * @param line 0 based index @@ -269,17 +274,25 @@ class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts installPackage = ts.notImplemented; - getCompilationSettings() { return this.settings; } + getCompilationSettings() { + return this.settings; + } - getCancellationToken() { return this.cancellationToken; } + getCancellationToken() { + return this.cancellationToken; + } getDirectories(path: string): string[] { return this.sys.getDirectories(path); } - getCurrentDirectory(): string { return virtualFileSystemRoot; } + getCurrentDirectory(): string { + return virtualFileSystemRoot; + } - getDefaultLibFileName(): string { return Compiler.defaultLibFileName; } + getDefaultLibFileName(): string { + return Compiler.defaultLibFileName; + } getScriptFileNames(): string[] { return this.getFilenames().filter(ts.isAnySupportedFileExtension); @@ -290,7 +303,9 @@ class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts return script ? new ScriptSnapshot(script) : undefined; } - getScriptKind(): ts.ScriptKind { return ts.ScriptKind.Unknown; } + getScriptKind(): ts.ScriptKind { + return ts.ScriptKind.Unknown; + } getScriptVersion(fileName: string): string { const script = this.getScriptInfo(fileName); @@ -331,10 +346,18 @@ export class NativeLanguageServiceAdapter implements LanguageServiceAdapter { constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) { this.host = new NativeLanguageServiceHost(cancellationToken, options); } - getHost(): LanguageServiceAdapterHost { return this.host; } - getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.host); } - getClassifier(): ts.Classifier { return ts.createClassifier(); } - getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /*readImportFiles*/ true, ts.hasJSFileExtension(fileName)); } + getHost(): LanguageServiceAdapterHost { + return this.host; + } + getLanguageService(): ts.LanguageService { + return ts.createLanguageService(this.host); + } + getClassifier(): ts.Classifier { + return ts.createClassifier(); + } + getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { + return ts.preProcessFile(fileContents, /*readImportFiles*/ true, ts.hasJSFileExtension(fileName)); + } } /// Shim adapter @@ -356,9 +379,9 @@ class ShimLanguageServiceHost extends LanguageServiceAdapterHost implements ts.L const scriptInfo = this.getScriptInfo(fileName); return scriptInfo && scriptInfo.content; }, - useCaseSensitiveFileNames: this.useCaseSensitiveFileNames() + useCaseSensitiveFileNames: this.useCaseSensitiveFileNames(), }; - this.getModuleResolutionsForFile = (fileName) => { + this.getModuleResolutionsForFile = fileName => { const scriptInfo = this.getScriptInfo(fileName)!; const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ true); const imports: ts.MapLike = {}; @@ -370,7 +393,7 @@ class ShimLanguageServiceHost extends LanguageServiceAdapterHost implements ts.L } return JSON.stringify(imports); }; - this.getTypeReferenceDirectiveResolutionsForFile = (fileName) => { + this.getTypeReferenceDirectiveResolutionsForFile = fileName => { const scriptInfo = this.getScriptInfo(fileName); if (scriptInfo) { const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ false); @@ -391,37 +414,73 @@ class ShimLanguageServiceHost extends LanguageServiceAdapterHost implements ts.L } } - override getFilenames(): string[] { return this.nativeHost.getFilenames(); } - override getScriptInfo(fileName: string): ScriptInfo | undefined { return this.nativeHost.getScriptInfo(fileName); } - override addScript(fileName: string, content: string, isRootFile: boolean): void { this.nativeHost.addScript(fileName, content, isRootFile); } - override editScript(fileName: string, start: number, end: number, newText: string): void { this.nativeHost.editScript(fileName, start, end, newText); } - override positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter { return this.nativeHost.positionToLineAndCharacter(fileName, position); } + override getFilenames(): string[] { + return this.nativeHost.getFilenames(); + } + override getScriptInfo(fileName: string): ScriptInfo | undefined { + return this.nativeHost.getScriptInfo(fileName); + } + override addScript(fileName: string, content: string, isRootFile: boolean): void { + this.nativeHost.addScript(fileName, content, isRootFile); + } + override editScript(fileName: string, start: number, end: number, newText: string): void { + this.nativeHost.editScript(fileName, start, end, newText); + } + override positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter { + return this.nativeHost.positionToLineAndCharacter(fileName, position); + } - getCompilationSettings(): string { return JSON.stringify(this.nativeHost.getCompilationSettings()); } - getCancellationToken(): ts.HostCancellationToken { return this.nativeHost.getCancellationToken(); } - getCurrentDirectory(): string { return this.nativeHost.getCurrentDirectory(); } - getDirectories(path: string): string { return JSON.stringify(this.nativeHost.getDirectories(path)); } - getDefaultLibFileName(): string { return this.nativeHost.getDefaultLibFileName(); } - getScriptFileNames(): string { return JSON.stringify(this.nativeHost.getScriptFileNames()); } + getCompilationSettings(): string { + return JSON.stringify(this.nativeHost.getCompilationSettings()); + } + getCancellationToken(): ts.HostCancellationToken { + return this.nativeHost.getCancellationToken(); + } + getCurrentDirectory(): string { + return this.nativeHost.getCurrentDirectory(); + } + getDirectories(path: string): string { + return JSON.stringify(this.nativeHost.getDirectories(path)); + } + getDefaultLibFileName(): string { + return this.nativeHost.getDefaultLibFileName(); + } + getScriptFileNames(): string { + return JSON.stringify(this.nativeHost.getScriptFileNames()); + } getScriptSnapshot(fileName: string): ts.ScriptSnapshotShim { const nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName)!; // TODO: GH#18217 return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot); } - getScriptKind(): ts.ScriptKind { return this.nativeHost.getScriptKind(); } - getScriptVersion(fileName: string): string { return this.nativeHost.getScriptVersion(fileName); } - getLocalizedDiagnosticMessages(): string { return JSON.stringify({}); } + getScriptKind(): ts.ScriptKind { + return this.nativeHost.getScriptKind(); + } + getScriptVersion(fileName: string): string { + return this.nativeHost.getScriptVersion(fileName); + } + getLocalizedDiagnosticMessages(): string { + return JSON.stringify({}); + } readDirectory = ts.notImplemented; readDirectoryNames = ts.notImplemented; readFileNames = ts.notImplemented; - override fileExists(fileName: string) { return this.getScriptInfo(fileName) !== undefined; } + override fileExists(fileName: string) { + return this.getScriptInfo(fileName) !== undefined; + } override readFile(fileName: string) { const snapshot = this.nativeHost.getScriptSnapshot(fileName); return snapshot && ts.getSnapshotText(snapshot); } - log(s: string): void { this.nativeHost.log(s); } - trace(s: string): void { this.nativeHost.trace(s); } - error(s: string): void { this.nativeHost.error(s); } + log(s: string): void { + this.nativeHost.log(s); + } + trace(s: string): void { + this.nativeHost.trace(s); + } + error(s: string): void { + this.nativeHost.error(s); + } override directoryExists(): boolean { // for tests pessimistically assume that directory always exists return true; @@ -443,7 +502,7 @@ class ClassifierShimProxy implements ts.Classifier { for (; i < result.length - 1; i += 2) { const t = entries[i / 2] = { length: parseInt(result[i]), - classification: parseInt(result[i + 1]) + classification: parseInt(result[i + 1]), }; assert.isTrue(t.length > 0, "Result length should be greater than 0, got :" + t.length); @@ -455,7 +514,7 @@ class ClassifierShimProxy implements ts.Classifier { return { finalLexState, - entries + entries, }; } } @@ -618,7 +677,7 @@ class LanguageServiceShimProxy implements ts.LanguageService { getApplicableRefactors(): ts.ApplicableRefactorInfo[] { throw new Error("Not supported on the shim."); } - getMoveToRefactoringFileSuggestions(): { newFileName: string, files: string[] } { + getMoveToRefactoringFileSuggestions(): { newFileName: string; files: string[]; } { throw new Error("Not supported on the shim."); } organizeImports(_args: ts.OrganizeImportsArgs, _formatOptions: ts.FormatCodeSettings): readonly ts.FileTextChanges[] { @@ -678,7 +737,9 @@ class LanguageServiceShimProxy implements ts.LanguageService { uncommentSelection(fileName: string, textRange: ts.TextRange): ts.TextChange[] { return unwrapJSONCallResult(this.shim.uncommentSelection(fileName, textRange)); } - dispose(): void { this.shim.dispose({}); } + dispose(): void { + this.shim.dispose({}); + } } export class ShimLanguageServiceAdapter implements LanguageServiceAdapter { @@ -688,9 +749,15 @@ export class ShimLanguageServiceAdapter implements LanguageServiceAdapter { this.host = new ShimLanguageServiceHost(preprocessToResolve, cancellationToken, options); this.factory = new ts.TypeScriptServicesFactory(); } - getHost() { return this.host; } - getLanguageService(): ts.LanguageService { return new LanguageServiceShimProxy(this.factory.createLanguageServiceShim(this.host)); } - getClassifier(): ts.Classifier { return new ClassifierShimProxy(this.factory.createClassifierShim(this.host)); } + getHost() { + return this.host; + } + getLanguageService(): ts.LanguageService { + return new LanguageServiceShimProxy(this.factory.createLanguageServiceShim(this.host)); + } + getClassifier(): ts.Classifier { + return new ClassifierShimProxy(this.factory.createClassifierShim(this.host)); + } getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { const coreServicesShim = this.factory.createCoreServicesShim(this.host); const shimResult: { @@ -706,14 +773,14 @@ export class ShimLanguageServiceAdapter implements LanguageServiceAdapter { ambientExternalModules: [], isLibFile: shimResult.isLibFile, typeReferenceDirectives: [], - libReferenceDirectives: [] + libReferenceDirectives: [], }; ts.forEach(shimResult.referencedFiles, refFile => { convertResult.referencedFiles.push({ fileName: refFile.path, pos: refFile.position, - end: refFile.position + refFile.length + end: refFile.position + refFile.length, }); }); @@ -721,7 +788,7 @@ export class ShimLanguageServiceAdapter implements LanguageServiceAdapter { convertResult.importedFiles.push({ fileName: importedFile.path, pos: importedFile.position, - end: importedFile.position + importedFile.length + end: importedFile.position + importedFile.length, }); }); @@ -729,7 +796,7 @@ export class ShimLanguageServiceAdapter implements LanguageServiceAdapter { convertResult.importedFiles.push({ fileName: typeRefDirective.path, pos: typeRefDirective.position, - end: typeRefDirective.position + typeRefDirective.length + end: typeRefDirective.position + typeRefDirective.length, }); }); return convertResult; @@ -863,8 +930,12 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger { return false; } - startGroup() { throw ts.notImplemented(); } - endGroup() { throw ts.notImplemented(); } + startGroup() { + throw ts.notImplemented(); + } + endGroup() { + throw ts.notImplemented(); + } perftrc(message: string): void { return this.host.log(message); @@ -912,9 +983,9 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger { }; return proxy; - } + }, }), - error: undefined + error: undefined, }; // Throws during initialization @@ -923,9 +994,9 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger { module: () => ({ create() { throw new Error("I am not a well-behaved plugin"); - } + }, }), - error: undefined + error: undefined, }; // Adds another diagnostic @@ -943,14 +1014,14 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger { code: 9999, length: 3, messageText: `Plugin diagnostic`, - start: 0 + start: 0, }); return prev; }; return proxy; - } + }, }), - error: undefined + error: undefined, }; // Accepts configurations @@ -970,7 +1041,7 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger { code: 9999, length: 3, messageText: customMessage, - start: 0 + start: 0, }); return prev; }; @@ -978,15 +1049,15 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger { }, onConfigurationChanged(config: any) { customMessage = config.message; - } + }, }), - error: undefined + error: undefined, }; default: return { module: undefined, - error: new Error("Could not resolve module") + error: new Error("Could not resolve module"), }; } } @@ -1024,7 +1095,6 @@ export class ServerLanguageServiceAdapter implements LanguageServiceAdapter { }; this.server = new FourslashSession(opts); - // Fake the connection between the client and the server serverHost.writeMessage = client.onMessage.bind(client); clientHost.writeMessage = this.server.onMessage.bind(this.server); @@ -1037,23 +1107,34 @@ export class ServerLanguageServiceAdapter implements LanguageServiceAdapter { this.client = client; this.host = clientHost; } - getHost() { return this.host; } - getLanguageService(): ts.LanguageService { return this.client; } - getClassifier(): ts.Classifier { throw new Error("getClassifier is not available using the server interface."); } - getPreProcessedFileInfo(): ts.PreProcessedFileInfo { throw new Error("getPreProcessedFileInfo is not available using the server interface."); } + getHost() { + return this.host; + } + getLanguageService(): ts.LanguageService { + return this.client; + } + getClassifier(): ts.Classifier { + throw new Error("getClassifier is not available using the server interface."); + } + getPreProcessedFileInfo(): ts.PreProcessedFileInfo { + throw new Error("getPreProcessedFileInfo is not available using the server interface."); + } assertTextConsistent(fileName: string) { const serverText = this.server.getText(fileName); const clientText = this.host.readFile(fileName); - ts.Debug.assert(serverText === clientText, [ - "Server and client text are inconsistent.", - "", - "\x1b[1mServer\x1b[0m\x1b[31m:", - serverText, - "", - "\x1b[1mClient\x1b[0m\x1b[31m:", - clientText, - "", - "This probably means something is wrong with the fourslash infrastructure, not with the test." - ].join(ts.sys.newLine)); + ts.Debug.assert( + serverText === clientText, + [ + "Server and client text are inconsistent.", + "", + "\x1b[1mServer\x1b[0m\x1b[31m:", + serverText, + "", + "\x1b[1mClient\x1b[0m\x1b[31m:", + clientText, + "", + "This probably means something is wrong with the fourslash infrastructure, not with the test.", + ].join(ts.sys.newLine), + ); } } diff --git a/src/harness/harnessUtils.ts b/src/harness/harnessUtils.ts index beee8048030a8..95c6068ab0702 100644 --- a/src/harness/harnessUtils.ts +++ b/src/harness/harnessUtils.ts @@ -91,23 +91,21 @@ export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | un // Make sure each of the children is in order. let currentPos = 0; - ts.forEachChild(node, - child => { - assert.isFalse(child.pos < currentPos, "child.pos < currentPos"); - currentPos = child.end; - }, - array => { - assert.isFalse(array.pos < node.pos, "array.pos < node.pos"); - assert.isFalse(array.end > node.end, "array.end > node.end"); - assert.isFalse(array.pos < currentPos, "array.pos < currentPos"); - - for (const item of array) { - assert.isFalse(item.pos < currentPos, "array[i].pos < currentPos"); - currentPos = item.end; - } + ts.forEachChild(node, child => { + assert.isFalse(child.pos < currentPos, "child.pos < currentPos"); + currentPos = child.end; + }, array => { + assert.isFalse(array.pos < node.pos, "array.pos < node.pos"); + assert.isFalse(array.end > node.end, "array.end > node.end"); + assert.isFalse(array.pos < currentPos, "array.pos < currentPos"); - currentPos = array.end; - }); + for (const item of array) { + assert.isFalse(item.pos < currentPos, "array[i].pos < currentPos"); + currentPos = item.end; + } + + currentPos = array.end; + }); const childNodesAndArrays: any[] = []; ts.forEachChild(node, child => { @@ -117,7 +115,8 @@ export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | un }); for (const childName in node) { - if (childName === "parent" || + if ( + childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator" || @@ -133,13 +132,13 @@ export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | un childName === "illegalQuestionToken" || childName === "illegalExclamationToken" || childName === "illegalTypeParameters" || - childName === "illegalType") { + childName === "illegalType" + ) { continue; } const child = (node as any)[childName]; if (isNodeOrArray(child)) { - assert.isFalse(childNodesAndArrays.indexOf(child) < 0, - "Missing child when forEach'ing over node: " + ts.Debug.formatSyntaxKind(node.kind) + "-" + childName); + assert.isFalse(childNodesAndArrays.indexOf(child) < 0, "Missing child when forEach'ing over node: " + ts.Debug.formatSyntaxKind(node.kind) + "-" + childName); } } } @@ -160,7 +159,7 @@ function convertDiagnostic(diagnostic: ts.Diagnostic) { length: diagnostic.length, messageText: ts.flattenDiagnosticMessageText(diagnostic.messageText, Harness.IO.newLine()), category: ts.diagnosticCategoryName(diagnostic, /*lowerCase*/ false), - code: diagnostic.code + code: diagnostic.code, }; } @@ -270,7 +269,9 @@ export function assertDiagnosticsEquals(array1: readonly ts.Diagnostic[], array2 assert.equal(d1.length, d2.length, "d1.length !== d2.length"); assert.equal( ts.flattenDiagnosticMessageText(d1.messageText, Harness.IO.newLine()), - ts.flattenDiagnosticMessageText(d2.messageText, Harness.IO.newLine()), "d1.messageText !== d2.messageText"); + ts.flattenDiagnosticMessageText(d2.messageText, Harness.IO.newLine()), + "d1.messageText !== d2.messageText", + ); assert.equal(d1.category, d2.category, "d1.category !== d2.category"); assert.equal(d1.code, d2.code, "d1.code !== d2.code"); } @@ -292,19 +293,17 @@ export function assertStructuralEquals(node1: ts.Node, node2: ts.Node) { assert.equal(ts.containsParseError(node1), ts.containsParseError(node2)); assert.equal(node1.flags & ~ts.NodeFlags.ReachabilityAndEmitFlags, node2.flags & ~ts.NodeFlags.ReachabilityAndEmitFlags, "node1.flags !== node2.flags"); - ts.forEachChild(node1, - child1 => { - const childName = findChildName(node1, child1); - const child2: ts.Node = (node2 as any)[childName]; + ts.forEachChild(node1, child1 => { + const childName = findChildName(node1, child1); + const child2: ts.Node = (node2 as any)[childName]; - assertStructuralEquals(child1, child2); - }, - array1 => { - const childName = findChildName(node1, array1); - const array2: ts.NodeArray = (node2 as any)[childName]; + assertStructuralEquals(child1, child2); + }, array1 => { + const childName = findChildName(node1, array1); + const array2: ts.NodeArray = (node2 as any)[childName]; - assertArrayStructuralEquals(array1, array2); - }); + assertArrayStructuralEquals(array1, array2); + }); } function assertArrayStructuralEquals(array1: ts.NodeArray, array2: ts.NodeArray) { @@ -344,9 +343,11 @@ export function filterStack(error: Error, stackTraceLimit = Infinity) { let harnessFrameCount = 0; for (let line of lines) { if (isStackFrame(line)) { - if (frameCount >= stackTraceLimit + if ( + frameCount >= stackTraceLimit || isMocha(line) - || isNode(line)) { + || isNode(line) + ) { continue; } diff --git a/src/harness/incrementalUtils.ts b/src/harness/incrementalUtils.ts index b1f517b2fd89f..5aa4c16b927aa 100644 --- a/src/harness/incrementalUtils.ts +++ b/src/harness/incrementalUtils.ts @@ -33,29 +33,37 @@ function verifyDocumentRegistryStats( ); } else { - entry.forEach((real, kind) => ts.Debug.assert( - real.languageServiceRefCount === expected?.get(kind), - `Document registry has unexpected language service ref count for ${key} ${path} ${ts.Debug.formatScriptKind(kind)} ${real.languageServiceRefCount}`, - reportStats, - )); - expected?.forEach((value, kind) => ts.Debug.assert( - entry.has(kind), - `Document registry expected language service ref count for ${key} ${path} ${ts.Debug.formatScriptKind(kind)} ${value}`, - reportStats, - )); + entry.forEach((real, kind) => + ts.Debug.assert( + real.languageServiceRefCount === expected?.get(kind), + `Document registry has unexpected language service ref count for ${key} ${path} ${ts.Debug.formatScriptKind(kind)} ${real.languageServiceRefCount}`, + reportStats, + ) + ); + expected?.forEach((value, kind) => + ts.Debug.assert( + entry.has(kind), + `Document registry expected language service ref count for ${key} ${path} ${ts.Debug.formatScriptKind(kind)} ${value}`, + reportStats, + ) + ); } }); - statsByPath?.forEach((_value, path) => ts.Debug.assert( - bucketEntries.has(path), - `Document registry does not contain entry for ${key}, ${path}`, - reportStats, - )); + statsByPath?.forEach((_value, path) => + ts.Debug.assert( + bucketEntries.has(path), + `Document registry does not contain entry for ${key}, ${path}`, + reportStats, + ) + ); }); - stats.forEach((_value, key) => ts.Debug.assert( - documentRegistry.getBuckets().has(key), - `Document registry does not contain entry for key: ${key}`, - reportStats, - )); + stats.forEach((_value, key) => + ts.Debug.assert( + documentRegistry.getBuckets().has(key), + `Document registry does not contain entry for key: ${key}`, + reportStats, + ) + ); function reportStats() { const str: string[] = ["", "Actual::", ...reportDocumentRegistryStats(documentRegistry)]; @@ -97,4 +105,4 @@ function verifyDocumentRegistry(service: ts.server.ProjectService) { export function incrementalVerifier(service: ts.server.ProjectService) { service.verifyDocumentRegistry = () => verifyDocumentRegistry(service); -} \ No newline at end of file +} diff --git a/src/harness/runnerbase.ts b/src/harness/runnerbase.ts index 41f4ca2469f44..3401301a08ca5 100644 --- a/src/harness/runnerbase.ts +++ b/src/harness/runnerbase.ts @@ -29,7 +29,7 @@ export abstract class RunnerBase { this.tests.push(fileName); } - public enumerateFiles(folder: string, regex?: RegExp, options?: { recursive: boolean }): string[] { + public enumerateFiles(folder: string, regex?: RegExp, options?: { recursive: boolean; }): string[] { return ts.map(IO.listFiles(userSpecifiedRoot + folder, regex, { recursive: (options ? options.recursive : false) }), ts.normalizeSlashes); } diff --git a/src/harness/sourceMapRecorder.ts b/src/harness/sourceMapRecorder.ts index 00852dbc1ccd2..9f0a906ed3218 100644 --- a/src/harness/sourceMapRecorder.ts +++ b/src/harness/sourceMapRecorder.ts @@ -1,5 +1,7 @@ import * as documents from "./_namespaces/documents"; -import { Compiler } from "./_namespaces/Harness"; +import { + Compiler, +} from "./_namespaces/Harness"; import * as ts from "./_namespaces/ts"; import * as Utils from "./_namespaces/Utils"; @@ -149,7 +151,6 @@ namespace SourceMapSpanWriter { if (!SourceMapDecoder.hasCompletedDecoding()) { sourceMapRecorder.WriteLine("!!!! **** There are more source map entries in the sourceMap's mapping than what was encoded"); sourceMapRecorder.WriteLine("!!!! **** Remaining decoded string: " + SourceMapDecoder.getRemainingDecodeString()); - } // write remaining js lines diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts index 3d3602b32decd..5cb9e7149da87 100644 --- a/src/harness/typeWriter.ts +++ b/src/harness/typeWriter.ts @@ -123,7 +123,8 @@ export class TypeWriterWalker { // return `error`s via `getTypeAtLocation` // But this is generally expected, so we don't call those out, either let typeString: string; - if (!this.hadErrorBaseline && + if ( + !this.hadErrorBaseline && type.flags & ts.TypeFlags.Any && !ts.isBindingElement(node.parent) && !ts.isPropertyAccessOrQualifiedName(node.parent) && @@ -132,7 +133,8 @@ export class TypeWriterWalker { !ts.isMetaProperty(node.parent) && !this.isImportStatementName(node) && !this.isExportStatementName(node) && - !this.isIntrinsicJsxTag(node)) { + !this.isIntrinsicJsxTag(node) + ) { typeString = (type as ts.IntrinsicType).intrinsicName; } else { @@ -147,7 +149,7 @@ export class TypeWriterWalker { line: lineAndCharacter.line, syntaxKind: node.kind, sourceText, - type: typeString + type: typeString, }; } const symbol = this.checker.getSymbolAtLocation(node); @@ -172,7 +174,7 @@ export class TypeWriterWalker { const declLineAndCharacter = declSourceFile.getLineAndCharacterOfPosition(declaration.pos); const fileName = ts.getBaseFileName(declSourceFile.fileName); const isLibFile = /lib(.*)\.d\.ts/i.test(fileName); - const declText = `Decl(${ fileName }, ${ isLibFile ? "--" : declLineAndCharacter.line }, ${ isLibFile ? "--" : declLineAndCharacter.character })`; + const declText = `Decl(${fileName}, ${isLibFile ? "--" : declLineAndCharacter.line}, ${isLibFile ? "--" : declLineAndCharacter.character})`; symbolString += declText; (declaration as any).__symbolTestOutputCache = declText; } @@ -182,7 +184,7 @@ export class TypeWriterWalker { line: lineAndCharacter.line, syntaxKind: node.kind, sourceText, - symbol: symbolString + symbol: symbolString, }; } } diff --git a/src/harness/util.ts b/src/harness/util.ts index 607e527459173..3a4a78f724009 100644 --- a/src/harness/util.ts +++ b/src/harness/util.ts @@ -18,7 +18,8 @@ function createDiagnosticMessageReplacer [entry, compilerVersion, moduleName]); + ([entry, , moduleName], compilerVersion) => [entry, compilerVersion, moduleName], +); export function sanitizeTraceResolutionLogEntry(text: string) { return text && replaceTypesVersionsMessage(text, "3.1.0-dev"); diff --git a/src/harness/vfsUtil.ts b/src/harness/vfsUtil.ts index 6968b34914d81..5d34d0bf15fb5 100644 --- a/src/harness/vfsUtil.ts +++ b/src/harness/vfsUtil.ts @@ -25,14 +25,14 @@ export const testLibFolder = "/.lib"; export const srcFolder = "/.src"; // file type -const S_IFMT = 0o170000; // file type -const S_IFSOCK = 0o140000; // socket -const S_IFLNK = 0o120000; // symbolic link -const S_IFREG = 0o100000; // regular file -const S_IFBLK = 0o060000; // block device -const S_IFDIR = 0o040000; // directory -const S_IFCHR = 0o020000; // character device -const S_IFIFO = 0o010000; // FIFO +const S_IFMT = 0o170000; // file type +const S_IFSOCK = 0o140000; // socket +const S_IFLNK = 0o120000; // symbolic link +const S_IFREG = 0o100000; // regular file +const S_IFBLK = 0o060000; // block device +const S_IFDIR = 0o040000; // directory +const S_IFCHR = 0o020000; // character device +const S_IFIFO = 0o010000; // FIFO let devCount = 0; // A monotonically increasing count of device ids let inoCount = 0; // A monotonically increasing count of inodes @@ -455,7 +455,6 @@ export class FileSystem { return this._stat(this._walk(this._resolve(path), /*noFollow*/ true)); } - private _stat(entry: WalkResult) { const node = entry.node; if (!node) throw createIOError(`ENOENT`, entry.realpath); @@ -768,9 +767,11 @@ export class FileSystem { if (isEmptyNonShadowedDirectory(changedNode) && isEmptyNonShadowedDirectory(baseNode)) return false; // no difference if both nodes are unpopulated and point to the same mounted file system - if (!changedNode.links && !baseNode.links && + if ( + !changedNode.links && !baseNode.links && changedNode.resolver && changedNode.source !== undefined && - baseNode.resolver === changedNode.resolver && baseNode.source === changedNode.source) return false; + baseNode.resolver === changedNode.resolver && baseNode.source === changedNode.source + ) return false; // no difference if both nodes have identical children const children: FileSet = {}; @@ -793,9 +794,11 @@ export class FileSystem { if (isEmptyNonShadowedFile(changedNode) && isEmptyNonShadowedFile(baseNode)) return false; // no difference if both nodes are unpopulated and point to the same mounted file system - if (!changedNode.buffer && !baseNode.buffer && + if ( + !changedNode.buffer && !baseNode.buffer && changedNode.resolver && changedNode.source !== undefined && - baseNode.resolver === changedNode.resolver && baseNode.source === changedNode.source) return false; + baseNode.resolver === changedNode.resolver && baseNode.source === changedNode.source + ) return false; const changedBuffer = changed._getBuffer(changedNode); const baseBuffer = base._getBuffer(baseNode); @@ -871,7 +874,7 @@ export class FileSystem { mtimeMs: time, ctimeMs: time, birthtimeMs: time, - nlink: 0 + nlink: 0, }; } @@ -964,7 +967,7 @@ export class FileSystem { ctimeMs: root.ctimeMs, birthtimeMs: root.birthtimeMs, nlink: root.nlink, - shadowRoot: root + shadowRoot: root, }; if (isSymlink(root)) (shadow as SymlinkInode).symlink = root.symlink; @@ -1218,7 +1221,7 @@ export function createResolver(host: FileSystemResolverHost): FileSystemResolver }, readFileSync(path: string): Buffer { return ts.sys.bufferFrom!(host.readFile(path)!, "utf8") as Buffer; // TODO: GH#18217 - } + }, }; } @@ -1309,13 +1312,27 @@ export class Stats { this.birthtime = new Date(this.birthtimeMs); } - public isFile() { return (this.mode & S_IFMT) === S_IFREG; } - public isDirectory() { return (this.mode & S_IFMT) === S_IFDIR; } - public isSymbolicLink() { return (this.mode & S_IFMT) === S_IFLNK; } - public isBlockDevice() { return (this.mode & S_IFMT) === S_IFBLK; } - public isCharacterDevice() { return (this.mode & S_IFMT) === S_IFCHR; } - public isFIFO() { return (this.mode & S_IFMT) === S_IFIFO; } - public isSocket() { return (this.mode & S_IFMT) === S_IFSOCK; } + public isFile() { + return (this.mode & S_IFMT) === S_IFREG; + } + public isDirectory() { + return (this.mode & S_IFMT) === S_IFDIR; + } + public isSymbolicLink() { + return (this.mode & S_IFMT) === S_IFLNK; + } + public isBlockDevice() { + return (this.mode & S_IFMT) === S_IFBLK; + } + public isCharacterDevice() { + return (this.mode & S_IFMT) === S_IFCHR; + } + public isFIFO() { + return (this.mode & S_IFMT) === S_IFIFO; + } + public isSocket() { + return (this.mode & S_IFMT) === S_IFSOCK; + } } export const IOErrorMessages = Object.freeze({ @@ -1330,7 +1347,7 @@ export const IOErrorMessages = Object.freeze({ EINVAL: "invalid value", ENOTEMPTY: "directory not empty", EPERM: "operation not permitted", - EROFS: "file system is read-only" + EROFS: "file system is read-only", }); export function createIOError(code: keyof typeof IOErrorMessages, details = "") { @@ -1354,7 +1371,7 @@ export type FileLike = File | Buffer | string; export class Directory { public readonly files: FileSet; public readonly meta: Record | undefined; - constructor(files: FileSet, { meta }: { meta?: Record } = {}) { + constructor(files: FileSet, { meta }: { meta?: Record; } = {}) { this.files = files; this.meta = meta; } @@ -1365,7 +1382,7 @@ export class File { public readonly data: Buffer | string; public readonly encoding: string | undefined; public readonly meta: Record | undefined; - constructor(data: Buffer | string, { meta, encoding }: { encoding?: string, meta?: Record } = {}) { + constructor(data: Buffer | string, { meta, encoding }: { encoding?: string; meta?: Record; } = {}) { this.data = data; this.encoding = encoding; this.meta = meta; @@ -1373,13 +1390,13 @@ export class File { } export class SameFileContentFile extends File { - constructor(data: Buffer | string, metaAndEncoding?: { encoding?: string, meta?: Record }) { + constructor(data: Buffer | string, metaAndEncoding?: { encoding?: string; meta?: Record; }) { super(data, metaAndEncoding); } } export class SameFileWithModifiedTime extends File { - constructor(data: Buffer | string, metaAndEncoding?: { encoding?: string, meta?: Record }) { + constructor(data: Buffer | string, metaAndEncoding?: { encoding?: string; meta?: Record; }) { super(data, metaAndEncoding); } } @@ -1406,7 +1423,7 @@ export class Unlink { export class Symlink { public readonly symlink: string; public readonly meta: Record | undefined; - constructor(symlink: string, { meta }: { meta?: Record } = {}) { + constructor(symlink: string, { meta }: { meta?: Record; } = {}) { this.symlink = symlink; this.meta = meta; } @@ -1417,7 +1434,7 @@ export class Mount { public readonly source: string; public readonly resolver: FileSystemResolver; public readonly meta: Record | undefined; - constructor(source: string, resolver: FileSystemResolver, { meta }: { meta?: Record } = {}) { + constructor(source: string, resolver: FileSystemResolver, { meta }: { meta?: Record; } = {}) { this.source = source; this.resolver = resolver; this.meta = meta; @@ -1519,10 +1536,10 @@ function getBuiltLocal(host: FileSystemResolverHost, ignoreCase: boolean): FileS [builtFolder]: new Mount(vpath.resolve(host.getWorkspaceRoot(), "built/local"), resolver), [testLibFolder]: new Mount(vpath.resolve(host.getWorkspaceRoot(), "tests/lib"), resolver), [projectsFolder]: new Mount(vpath.resolve(host.getWorkspaceRoot(), "tests/projects"), resolver), - [srcFolder]: {} + [srcFolder]: {}, }, cwd: srcFolder, - meta: { defaultLibLocation: builtFolder } + meta: { defaultLibLocation: builtFolder }, }); builtLocalCI.makeReadonly(); } @@ -1536,7 +1553,8 @@ function getBuiltLocal(host: FileSystemResolverHost, ignoreCase: boolean): FileS /* eslint-disable no-null/no-null */ function normalizeFileSetEntry(value: FileSet[string]) { - if (value === undefined || + if ( + value === undefined || value === null || value instanceof Directory || value instanceof File || @@ -1544,7 +1562,8 @@ function normalizeFileSetEntry(value: FileSet[string]) { value instanceof Symlink || value instanceof Mount || value instanceof Rmdir || - value instanceof Unlink) { + value instanceof Unlink + ) { return value; } return typeof value === "string" || Buffer.isBuffer(value) ? new File(value) : new Directory(value); diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index 1983107b35548..b2c186d6ede10 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -107,7 +107,7 @@ const unprefixedNodeCoreModuleList = [ "vm", "wasi", "worker_threads", - "zlib" + "zlib", ]; /** @internal */ @@ -167,9 +167,8 @@ export function discoverTypings( typeAcquisition: TypeAcquisition, unresolvedImports: readonly string[], typesRegistry: ReadonlyMap>, - compilerOptions: CompilerOptions): - { cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } { - + compilerOptions: CompilerOptions, +): { cachedTypingPaths: string[]; newTypingNames: string[]; filesToWatch: string[]; } { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } @@ -194,13 +193,13 @@ export function discoverTypings( if (!compilerOptions.types) { const possibleSearchDirs = new Set(fileNames.map(getDirectoryPath)); possibleSearchDirs.add(projectRootPath); - possibleSearchDirs.forEach((searchDir) => { + possibleSearchDirs.forEach(searchDir => { getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); }); } - if(!typeAcquisition.disableFilenameBasedTypeAcquisition) { + if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); } // add typings for unresolved imports @@ -208,7 +207,8 @@ export function discoverTypings( const module = deduplicate( unresolvedImports.map(nonRelativeModuleNameForTypingCache), equateStringsCaseSensitive, - compareStringsCaseSensitive); + compareStringsCaseSensitive, + ); addInferredTypings(module, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed @@ -383,7 +383,7 @@ export const enum NameValidationResult { NameTooLong, NameStartsWithDot, NameStartsWithUnderscore, - NameContainsNonURISafeCharacters + NameContainsNonURISafeCharacters, } const maxPackageNameLength = 214; diff --git a/src/lib/decorators.d.ts b/src/lib/decorators.d.ts index 977fa5fc5deb0..69b2d9ec3d970 100644 --- a/src/lib/decorators.d.ts +++ b/src/lib/decorators.d.ts @@ -6,21 +6,18 @@ type ClassMemberDecoratorContext = | ClassGetterDecoratorContext | ClassSetterDecoratorContext | ClassFieldDecoratorContext - | ClassAccessorDecoratorContext - ; + | ClassAccessorDecoratorContext; /** * The decorator context types provided to any decorator. */ type DecoratorContext = | ClassDecoratorContext - | ClassMemberDecoratorContext - ; + | ClassMemberDecoratorContext; type DecoratorMetadataObject = Record & object; -type DecoratorMetadata = - typeof globalThis extends { Symbol: { readonly metadata: symbol } } ? DecoratorMetadataObject : DecoratorMetadataObject | undefined; +type DecoratorMetadata = typeof globalThis extends { Symbol: { readonly metadata: symbol; }; } ? DecoratorMetadataObject : DecoratorMetadataObject | undefined; /** * Context provided to a class decorator. diff --git a/src/lib/dom.iterable.d.ts b/src/lib/dom.iterable.d.ts index 2c968671a1a42..8ffbcd4811b55 100644 --- a/src/lib/dom.iterable.d.ts +++ b/src/lib/dom.iterable.d.ts @@ -41,12 +41,10 @@ interface NodeList { */ values(): IterableIterator; - [Symbol.iterator](): IterableIterator; } interface NodeListOf { - /** * Returns an array of key, value pairs for every entry in the list */ diff --git a/src/lib/es2015.collection.d.ts b/src/lib/es2015.collection.d.ts index 122e30666ab27..e88f0d4c3b405 100644 --- a/src/lib/es2015.collection.d.ts +++ b/src/lib/es2015.collection.d.ts @@ -1,5 +1,4 @@ interface Map { - clear(): void; /** * @returns true if an element in the Map existed and has been removed, or false if the element does not exist. @@ -29,7 +28,7 @@ interface Map { } interface MapConstructor { - new(): Map; + new (): Map; new (entries?: readonly (readonly [K, V])[] | null): Map; readonly prototype: Map; } diff --git a/src/lib/es2015.core.d.ts b/src/lib/es2015.core.d.ts index 3b1c76c5afc3c..397e19639a3d9 100644 --- a/src/lib/es2015.core.d.ts +++ b/src/lib/es2015.core.d.ts @@ -535,5 +535,5 @@ interface StringConstructor { * @param template A well-formed template string call site representation. * @param substitutions A set of substitution values. */ - raw(template: { raw: readonly string[] | ArrayLike}, ...substitutions: any[]): string; + raw(template: { raw: readonly string[] | ArrayLike; }, ...substitutions: any[]): string; } diff --git a/src/lib/es2015.iterable.d.ts b/src/lib/es2015.iterable.d.ts index c7b7afa72119d..d28b8381eec86 100644 --- a/src/lib/es2015.iterable.d.ts +++ b/src/lib/es2015.iterable.d.ts @@ -137,11 +137,11 @@ interface ReadonlyMap { } interface MapConstructor { - new(): Map; + new (): Map; new (iterable?: Iterable | null): Map; } -interface WeakMap { } +interface WeakMap {} interface WeakMapConstructor { new (iterable: Iterable): WeakMap; @@ -189,13 +189,13 @@ interface SetConstructor { new (iterable?: Iterable | null): Set; } -interface WeakSet { } +interface WeakSet {} interface WeakSetConstructor { new (iterable: Iterable): WeakSet; } -interface Promise { } +interface Promise {} interface PromiseConstructor { /** @@ -297,7 +297,6 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { new (elements: Iterable): Uint8ClampedArray; - /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. diff --git a/src/lib/es2015.promise.d.ts b/src/lib/es2015.promise.d.ts index 68b476d8c2fc6..e4925d8b14962 100644 --- a/src/lib/es2015.promise.d.ts +++ b/src/lib/es2015.promise.d.ts @@ -18,7 +18,7 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: T): Promise<{ -readonly [P in keyof T]: Awaited }>; + all(values: T): Promise<{ -readonly [P in keyof T]: Awaited; }>; // see: lib.es2015.iterable.d.ts // all(values: Iterable>): Promise[]>; diff --git a/src/lib/es2015.symbol.d.ts b/src/lib/es2015.symbol.d.ts index 5ef7ff4bb0ee4..9ede0239fafbe 100644 --- a/src/lib/es2015.symbol.d.ts +++ b/src/lib/es2015.symbol.d.ts @@ -25,4 +25,4 @@ interface SymbolConstructor { keyFor(sym: symbol): string | undefined; } -declare var Symbol: SymbolConstructor; \ No newline at end of file +declare var Symbol: SymbolConstructor; diff --git a/src/lib/es2016.array.include.d.ts b/src/lib/es2016.array.include.d.ts index 1012c18407b0b..00ce45267012a 100644 --- a/src/lib/es2016.array.include.d.ts +++ b/src/lib/es2016.array.include.d.ts @@ -95,4 +95,4 @@ interface Float64Array { * @param fromIndex The position in this array at which to begin searching for searchElement. */ includes(searchElement: number, fromIndex?: number): boolean; -} \ No newline at end of file +} diff --git a/src/lib/es2016.d.ts b/src/lib/es2016.d.ts index fc1aab7798cac..b87f4c2c4f3a1 100644 --- a/src/lib/es2016.d.ts +++ b/src/lib/es2016.d.ts @@ -1,2 +1,2 @@ /// -/// \ No newline at end of file +/// diff --git a/src/lib/es2016.full.d.ts b/src/lib/es2016.full.d.ts index 0f1fd4349daa4..5dda8cc35e785 100644 --- a/src/lib/es2016.full.d.ts +++ b/src/lib/es2016.full.d.ts @@ -2,4 +2,4 @@ /// /// /// -/// \ No newline at end of file +/// diff --git a/src/lib/es2017.full.d.ts b/src/lib/es2017.full.d.ts index 82c358f31e18e..ab03ea04d4844 100644 --- a/src/lib/es2017.full.d.ts +++ b/src/lib/es2017.full.d.ts @@ -2,4 +2,4 @@ /// /// /// -/// \ No newline at end of file +/// diff --git a/src/lib/es2017.intl.d.ts b/src/lib/es2017.intl.d.ts index 2f9efc15fbbae..3ec15630c3e4a 100644 --- a/src/lib/es2017.intl.d.ts +++ b/src/lib/es2017.intl.d.ts @@ -1,17 +1,16 @@ declare namespace Intl { - interface DateTimeFormatPartTypesRegistry { - day: any - dayPeriod: any - era: any - hour: any - literal: any - minute: any - month: any - second: any - timeZoneName: any - weekday: any - year: any + day: any; + dayPeriod: any; + era: any; + hour: any; + literal: any; + minute: any; + month: any; + second: any; + timeZoneName: any; + weekday: any; + year: any; } type DateTimeFormatPartTypes = keyof DateTimeFormatPartTypesRegistry; diff --git a/src/lib/es2017.object.d.ts b/src/lib/es2017.object.d.ts index b3ace85bef182..139cc5b81ba39 100644 --- a/src/lib/es2017.object.d.ts +++ b/src/lib/es2017.object.d.ts @@ -3,7 +3,7 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties 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. */ - values(o: { [s: string]: T } | ArrayLike): T[]; + values(o: { [s: string]: T; } | ArrayLike): T[]; /** * Returns an array of values of the enumerable properties of an object @@ -15,7 +15,7 @@ interface ObjectConstructor { * Returns an array of key/values of the enumerable properties 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. */ - entries(o: { [s: string]: T } | ArrayLike): [string, T][]; + entries(o: { [s: string]: T; } | ArrayLike): [string, T][]; /** * Returns an array of key/values of the enumerable properties of an object @@ -27,5 +27,5 @@ interface ObjectConstructor { * Returns an object containing all own property descriptors 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. */ - getOwnPropertyDescriptors(o: T): {[P in keyof T]: TypedPropertyDescriptor} & { [x: string]: PropertyDescriptor }; + getOwnPropertyDescriptors(o: T): { [P in keyof T]: TypedPropertyDescriptor; } & { [x: string]: PropertyDescriptor; }; } diff --git a/src/lib/es2018.asynciterable.d.ts b/src/lib/es2018.asynciterable.d.ts index c19b8d34cd538..0fe799e21055e 100644 --- a/src/lib/es2018.asynciterable.d.ts +++ b/src/lib/es2018.asynciterable.d.ts @@ -22,4 +22,4 @@ interface AsyncIterable { interface AsyncIterableIterator extends AsyncIterator { [Symbol.asyncIterator](): AsyncIterableIterator; -} \ No newline at end of file +} diff --git a/src/lib/es2018.full.d.ts b/src/lib/es2018.full.d.ts index 0f38d44ca5e6c..e887270b82a2d 100644 --- a/src/lib/es2018.full.d.ts +++ b/src/lib/es2018.full.d.ts @@ -2,4 +2,4 @@ /// /// /// -/// \ No newline at end of file +/// diff --git a/src/lib/es2018.intl.d.ts b/src/lib/es2018.intl.d.ts index 849e064de5dea..9dfc84ed364de 100644 --- a/src/lib/es2018.intl.d.ts +++ b/src/lib/es2018.intl.d.ts @@ -1,5 +1,4 @@ declare namespace Intl { - // http://cldr.unicode.org/index/cldr-spec/plural-rules#TOC-Determining-Plural-Categories type LDMLPluralRule = "zero" | "one" | "two" | "few" | "many" | "other"; type PluralRuleType = "cardinal" | "ordinal"; @@ -34,7 +33,7 @@ declare namespace Intl { new (locales?: string | string[], options?: PluralRulesOptions): PluralRules; (locales?: string | string[], options?: PluralRulesOptions): PluralRules; - supportedLocalesOf(locales: string | string[], options?: { localeMatcher?: "lookup" | "best fit" }): string[]; + supportedLocalesOf(locales: string | string[], options?: { localeMatcher?: "lookup" | "best fit"; }): string[]; }; // We can only have one definition for 'type' in TypeScript, and so you can learn where the keys come from here: diff --git a/src/lib/es2018.promise.d.ts b/src/lib/es2018.promise.d.ts index 28f903870b67c..070c4972f1141 100644 --- a/src/lib/es2018.promise.d.ts +++ b/src/lib/es2018.promise.d.ts @@ -8,5 +8,5 @@ interface Promise { * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). * @returns A Promise for the completion of the callback. */ - finally(onfinally?: (() => void) | undefined | null): Promise + finally(onfinally?: (() => void) | undefined | null): Promise; } diff --git a/src/lib/es2018.regexp.d.ts b/src/lib/es2018.regexp.d.ts index 2067b4846d791..3f142e8cf2131 100644 --- a/src/lib/es2018.regexp.d.ts +++ b/src/lib/es2018.regexp.d.ts @@ -1,13 +1,13 @@ interface RegExpMatchArray { groups?: { - [key: string]: string - } + [key: string]: string; + }; } interface RegExpExecArray { groups?: { - [key: string]: string - } + [key: string]: string; + }; } interface RegExp { @@ -16,4 +16,4 @@ interface RegExp { * Default is false. Read-only. */ readonly dotAll: boolean; -} \ No newline at end of file +} diff --git a/src/lib/es2019.array.d.ts b/src/lib/es2019.array.d.ts index 5181677c5f973..c2da39b76435f 100644 --- a/src/lib/es2019.array.d.ts +++ b/src/lib/es2019.array.d.ts @@ -1,12 +1,10 @@ type FlatArray = { - "done": Arr, - "recur": Arr extends ReadonlyArray - ? FlatArray - : Arr + done: Arr; + recur: Arr extends ReadonlyArray ? FlatArray + : Arr; }[Depth extends -1 ? "done" : "recur"]; interface ReadonlyArray { - /** * Calls a defined callback function on each element of an array. Then, flattens the result into * a new array. @@ -17,11 +15,10 @@ interface ReadonlyArray { * @param thisArg An object to which the this keyword can refer in the callback function. If * thisArg is omitted, undefined is used as the this value. */ - flatMap ( + flatMap( callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, - thisArg?: This - ): U[] - + thisArg?: This, + ): U[]; /** * Returns a new array with all sub-array elements concatenated into it recursively up to the @@ -31,12 +28,11 @@ interface ReadonlyArray { */ flat( this: A, - depth?: D - ): FlatArray[] - } + depth?: D, + ): FlatArray[]; +} interface Array { - /** * Calls a defined callback function on each element of an array. Then, flattens the result into * a new array. @@ -47,10 +43,10 @@ interface Array { * @param thisArg An object to which the this keyword can refer in the callback function. If * thisArg is omitted, undefined is used as the this value. */ - flatMap ( + flatMap( callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, - thisArg?: This - ): U[] + thisArg?: This, + ): U[]; /** * Returns a new array with all sub-array elements concatenated into it recursively up to the @@ -60,6 +56,6 @@ interface Array { */ flat( this: A, - depth?: D - ): FlatArray[] + depth?: D, + ): FlatArray[]; } diff --git a/src/lib/es2019.intl.d.ts b/src/lib/es2019.intl.d.ts index 32993edc4d8cd..c7b62bcf8bded 100644 --- a/src/lib/es2019.intl.d.ts +++ b/src/lib/es2019.intl.d.ts @@ -1,5 +1,5 @@ declare namespace Intl { interface DateTimeFormatPartTypesRegistry { - unknown: any + unknown: any; } } diff --git a/src/lib/es2019.object.d.ts b/src/lib/es2019.object.d.ts index e3518b7b9d689..ed8e9777f01e2 100644 --- a/src/lib/es2019.object.d.ts +++ b/src/lib/es2019.object.d.ts @@ -5,7 +5,7 @@ interface ObjectConstructor { * Returns an object created by key-value entries for properties and methods * @param entries An iterable object that contains key-value entries for properties and methods. */ - fromEntries(entries: Iterable): { [k: string]: T }; + fromEntries(entries: Iterable): { [k: string]: T; }; /** * Returns an object created by key-value entries for properties and methods diff --git a/src/lib/es2020.bigint.d.ts b/src/lib/es2020.bigint.d.ts index e13da87bc71c7..597b3822792eb 100644 --- a/src/lib/es2020.bigint.d.ts +++ b/src/lib/es2020.bigint.d.ts @@ -371,9 +371,9 @@ interface BigInt64Array { interface BigInt64ArrayConstructor { readonly prototype: BigInt64Array; - new(length?: number): BigInt64Array; - new(array: Iterable): BigInt64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; + new (length?: number): BigInt64Array; + new (array: Iterable): BigInt64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; @@ -643,9 +643,9 @@ interface BigUint64Array { interface BigUint64ArrayConstructor { readonly prototype: BigUint64Array; - new(length?: number): BigUint64Array; - new(array: Iterable): BigUint64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; + new (length?: number): BigUint64Array; + new (array: Iterable): BigUint64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; @@ -702,7 +702,7 @@ interface DataView { setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; } -declare namespace Intl{ +declare namespace Intl { interface NumberFormat { format(value: number | bigint): string; resolvedOptions(): ResolvedNumberFormatOptions; diff --git a/src/lib/es2020.date.d.ts b/src/lib/es2020.date.d.ts index 07af7065f7391..f85966ec7f9ae 100644 --- a/src/lib/es2020.date.d.ts +++ b/src/lib/es2020.date.d.ts @@ -21,4 +21,4 @@ interface Date { * @param options An object that contains one or more properties that specify comparison options. */ toLocaleTimeString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string; -} \ No newline at end of file +} diff --git a/src/lib/es2020.intl.d.ts b/src/lib/es2020.intl.d.ts index 37486e296307d..550edaaa6c848 100644 --- a/src/lib/es2020.intl.d.ts +++ b/src/lib/es2020.intl.d.ts @@ -1,6 +1,5 @@ /// declare namespace Intl { - /** * [Unicode BCP 47 Locale Identifiers](https://unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers) definition. * @@ -40,7 +39,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). */ - type RelativeTimeFormatUnitSingular = + type RelativeTimeFormatUnitSingular = | "year" | "quarter" | "month" @@ -122,14 +121,14 @@ declare namespace Intl { */ type RelativeTimeFormatPart = | { - type: "literal"; - value: string; - } + type: "literal"; + value: string; + } | { - type: Exclude; - value: string; - unit: RelativeTimeFormatUnitSingular; - }; + type: Exclude; + value: string; + unit: RelativeTimeFormatUnitSingular; + }; interface RelativeTimeFormat { /** @@ -200,7 +199,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat). */ - new( + new ( locales?: UnicodeBCP47LocaleIdentifier | UnicodeBCP47LocaleIdentifier[], options?: RelativeTimeFormatOptions, ): RelativeTimeFormat; @@ -392,7 +391,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames). */ - new(locales: LocalesArgument, options: DisplayNamesOptions): DisplayNames; + new (locales: LocalesArgument, options: DisplayNamesOptions): DisplayNames; /** * Returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale. @@ -407,7 +406,6 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/supportedLocalesOf). */ - supportedLocalesOf(locales?: LocalesArgument, options?: { localeMatcher?: RelativeTimeFormatLocaleMatcher }): BCP47LanguageTag[]; + supportedLocalesOf(locales?: LocalesArgument, options?: { localeMatcher?: RelativeTimeFormatLocaleMatcher; }): BCP47LanguageTag[]; }; - } diff --git a/src/lib/es2020.promise.d.ts b/src/lib/es2020.promise.d.ts index a1b408ff8f6a9..a4ebc79a8df28 100644 --- a/src/lib/es2020.promise.d.ts +++ b/src/lib/es2020.promise.d.ts @@ -17,7 +17,7 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - allSettled(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult> }>; + allSettled(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult>; }>; /** * Creates a Promise that is resolved with an array of results when all diff --git a/src/lib/es2021.intl.d.ts b/src/lib/es2021.intl.d.ts index b6e3dbf156ff6..b3835b8b1ff04 100644 --- a/src/lib/es2021.intl.d.ts +++ b/src/lib/es2021.intl.d.ts @@ -1,8 +1,7 @@ declare namespace Intl { - interface DateTimeFormatPartTypesRegistry { - fractionalSecond: any - } + fractionalSecond: any; + } interface DateTimeFormatOptions { formatMatcher?: "basic" | "best fit" | "best fit" | undefined; @@ -13,7 +12,7 @@ declare namespace Intl { } interface DateTimeRangeFormatPart extends DateTimeFormatPart { - source: "startRange" | "endRange" | "shared" + source: "startRange" | "endRange" | "shared"; } interface DateTimeFormat { @@ -96,7 +95,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts). */ - formatToParts(list: Iterable): { type: "element" | "literal", value: string; }[]; + formatToParts(list: Iterable): { type: "element" | "literal"; value: string; }[]; /** * Returns a new object with properties reflecting the locale and style @@ -126,7 +125,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat). */ - new(locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: ListFormatOptions): ListFormat; + new (locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: ListFormatOptions): ListFormat; /** * Returns an array containing those of the provided locales that are diff --git a/src/lib/es2021.promise.d.ts b/src/lib/es2021.promise.d.ts index ef9fdeda98389..cb001ed63e92b 100644 --- a/src/lib/es2021.promise.d.ts +++ b/src/lib/es2021.promise.d.ts @@ -1,9 +1,9 @@ interface AggregateError extends Error { - errors: any[] + errors: any[]; } interface AggregateErrorConstructor { - new(errors: Iterable, message?: string): AggregateError; + new (errors: Iterable, message?: string): AggregateError; (errors: Iterable, message?: string): AggregateError; readonly prototype: AggregateError; } @@ -26,5 +26,5 @@ interface PromiseConstructor { * @param values An array or iterable of Promises. * @returns A new Promise. */ - any(values: Iterable>): Promise> + any(values: Iterable>): Promise>; } diff --git a/src/lib/es2021.weakref.d.ts b/src/lib/es2021.weakref.d.ts index b8aac14ae51f9..dd6f4a37056f3 100644 --- a/src/lib/es2021.weakref.d.ts +++ b/src/lib/es2021.weakref.d.ts @@ -17,7 +17,7 @@ interface WeakRefConstructor { * In es2023 the value can be either a symbol or an object, in previous versions only object is permissible. * @param target The target value for the WeakRef instance. */ - new(target: T): WeakRef; + new (target: T): WeakRef; } declare var WeakRef: WeakRefConstructor; @@ -52,7 +52,7 @@ interface FinalizationRegistryConstructor { * Creates a finalization registry with an associated cleanup callback * @param cleanupCallback The callback to call after a value in the registry has been reclaimed. */ - new(cleanupCallback: (heldValue: T) => void): FinalizationRegistry; + new (cleanupCallback: (heldValue: T) => void): FinalizationRegistry; } declare var FinalizationRegistry: FinalizationRegistryConstructor; diff --git a/src/lib/es2022.error.d.ts b/src/lib/es2022.error.d.ts index 5f9bae491f42e..c4d956136bc1f 100644 --- a/src/lib/es2022.error.d.ts +++ b/src/lib/es2022.error.d.ts @@ -45,11 +45,11 @@ interface AggregateErrorConstructor { new ( errors: Iterable, message?: string, - options?: ErrorOptions + options?: ErrorOptions, ): AggregateError; ( errors: Iterable, message?: string, - options?: ErrorOptions + options?: ErrorOptions, ): AggregateError; } diff --git a/src/lib/es2022.intl.d.ts b/src/lib/es2022.intl.d.ts index 987b621559777..7ed03b05e07ca 100644 --- a/src/lib/es2022.intl.d.ts +++ b/src/lib/es2022.intl.d.ts @@ -1,5 +1,4 @@ declare namespace Intl { - /** * An object with some or all properties of the `Intl.Segmenter` constructor `options` parameter. * @@ -72,7 +71,7 @@ declare namespace Intl { * * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter). */ - new(locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: SegmenterOptions): Segmenter; + new (locales?: BCP47LanguageTag | BCP47LanguageTag[], options?: SegmenterOptions): Segmenter; /** * Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. diff --git a/src/lib/es2022.sharedmemory.d.ts b/src/lib/es2022.sharedmemory.d.ts index fe6c26d02cf79..e6803febf07fc 100644 --- a/src/lib/es2022.sharedmemory.d.ts +++ b/src/lib/es2022.sharedmemory.d.ts @@ -7,7 +7,7 @@ interface Atomics { * @param value The expected value to test. * @param [timeout] The expected value to test. */ - waitAsync(typedArray: Int32Array, index: number, value: number, timeout?: number): { async: false, value: "not-equal" | "timed-out" } | { async: true, value: Promise<"ok" | "timed-out"> }; + waitAsync(typedArray: Int32Array, index: number, value: number, timeout?: number): { async: false; value: "not-equal" | "timed-out"; } | { async: true; value: Promise<"ok" | "timed-out">; }; /** * A non-blocking, asynchronous version of wait which is usable on the main thread. @@ -17,5 +17,5 @@ interface Atomics { * @param value The expected value to test. * @param [timeout] The expected value to test. */ - waitAsync(typedArray: BigInt64Array, index: number, value: bigint, timeout?: number): { async: false, value: "not-equal" | "timed-out" } | { async: true, value: Promise<"ok" | "timed-out"> }; + waitAsync(typedArray: BigInt64Array, index: number, value: bigint, timeout?: number): { async: false; value: "not-equal" | "timed-out"; } | { async: true; value: Promise<"ok" | "timed-out">; }; } diff --git a/src/lib/es2023.array.d.ts b/src/lib/es2023.array.d.ts index a5cc73ae0f963..8ccbca44bb8c3 100644 --- a/src/lib/es2023.array.d.ts +++ b/src/lib/es2023.array.d.ts @@ -79,11 +79,11 @@ interface ReadonlyArray { */ findLast( predicate: (value: T, index: number, array: readonly T[]) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: T, index: number, array: readonly T[]) => unknown, - thisArg?: any + thisArg?: any, ): T | undefined; /** @@ -97,7 +97,7 @@ interface ReadonlyArray { */ findLastIndex( predicate: (value: T, index: number, array: readonly T[]) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -159,13 +159,13 @@ interface Int8Array { predicate: ( value: number, index: number, - array: Int8Array + array: Int8Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: number, index: number, array: Int8Array) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -179,7 +179,7 @@ interface Int8Array { */ findLastIndex( predicate: (value: number, index: number, array: Int8Array) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -223,13 +223,13 @@ interface Uint8Array { predicate: ( value: number, index: number, - array: Uint8Array + array: Uint8Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: number, index: number, array: Uint8Array) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -243,7 +243,7 @@ interface Uint8Array { */ findLastIndex( predicate: (value: number, index: number, array: Uint8Array) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -287,17 +287,17 @@ interface Uint8ClampedArray { predicate: ( value: number, index: number, - array: Uint8ClampedArray + array: Uint8ClampedArray, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Uint8ClampedArray + array: Uint8ClampedArray, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -313,9 +313,9 @@ interface Uint8ClampedArray { predicate: ( value: number, index: number, - array: Uint8ClampedArray + array: Uint8ClampedArray, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -359,13 +359,13 @@ interface Int16Array { predicate: ( value: number, index: number, - array: Int16Array + array: Int16Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: number, index: number, array: Int16Array) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -379,7 +379,7 @@ interface Int16Array { */ findLastIndex( predicate: (value: number, index: number, array: Int16Array) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -423,17 +423,17 @@ interface Uint16Array { predicate: ( value: number, index: number, - array: Uint16Array + array: Uint16Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Uint16Array + array: Uint16Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -449,9 +449,9 @@ interface Uint16Array { predicate: ( value: number, index: number, - array: Uint16Array + array: Uint16Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -495,13 +495,13 @@ interface Int32Array { predicate: ( value: number, index: number, - array: Int32Array + array: Int32Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: (value: number, index: number, array: Int32Array) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -515,7 +515,7 @@ interface Int32Array { */ findLastIndex( predicate: (value: number, index: number, array: Int32Array) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -559,17 +559,17 @@ interface Uint32Array { predicate: ( value: number, index: number, - array: Uint32Array + array: Uint32Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Uint32Array + array: Uint32Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -585,9 +585,9 @@ interface Uint32Array { predicate: ( value: number, index: number, - array: Uint32Array + array: Uint32Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -631,17 +631,17 @@ interface Float32Array { predicate: ( value: number, index: number, - array: Float32Array + array: Float32Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Float32Array + array: Float32Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -657,9 +657,9 @@ interface Float32Array { predicate: ( value: number, index: number, - array: Float32Array + array: Float32Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -703,17 +703,17 @@ interface Float64Array { predicate: ( value: number, index: number, - array: Float64Array + array: Float64Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: number, index: number, - array: Float64Array + array: Float64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number | undefined; /** @@ -729,9 +729,9 @@ interface Float64Array { predicate: ( value: number, index: number, - array: Float64Array + array: Float64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -775,17 +775,17 @@ interface BigInt64Array { predicate: ( value: bigint, index: number, - array: BigInt64Array + array: BigInt64Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: bigint, index: number, - array: BigInt64Array + array: BigInt64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): bigint | undefined; /** @@ -801,9 +801,9 @@ interface BigInt64Array { predicate: ( value: bigint, index: number, - array: BigInt64Array + array: BigInt64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** @@ -847,17 +847,17 @@ interface BigUint64Array { predicate: ( value: bigint, index: number, - array: BigUint64Array + array: BigUint64Array, ) => value is S, - thisArg?: any + thisArg?: any, ): S | undefined; findLast( predicate: ( value: bigint, index: number, - array: BigUint64Array + array: BigUint64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): bigint | undefined; /** @@ -873,9 +873,9 @@ interface BigUint64Array { predicate: ( value: bigint, index: number, - array: BigUint64Array + array: BigUint64Array, ) => unknown, - thisArg?: any + thisArg?: any, ): number; /** diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index a187e3c04a0f3..988751cd338b3 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -135,7 +135,7 @@ interface Object { } interface ObjectConstructor { - new(value?: any): Object; + new (value?: any): Object; (): any; (value: any): any; @@ -207,7 +207,7 @@ interface ObjectConstructor { * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. * @param o Object on which to lock the attributes. */ - freeze(o: T): Readonly; + freeze(o: T): Readonly; /** * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. @@ -293,7 +293,7 @@ interface FunctionConstructor { * Creates a new function. * @param args A list of arguments the function accepts. */ - new(...args: string[]): Function; + new (...args: string[]): Function; (...args: string[]): Function; readonly prototype: Function; } @@ -514,7 +514,7 @@ interface String { } interface StringConstructor { - new(value?: any): String; + new (value?: any): String; (value?: any): string; readonly prototype: String; fromCharCode(...codes: number[]): string; @@ -531,7 +531,7 @@ interface Boolean { } interface BooleanConstructor { - new(value?: any): Boolean; + new (value?: any): Boolean; (value?: T): boolean; readonly prototype: Boolean; } @@ -568,7 +568,7 @@ interface Number { } interface NumberConstructor { - new(value?: any): Number; + new (value?: any): Number; (value?: any): number; readonly prototype: Number; @@ -896,8 +896,8 @@ interface Date { } interface DateConstructor { - new(): Date; - new(value: number | string): Date; + new (): Date; + new (value: number | string): Date; /** * Creates a new Date. * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. @@ -908,7 +908,7 @@ interface DateConstructor { * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. * @param ms A number from 0 to 999 that specifies the milliseconds. */ - new(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + new (year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; readonly prototype: Date; /** @@ -996,49 +996,49 @@ interface RegExp { } interface RegExpConstructor { - new(pattern: RegExp | string): RegExp; - new(pattern: string, flags?: string): RegExp; + new (pattern: RegExp | string): RegExp; + new (pattern: string, flags?: string): RegExp; (pattern: RegExp | string): RegExp; (pattern: string, flags?: string): RegExp; - readonly prototype: RegExp; + readonly "prototype": RegExp; // Non-standard extensions /** @deprecated A legacy feature for browser compatibility */ - $1: string; + "$1": string; /** @deprecated A legacy feature for browser compatibility */ - $2: string; + "$2": string; /** @deprecated A legacy feature for browser compatibility */ - $3: string; + "$3": string; /** @deprecated A legacy feature for browser compatibility */ - $4: string; + "$4": string; /** @deprecated A legacy feature for browser compatibility */ - $5: string; + "$5": string; /** @deprecated A legacy feature for browser compatibility */ - $6: string; + "$6": string; /** @deprecated A legacy feature for browser compatibility */ - $7: string; + "$7": string; /** @deprecated A legacy feature for browser compatibility */ - $8: string; + "$8": string; /** @deprecated A legacy feature for browser compatibility */ - $9: string; + "$9": string; /** @deprecated A legacy feature for browser compatibility */ - input: string; + "input": string; /** @deprecated A legacy feature for browser compatibility */ - $_: string; + "$_": string; /** @deprecated A legacy feature for browser compatibility */ - lastMatch: string; + "lastMatch": string; /** @deprecated A legacy feature for browser compatibility */ "$&": string; /** @deprecated A legacy feature for browser compatibility */ - lastParen: string; + "lastParen": string; /** @deprecated A legacy feature for browser compatibility */ "$+": string; /** @deprecated A legacy feature for browser compatibility */ - leftContext: string; + "leftContext": string; /** @deprecated A legacy feature for browser compatibility */ "$`": string; /** @deprecated A legacy feature for browser compatibility */ - rightContext: string; + "rightContext": string; /** @deprecated A legacy feature for browser compatibility */ "$'": string; } @@ -1052,7 +1052,7 @@ interface Error { } interface ErrorConstructor { - new(message?: string): Error; + new (message?: string): Error; (message?: string): Error; readonly prototype: Error; } @@ -1063,7 +1063,7 @@ interface EvalError extends Error { } interface EvalErrorConstructor extends ErrorConstructor { - new(message?: string): EvalError; + new (message?: string): EvalError; (message?: string): EvalError; readonly prototype: EvalError; } @@ -1074,7 +1074,7 @@ interface RangeError extends Error { } interface RangeErrorConstructor extends ErrorConstructor { - new(message?: string): RangeError; + new (message?: string): RangeError; (message?: string): RangeError; readonly prototype: RangeError; } @@ -1085,7 +1085,7 @@ interface ReferenceError extends Error { } interface ReferenceErrorConstructor extends ErrorConstructor { - new(message?: string): ReferenceError; + new (message?: string): ReferenceError; (message?: string): ReferenceError; readonly prototype: ReferenceError; } @@ -1096,7 +1096,7 @@ interface SyntaxError extends Error { } interface SyntaxErrorConstructor extends ErrorConstructor { - new(message?: string): SyntaxError; + new (message?: string): SyntaxError; (message?: string): SyntaxError; readonly prototype: SyntaxError; } @@ -1107,7 +1107,7 @@ interface TypeError extends Error { } interface TypeErrorConstructor extends ErrorConstructor { - new(message?: string): TypeError; + new (message?: string): TypeError; (message?: string): TypeError; readonly prototype: TypeError; } @@ -1118,7 +1118,7 @@ interface URIError extends Error { } interface URIErrorConstructor extends ErrorConstructor { - new(message?: string): URIError; + new (message?: string): URIError; (message?: string): URIError; readonly prototype: URIError; } @@ -1154,7 +1154,6 @@ interface JSON { */ declare var JSON: JSON; - ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// @@ -1478,7 +1477,7 @@ interface Array { } interface ArrayConstructor { - new(arrayLength?: number): any[]; + new (arrayLength?: number): any[]; new (arrayLength: number): T[]; new (...items: T[]): T[]; (arrayLength?: number): any[]; @@ -1534,13 +1533,12 @@ interface Promise { /** * Recursively unwraps the "awaited type" of a type. Non-promise "thenables" should resolve to `never`. This emulates the behavior of `await`. */ -type Awaited = - T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode - T extends object & { then(onfulfilled: infer F, ...args: infer _): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped - F extends ((value: infer V, ...args: infer _) => any) ? // if the argument to `then` is callable, extracts the first argument - Awaited : // recursively unwrap the value - never : // the argument to `then` was not callable - T; // non-object or non-thenable +type Awaited = T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode + T extends object & { then(onfulfilled: infer F, ...args: infer _): any; } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped + F extends ((value: infer V, ...args: infer _) => any) ? // if the argument to `then` is callable, extracts the first argument + Awaited : // recursively unwrap the value + never : // the argument to `then` was not callable + T; // non-object or non-thenable interface ArrayLike { readonly length: number; @@ -1645,7 +1643,7 @@ type Uncapitalize = intrinsic; /** * Marker for contextual 'this' type */ -interface ThisType { } +interface ThisType {} /** * Stores types to be used with WeakSet, WeakMap, WeakRef, and FinalizationRegistry @@ -1684,7 +1682,7 @@ type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; - new(byteLength: number): ArrayBuffer; + new (byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } declare var ArrayBuffer: ArrayBufferConstructor; @@ -1836,7 +1834,7 @@ interface DataView { interface DataViewConstructor { readonly prototype: DataView; - new(buffer: ArrayBufferLike & { BYTES_PER_ELEMENT?: never }, byteOffset?: number, byteLength?: number): DataView; + new (buffer: ArrayBufferLike & { BYTES_PER_ELEMENT?: never; }, byteOffset?: number, byteLength?: number): DataView; } declare var DataView: DataViewConstructor; @@ -2089,9 +2087,9 @@ interface Int8Array { } interface Int8ArrayConstructor { readonly prototype: Int8Array; - new(length: number): Int8Array; - new(array: ArrayLike | ArrayBufferLike): Int8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + new (length: number): Int8Array; + new (array: ArrayLike | ArrayBufferLike): Int8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -2117,8 +2115,6 @@ interface Int8ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array; - - } declare var Int8Array: Int8ArrayConstructor; @@ -2372,9 +2368,9 @@ interface Uint8Array { interface Uint8ArrayConstructor { readonly prototype: Uint8Array; - new(length: number): Uint8Array; - new(array: ArrayLike | ArrayBufferLike): Uint8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + new (length: number): Uint8Array; + new (array: ArrayLike | ArrayBufferLike): Uint8Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2400,7 +2396,6 @@ interface Uint8ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array; - } declare var Uint8Array: Uint8ArrayConstructor; @@ -2654,9 +2649,9 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; - new(length: number): Uint8ClampedArray; - new(array: ArrayLike | ArrayBufferLike): Uint8ClampedArray; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + new (length: number): Uint8ClampedArray; + new (array: ArrayLike | ArrayBufferLike): Uint8ClampedArray; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2934,9 +2929,9 @@ interface Int16Array { interface Int16ArrayConstructor { readonly prototype: Int16Array; - new(length: number): Int16Array; - new(array: ArrayLike | ArrayBufferLike): Int16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + new (length: number): Int16Array; + new (array: ArrayLike | ArrayBufferLike): Int16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2962,8 +2957,6 @@ interface Int16ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array; - - } declare var Int16Array: Int16ArrayConstructor; @@ -3217,9 +3210,9 @@ interface Uint16Array { interface Uint16ArrayConstructor { readonly prototype: Uint16Array; - new(length: number): Uint16Array; - new(array: ArrayLike | ArrayBufferLike): Uint16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + new (length: number): Uint16Array; + new (array: ArrayLike | ArrayBufferLike): Uint16Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -3245,8 +3238,6 @@ interface Uint16ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array; - - } declare var Uint16Array: Uint16ArrayConstructor; /** @@ -3499,9 +3490,9 @@ interface Int32Array { interface Int32ArrayConstructor { readonly prototype: Int32Array; - new(length: number): Int32Array; - new(array: ArrayLike | ArrayBufferLike): Int32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + new (length: number): Int32Array; + new (array: ArrayLike | ArrayBufferLike): Int32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3527,7 +3518,6 @@ interface Int32ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array; - } declare var Int32Array: Int32ArrayConstructor; @@ -3780,9 +3770,9 @@ interface Uint32Array { interface Uint32ArrayConstructor { readonly prototype: Uint32Array; - new(length: number): Uint32Array; - new(array: ArrayLike | ArrayBufferLike): Uint32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + new (length: number): Uint32Array; + new (array: ArrayLike | ArrayBufferLike): Uint32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3808,7 +3798,6 @@ interface Uint32ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array; - } declare var Uint32Array: Uint32ArrayConstructor; @@ -4062,9 +4051,9 @@ interface Float32Array { interface Float32ArrayConstructor { readonly prototype: Float32Array; - new(length: number): Float32Array; - new(array: ArrayLike | ArrayBufferLike): Float32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + new (length: number): Float32Array; + new (array: ArrayLike | ArrayBufferLike): Float32Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -4090,8 +4079,6 @@ interface Float32ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array; - - } declare var Float32Array: Float32ArrayConstructor; @@ -4345,9 +4332,9 @@ interface Float64Array { interface Float64ArrayConstructor { readonly prototype: Float64Array; - new(length: number): Float64Array; - new(array: ArrayLike | ArrayBufferLike): Float64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + new (length: number): Float64Array; + new (array: ArrayLike | ArrayBufferLike): Float64Array; + new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4373,7 +4360,6 @@ interface Float64ArrayConstructor { * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array; - } declare var Float64Array: Float64ArrayConstructor; @@ -4407,7 +4393,7 @@ declare namespace Intl { resolvedOptions(): ResolvedCollatorOptions; } var Collator: { - new(locales?: string | string[], options?: CollatorOptions): Collator; + new (locales?: string | string[], options?: CollatorOptions): Collator; (locales?: string | string[], options?: CollatorOptions): Collator; supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; }; @@ -4443,7 +4429,7 @@ declare namespace Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; readonly prototype: NumberFormat; @@ -4487,7 +4473,7 @@ declare namespace Intl { resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; readonly prototype: DateTimeFormat; diff --git a/src/lib/esnext.disposable.d.ts b/src/lib/esnext.disposable.d.ts index 318b7395ac28a..4d91a6e98a300 100644 --- a/src/lib/esnext.disposable.d.ts +++ b/src/lib/esnext.disposable.d.ts @@ -70,18 +70,18 @@ interface DisposableStack { * constructor() { * // stack will be disposed when exiting constructor for any reason * using stack = new DisposableStack(); - * + * * // get first resource * this.#res1 = stack.use(getResource1()); - * + * * // get second resource. If this fails, both `stack` and `#res1` will be disposed. * this.#res2 = stack.use(getResource2()); - * + * * // all operations succeeded, move resources out of `stack` so that they aren't disposed * // when constructor exits * this.#disposables = stack.move(); * } - * + * * [Symbol.dispose]() { * this.#disposables.dispose(); * } @@ -94,7 +94,7 @@ interface DisposableStack { } interface DisposableStackConstructor { - new(): DisposableStack; + new (): DisposableStack; readonly prototype: DisposableStack; } declare var DisposableStack: DisposableStackConstructor; @@ -137,18 +137,18 @@ interface AsyncDisposableStack { * constructor() { * // stack will be disposed when exiting constructor for any reason * using stack = new DisposableStack(); - * + * * // get first resource * this.#res1 = stack.use(getResource1()); - * + * * // get second resource. If this fails, both `stack` and `#res1` will be disposed. * this.#res2 = stack.use(getResource2()); - * + * * // all operations succeeded, move resources out of `stack` so that they aren't disposed * // when constructor exits * this.#disposables = stack.move(); * } - * + * * [Symbol.dispose]() { * this.#disposables.dispose(); * } @@ -161,7 +161,7 @@ interface AsyncDisposableStack { } interface AsyncDisposableStackConstructor { - new(): AsyncDisposableStack; + new (): AsyncDisposableStack; readonly prototype: AsyncDisposableStack; } declare var AsyncDisposableStack: AsyncDisposableStackConstructor; diff --git a/src/lib/esnext.full.d.ts b/src/lib/esnext.full.d.ts index 2a8029d3a80fa..70fc982b908bc 100644 --- a/src/lib/esnext.full.d.ts +++ b/src/lib/esnext.full.d.ts @@ -2,4 +2,4 @@ /// /// /// -/// \ No newline at end of file +/// diff --git a/src/lib/esnext.intl.d.ts b/src/lib/esnext.intl.d.ts index 3c5a0bd4df9a3..b6d59cfa0d9fc 100644 --- a/src/lib/esnext.intl.d.ts +++ b/src/lib/esnext.intl.d.ts @@ -1,10 +1,10 @@ declare namespace Intl { - interface NumberRangeFormatPart extends NumberFormatPart { - source: "startRange" | "endRange" | "shared" - } + interface NumberRangeFormatPart extends NumberFormatPart { + source: "startRange" | "endRange" | "shared"; + } - interface NumberFormat { - formatRange(start: number | bigint, end: number | bigint): string; - formatRangeToParts(start: number | bigint, end: number | bigint): NumberRangeFormatPart[]; - } + interface NumberFormat { + formatRange(start: number | bigint, end: number | bigint): string; + formatRangeToParts(start: number | bigint, end: number | bigint): NumberRangeFormatPart[]; + } } diff --git a/src/lib/scripthost.d.ts b/src/lib/scripthost.d.ts index c3ac4a7e6560f..704399103b3b5 100644 --- a/src/lib/scripthost.d.ts +++ b/src/lib/scripthost.d.ts @@ -1,10 +1,7 @@ - - ///////////////////////////// /// Windows Script Host APIS ///////////////////////////// - interface ActiveXObject { new (s: string): any; } @@ -244,7 +241,7 @@ interface Enumerator { interface EnumeratorConstructor { new (safearray: SafeArray): Enumerator; - new (collection: { Item(index: any): T }): Enumerator; + new (collection: { Item(index: any): T; }): Enumerator; new (collection: any): Enumerator; } diff --git a/src/lib/webworker.importscripts.d.ts b/src/lib/webworker.importscripts.d.ts index 1c4c4f4e953da..8144ff3387a46 100644 --- a/src/lib/webworker.importscripts.d.ts +++ b/src/lib/webworker.importscripts.d.ts @@ -1,4 +1,3 @@ - ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 354198918b5e8..158e08f25d30e 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -216,12 +216,12 @@ export interface LargeFileReferencedEvent { export interface ConfigFileDiagEvent { eventName: typeof ConfigFileDiagEvent; - data: { triggerFile: string, configFileName: string, diagnostics: readonly Diagnostic[] }; + data: { triggerFile: string; configFileName: string; diagnostics: readonly Diagnostic[]; }; } export interface ProjectLanguageServiceStateEvent { eventName: typeof ProjectLanguageServiceStateEvent; - data: { project: Project, languageServiceEnabled: boolean }; + data: { project: Project; languageServiceEnabled: boolean; }; } /** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */ @@ -320,7 +320,7 @@ export interface OpenFileInfo { } export type ProjectServiceEvent = - LargeFileReferencedEvent + | LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent @@ -335,7 +335,7 @@ export type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; export type PerformanceEventHandler = (event: PerformanceEvent) => void; export interface SafeList { - [name: string]: { match: RegExp, exclude?: (string | number)[][], types?: string[] }; + [name: string]: { match: RegExp; exclude?: (string | number)[][]; types?: string[]; }; } function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): Map> { @@ -358,12 +358,12 @@ const watchOptionsConverters = prepareConvertersForEnumLikeCompilerOptions(optio const indentStyle = new Map(Object.entries({ none: IndentStyle.None, block: IndentStyle.Block, - smart: IndentStyle.Smart + smart: IndentStyle.Smart, })); export interface TypesMapFile { typesMap: SafeList; - simpleMap: { [libName: string]: string }; + simpleMap: { [libName: string]: string; }; } /** @@ -388,30 +388,30 @@ const defaultTypeSafeList: SafeList = { "jquery": { // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") match: /jquery(-[\d.]+)?(\.intellisense)?(\.min)?\.js$/i, - types: ["jquery"] + types: ["jquery"], }, "WinJS": { // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js - match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, // If the winjs/base.js file is found.. - exclude: [["^", 1, "/.*"]], // ..then exclude all files under the winjs folder - types: ["winjs"] // And fetch the @types package for WinJS + match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, // If the winjs/base.js file is found.. + exclude: [["^", 1, "/.*"]], // ..then exclude all files under the winjs folder + types: ["winjs"], // And fetch the @types package for WinJS }, "Kendo": { // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, exclude: [["^", 1, "/.*"]], - types: ["kendo-ui"] + types: ["kendo-ui"], }, "Office Nuget": { // e.g. /scripts/Office/1/excel-15.debug.js match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, // Office NuGet package is installed under a "1/office" folder - exclude: [["^", 1, "/.*"]], // Exclude that whole folder if the file indicated above is found in it - types: ["office"] // @types package to fetch instead + exclude: [["^", 1, "/.*"]], // Exclude that whole folder if the file indicated above is found in it + types: ["office"], // @types package to fetch instead }, "References": { match: /^(.*\/_references\.js)$/i, - exclude: [["^", 1, "$"]] - } + exclude: [["^", 1, "$"]], + }, }; export function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings { @@ -448,7 +448,7 @@ export function convertWatchOptions(protocolOptions: protocol.ExternalProjectCom export function convertTypeAcquisition(protocolOptions: protocol.InferredProjectCompilerOptions): TypeAcquisition | undefined { let result: TypeAcquisition | undefined; - typeAcquisitionDeclarations.forEach((option) => { + typeAcquisitionDeclarations.forEach(option => { const propertyValue = protocolOptions[option.name]; if (propertyValue === undefined) return; (result || (result = {}))[option.name] = propertyValue; @@ -593,7 +593,10 @@ export interface ProjectServiceOptions { /** @internal */ incrementalVerifier?: (service: ProjectService) => void; } -interface OriginalFileInfo { fileName: NormalizedPath; path: Path; } +interface OriginalFileInfo { + fileName: NormalizedPath; + path: Path; +} interface AncestorConfigFileInfo { /** config file name */ fileName: string; @@ -623,7 +626,7 @@ export enum ProjectReferenceProjectLoadKind { /** Find existing project or create one for the project reference */ FindCreate, /** Find existing project or create and load it for the project reference */ - FindCreateLoad + FindCreateLoad, } /** @internal */ @@ -639,14 +642,14 @@ export function forEachResolvedProjectReferenceProject( fileName: string | undefined, cb: (child: ConfiguredProject) => T | undefined, projectReferenceProjectLoadKind: ProjectReferenceProjectLoadKind, - reason: string + reason: string, ): T | undefined; export function forEachResolvedProjectReferenceProject( project: ConfiguredProject, fileName: string | undefined, cb: (child: ConfiguredProject) => T | undefined, projectReferenceProjectLoadKind: ProjectReferenceProjectLoadKind, - reason?: string + reason?: string, ): T | undefined { const resolvedRefs = project.getCurrentProgram()?.getResolvedProjectReferences(); if (!resolvedRefs) return undefined; @@ -669,7 +672,7 @@ export function forEachResolvedProjectReferenceProject( (ref, loadKind) => possibleDefaultRef === ref ? callback(ref, loadKind) : undefined, projectReferenceProjectLoadKind, project.projectService, - seenResolvedRefs + seenResolvedRefs, ); if (result) return result; // Cleanup seenResolvedRefs @@ -683,7 +686,7 @@ export function forEachResolvedProjectReferenceProject( (ref, loadKind) => possibleDefaultRef !== ref ? callback(ref, loadKind) : undefined, projectReferenceProjectLoadKind, project.projectService, - seenResolvedRefs + seenResolvedRefs, ); function callback(ref: ResolvedProjectReference, loadKind: ProjectReferenceProjectLoadKind) { @@ -692,10 +695,10 @@ export function forEachResolvedProjectReferenceProject( loadKind === ProjectReferenceProjectLoadKind.Find ? undefined : loadKind === ProjectReferenceProjectLoadKind.FindCreate ? - project.projectService.createConfiguredProject(configFileName) : - loadKind === ProjectReferenceProjectLoadKind.FindCreateLoad ? - project.projectService.createAndLoadConfiguredProject(configFileName, reason!) : - Debug.assertNever(loadKind) + project.projectService.createConfiguredProject(configFileName) : + loadKind === ProjectReferenceProjectLoadKind.FindCreateLoad ? + project.projectService.createAndLoadConfiguredProject(configFileName, reason!) : + Debug.assertNever(loadKind) ); return child && cb(child); @@ -732,7 +735,7 @@ function forEachResolvedProjectReferenceProjectWorker( function forEachPotentialProjectReference( project: ConfiguredProject, - cb: (potentialProjectReference: NormalizedPath) => T | undefined + cb: (potentialProjectReference: NormalizedPath) => T | undefined, ): T | undefined { return project.potentialProjectReferences && forEachKey(project.potentialProjectReferences, cb); @@ -742,19 +745,19 @@ function forEachAnyProjectReferenceKind( project: ConfiguredProject, cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined, cbProjectRef: (projectReference: ProjectReference) => T | undefined, - cbPotentialProjectRef: (potentialProjectReference: NormalizedPath) => T | undefined + cbPotentialProjectRef: (potentialProjectReference: NormalizedPath) => T | undefined, ): T | undefined { return project.getCurrentProgram() ? project.forEachResolvedProjectReference(cb) : project.isInitialLoadPending() ? - forEachPotentialProjectReference(project, cbPotentialProjectRef) : - forEach(project.getProjectReferences(), cbProjectRef); + forEachPotentialProjectReference(project, cbPotentialProjectRef) : + forEach(project.getProjectReferences(), cbProjectRef); } function callbackRefProject( project: ConfiguredProject, cb: (refProj: ConfiguredProject) => T | undefined, - refPath: P | undefined + refPath: P | undefined, ) { const refProject = refPath && project.projectService.configuredProjects.get(refPath); return refProject && cb(refProject); @@ -762,13 +765,13 @@ function callbackRefProject( function forEachReferencedProject( project: ConfiguredProject, - cb: (refProj: ConfiguredProject) => T | undefined + cb: (refProj: ConfiguredProject) => T | undefined, ): T | undefined { return forEachAnyProjectReferenceKind( project, resolvedRef => callbackRefProject(project, cb, resolvedRef.sourceFile.path), projectRef => callbackRefProject(project, cb, project.toPath(resolveProjectReferencePath(projectRef))), - potentialProjectRef => callbackRefProject(project, cb, potentialProjectRef) + potentialProjectRef => callbackRefProject(project, cb, potentialProjectRef), ); } @@ -830,7 +833,7 @@ export interface WatchOptionsAndErrors { } /** @internal */ -export interface ParsedConfig{ +export interface ParsedConfig { cachedDirectoryStructureHost: CachedDirectoryStructureHost; /** * The map contains @@ -853,7 +856,6 @@ function createProjectNameFactoryWithCounter(nameFactory: (counter: number) => s } export class ProjectService { - /** @internal */ readonly typingsCache: TypingsCache; @@ -933,7 +935,6 @@ export class ProjectService { * - Or it is present if we have configured project open with config file at that location * In this case the exists property is always true * - * * @internal */ readonly configFileExistenceInfoCache = new Map(); @@ -1105,7 +1106,7 @@ export class ProjectService { } const event: ProjectLanguageServiceStateEvent = { eventName: ProjectLanguageServiceStateEvent, - data: { project, languageServiceEnabled } + data: { project, languageServiceEnabled }, }; this.eventHandler(event); } @@ -1209,8 +1210,8 @@ export class ProjectService { const event: ProjectsUpdatedInBackgroundEvent = { eventName: ProjectsUpdatedInBackgroundEvent, data: { - openFiles: arrayFrom(this.openFiles.keys(), path => this.getScriptInfoForPath(path as Path)!.fileName) - } + openFiles: arrayFrom(this.openFiles.keys(), path => this.getScriptInfoForPath(path as Path)!.fileName), + }, }; this.eventHandler(event); } @@ -1223,7 +1224,7 @@ export class ProjectService { const event: LargeFileReferencedEvent = { eventName: LargeFileReferencedEvent, - data: { file, fileSize, maxFileSize } + data: { file, fileSize, maxFileSize }, }; this.eventHandler(event); } @@ -1236,7 +1237,7 @@ export class ProjectService { project.sendLoadingProjectFinish = true; const event: ProjectLoadingStartEvent = { eventName: ProjectLoadingStartEvent, - data: { project, reason } + data: { project, reason }, }; this.eventHandler(event); } @@ -1250,7 +1251,7 @@ export class ProjectService { project.sendLoadingProjectFinish = false; const event: ProjectLoadingFinishEvent = { eventName: ProjectLoadingFinishEvent, - data: { project } + data: { project }, }; this.eventHandler(event); } @@ -1310,9 +1311,11 @@ export class ProjectService { // root path // - Inferred projects with a projectRootPath, if the new options apply to that // project root path. - if (canonicalProjectRootPath ? - project.projectRootPath === canonicalProjectRootPath : - !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { + if ( + canonicalProjectRootPath ? + project.projectRootPath === canonicalProjectRootPath : + !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath) + ) { project.setCompilerOptions(compilerOptions); project.setTypeAcquisition(typeAcquisition); project.setWatchOptions(watchOptions?.watchOptions); @@ -1501,7 +1504,8 @@ export class ProjectService { fileOrDirectory => { const fileOrDirectoryPath = this.toPath(fileOrDirectory); const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && + if ( + getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectoryPath)) ) { this.logger.info(`Config: ${configFileName} Detected new package.json: ${fileOrDirectory}`); @@ -1509,19 +1513,21 @@ export class ProjectService { } const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName); - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: directory, - fileOrDirectory, - fileOrDirectoryPath, - configFileName, - extraFileExtensions: this.hostConfiguration.extraFileExtensions, - currentDirectory: this.currentDirectory, - options: config.parsedCommandLine!.options, - program: configuredProjectForConfig?.getCurrentProgram() || config.parsedCommandLine!.fileNames, - useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, - writeLog: s => this.logger.info(s), - toPath: s => this.toPath(s) - })) return; + if ( + isIgnoredFileFromWildCardWatching({ + watchedDirPath: directory, + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + extraFileExtensions: this.hostConfiguration.extraFileExtensions, + currentDirectory: this.currentDirectory, + options: config.parsedCommandLine!.options, + program: configuredProjectForConfig?.getCurrentProgram() || config.parsedCommandLine!.fileNames, + useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, + writeLog: s => this.logger.info(s), + toPath: s => this.toPath(s), + }) + ) return; // Reload is pending, do the reload if (config.reloadLevel !== ConfigFileProgramReloadLevel.Full) config.reloadLevel = ConfigFileProgramReloadLevel.Partial; @@ -1556,7 +1562,7 @@ export class ProjectService { flags, this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine!.watchOptions), WatchType.WildcardDirectory, - configFileName + configFileName, ); } @@ -1625,7 +1631,7 @@ export class ProjectService { eventKind !== FileWatcherEventKind.Deleted ? identity : // Reload open files if they are root of inferred project returnTrue, // Reload all the open files impacted by config file - "Change in config file detected" + "Change in config file detected", ); this.delayEnsureProjectForOpenFiles(); } @@ -1636,24 +1642,31 @@ export class ProjectService { project.close(); if (Debug.shouldAssert(AssertionLevel.Normal)) { - this.filenameToScriptInfo.forEach(info => Debug.assert( - !info.isAttached(project), - "Found script Info still attached to project", - () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify( - arrayFrom( - mapDefinedIterator( - this.filenameToScriptInfo.values(), - info => info.isAttached(project) ? - { - fileName: info.fileName, - projects: info.containingProjects.map(p => p.projectName), - hasMixedContent: info.hasMixedContent - } : undefined - ) - ), - /*replacer*/ undefined, - " " - )}`)); + this.filenameToScriptInfo.forEach(info => + Debug.assert( + !info.isAttached(project), + "Found script Info still attached to project", + () => + `${project.projectName}: ScriptInfos still attached: ${ + JSON.stringify( + arrayFrom( + mapDefinedIterator( + this.filenameToScriptInfo.values(), + info => + info.isAttached(project) ? + { + fileName: info.fileName, + projects: info.containingProjects.map(p => p.projectName), + hasMixedContent: info.hasMixedContent, + } : undefined, + ), + ), + /*replacer*/ undefined, + " ", + ) + }`, + ) + ); } // Remove the project from pending project updates this.pendingProjectUpdates.delete(project.getProjectName()); @@ -1689,9 +1702,9 @@ export class ProjectService { info.fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : - this.currentDirectory - ) - ) + this.currentDirectory, + ), + ), ); project.addRoot(info); @@ -1870,7 +1883,7 @@ export class ProjectService { PollingInterval.High, this.getWatchOptionsFromProjectWatchOptions(configFileExistenceInfo?.config?.parsedCommandLine?.watchOptions), WatchType.ConfigFile, - forProject + forProject, ); } // Watching config file for project, update the map @@ -1929,9 +1942,11 @@ export class ProjectService { private closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo: ConfigFileExistenceInfo) { // Close the config file watcher if there are no more open files that are root of inferred project // or if there are no projects that need to watch this config file existence info - if (configFileExistenceInfo.watcher && + if ( + configFileExistenceInfo.watcher && !configFileExistenceInfo.config && - !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo) + ) { configFileExistenceInfo.watcher.close(); configFileExistenceInfo.watcher = undefined; } @@ -1961,8 +1976,10 @@ export class ProjectService { // If there are no open files that are impacted by configFileExistenceInfo after closing this script info // and there is are no projects that need the config file existence or parsed config, // remove the cached existence info - if (!configFileExistenceInfo.openFilesImpactedByConfigFile?.size && - !configFileExistenceInfo.config) { + if ( + !configFileExistenceInfo.openFilesImpactedByConfigFile?.size && + !configFileExistenceInfo.config + ) { Debug.assert(!configFileExistenceInfo.watcher); this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); } @@ -1995,7 +2012,7 @@ export class ProjectService { (_filename, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), PollingInterval.High, this.hostConfiguration.watchOptions, - WatchType.ConfigFileForInferredRoot + WatchType.ConfigFileForInferredRoot, ) : noopConfigFileWatcher; }); @@ -2069,7 +2086,8 @@ export class ProjectService { if (parentPath === searchPath) break; searchPath = parentPath; searchInDirectory = true; - } while (anySearchPathOk || isSearchPathInProjectRoot()); + } + while (anySearchPathOk || isSearchPathInProjectRoot()); return undefined; } @@ -2103,8 +2121,7 @@ export class ProjectService { if (result !== undefined) return result || undefined; } this.logger.info(`Search path: ${getDirectoryPath(info.fileName)}`); - const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => - this.configFileExists(configFileName, canonicalConfigFilePath, info)); + const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => this.configFileExists(configFileName, canonicalConfigFilePath, info)); if (configFileName) { this.logger.info(`For info: ${info.fileName} :: Config file name: ${configFileName}`); } @@ -2161,7 +2178,7 @@ export class ProjectService { let availableSpace = maxProgramSizeForNonTsFiles; this.projectToSizeMap.set(name, 0); - this.projectToSizeMap.forEach(val => (availableSpace -= (val || 0))); + this.projectToSizeMap.forEach(val => (availableSpace -= val || 0)); let totalNonTsFileSize = 0; @@ -2198,7 +2215,7 @@ export class ProjectService { /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave, /*projectFilePath*/ undefined, - watchOptionsAndErrors?.watchOptions + watchOptionsAndErrors?.watchOptions, ); project.setProjectErrors(watchOptionsAndErrors?.errors); project.excludedFiles = excludedFiles; @@ -2280,7 +2297,7 @@ export class ProjectService { configFileExistenceInfo.config = { cachedDirectoryStructureHost: createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames)!, projects: new Map(), - reloadLevel: ConfigFileProgramReloadLevel.Full + reloadLevel: ConfigFileProgramReloadLevel.Full, }; } @@ -2289,7 +2306,8 @@ export class ProjectService { canonicalConfigFilePath, this, this.documentRegistry, - configFileExistenceInfo.config.cachedDirectoryStructureHost); + configFileExistenceInfo.config.cachedDirectoryStructureHost, + ); this.configuredProjects.set(canonicalConfigFilePath, project); this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project); return project; @@ -2332,7 +2350,7 @@ export class ProjectService { configFilename, project.canonicalConfigFilePath, this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)!, - project + project, ); const parsedCommandLine = configFileExistenceInfo.config!.parsedCommandLine!; Debug.assert(!!parsedCommandLine.fileNames); @@ -2344,7 +2362,7 @@ export class ProjectService { configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, configHasFilesProperty: parsedCommandLine.raw.files !== undefined, configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, }; } project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(parsedCommandLine.raw); @@ -2353,8 +2371,7 @@ export class ProjectService { const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); if (lastFileExceededProgramSize) { project.disableLanguageService(lastFileExceededProgramSize); - this.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => - this.stopWatchingWildCards(canonicalConfigFilePath, project)); + this.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.stopWatchingWildCards(canonicalConfigFilePath, project)); } else { project.setCompilerOptions(compilerOptions); @@ -2393,7 +2410,7 @@ export class ProjectService { getDirectoryPath(configFilename), /*existingOptions*/ {}, configFilename, - /*resolutionStack*/[], + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions, this.extendedConfigCache, ); @@ -2402,12 +2419,18 @@ export class ProjectService { configFileErrors.push(...parsedCommandLine.errors); } - this.logger.info(`Config: ${configFilename} : ${JSON.stringify({ - rootNames: parsedCommandLine.fileNames, - options: parsedCommandLine.options, - watchOptions: parsedCommandLine.watchOptions, - projectReferences: parsedCommandLine.projectReferences - }, /*replacer*/ undefined, " ")}`); + this.logger.info(`Config: ${configFilename} : ${ + JSON.stringify( + { + rootNames: parsedCommandLine.fileNames, + options: parsedCommandLine.options, + watchOptions: parsedCommandLine.watchOptions, + projectReferences: parsedCommandLine.projectReferences, + }, + /*replacer*/ undefined, + " ", + ) + }`); const oldCommandLine = configFileExistenceInfo.config?.parsedCommandLine; if (!configFileExistenceInfo.config) { @@ -2420,12 +2443,14 @@ export class ProjectService { } // If watch options different than older options when setting for the first time, update the config file watcher - if (!oldCommandLine && !isJsonEqual( - // Old options - this.getWatchOptionsFromProjectWatchOptions(/*projectOptions*/ undefined), - // New options - this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions) - )) { + if ( + !oldCommandLine && !isJsonEqual( + // Old options + this.getWatchOptionsFromProjectWatchOptions(/*projectOptions*/ undefined), + // New options + this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions), + ) + ) { // Reset the config file watcher configFileExistenceInfo.watcher?.close(); configFileExistenceInfo.watcher = undefined; @@ -2438,23 +2463,24 @@ export class ProjectService { canonicalConfigFilePath, parsedCommandLine.options, this.sharedExtendedConfigFileWatchers, - (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile( - extendedConfigFileName, - () => { - // Update extended config cache - cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, fileName => this.toPath(fileName)); - // Update projects - let ensureProjectsForOpenFiles = false; - this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)?.projects.forEach(canonicalPath => { - ensureProjectsForOpenFiles = this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, `Change in extended config file ${extendedConfigFileName} detected`) || ensureProjectsForOpenFiles; - }); - if (ensureProjectsForOpenFiles) this.delayEnsureProjectForOpenFiles(); - }, - PollingInterval.High, - this.hostConfiguration.watchOptions, - WatchType.ExtendedConfigFile, - configFilename - ), + (extendedConfigFileName, extendedConfigFilePath) => + this.watchFactory.watchFile( + extendedConfigFileName, + () => { + // Update extended config cache + cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, fileName => this.toPath(fileName)); + // Update projects + let ensureProjectsForOpenFiles = false; + this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)?.projects.forEach(canonicalPath => { + ensureProjectsForOpenFiles = this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, `Change in extended config file ${extendedConfigFileName} detected`) || ensureProjectsForOpenFiles; + }); + if (ensureProjectsForOpenFiles) this.delayEnsureProjectForOpenFiles(); + }, + PollingInterval.High, + this.hostConfiguration.watchOptions, + WatchType.ExtendedConfigFile, + configFilename, + ), fileName => this.toPath(fileName), ); return configFileExistenceInfo; @@ -2484,8 +2510,10 @@ export class ProjectService { /** @internal */ stopWatchingWildCards(canonicalConfigFilePath: NormalizedPath, forProject: ConfiguredProject) { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath)!; - if (!configFileExistenceInfo.config || - !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath)) { + if ( + !configFileExistenceInfo.config || + !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath) + ) { return; } @@ -2532,7 +2560,7 @@ export class ProjectService { project.currentDirectory, scriptKind, hasMixedContent, - project.directoryStructureHost + project.directoryStructureHost, )); path = scriptInfo.path; const existingValue = projectRootFilesMap.get(path); @@ -2606,7 +2634,7 @@ export class ProjectService { getDirectoryPath(configFileName), config.parsedCommandLine!.options, config.cachedDirectoryStructureHost, - this.hostConfiguration.extraFileExtensions + this.hostConfiguration.extraFileExtensions, ); config.parsedCommandLine = { ...config.parsedCommandLine!, fileNames }; return fileNames; @@ -2654,16 +2682,20 @@ export class ProjectService { const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); diagnostics.push(...project.getAllProjectErrors()); - this.eventHandler({ - eventName: ConfigFileDiagEvent, - data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile } - } satisfies ConfigFileDiagEvent); + this.eventHandler( + { + eventName: ConfigFileDiagEvent, + data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile }, + } satisfies ConfigFileDiagEvent, + ); } private getOrCreateInferredProjectForProjectRootPathIfEnabled(info: ScriptInfo, projectRootPath: NormalizedPath | undefined): InferredProject | undefined { - if (!this.useInferredProjectPerProjectRoot || + if ( + !this.useInferredProjectPerProjectRoot || // Its a dynamic info opened without project root - (info.isDynamic && projectRootPath === undefined)) { + (info.isDynamic && projectRootPath === undefined) + ) { return undefined; } @@ -2721,9 +2753,11 @@ export class ProjectService { const expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory)); // Reuse the project with same current directory but no roots for (const inferredProject of this.inferredProjects) { - if (!inferredProject.projectRootPath && + if ( + !inferredProject.projectRootPath && inferredProject.isOrphan() && - inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory) { + inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory + ) { return inferredProject; } } @@ -2760,8 +2794,11 @@ export class ProjectService { /** @internal */ getOrCreateScriptInfoNotOpenedByClient(uncheckedFileName: string, currentDirectory: string, hostToQueryFileExistsOn: DirectoryStructureHost) { return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath( - toNormalizedPath(uncheckedFileName), currentDirectory, /*scriptKind*/ undefined, - /*hasMixedContent*/ undefined, hostToQueryFileExistsOn + toNormalizedPath(uncheckedFileName), + currentDirectory, + /*scriptKind*/ undefined, + /*hasMixedContent*/ undefined, + hostToQueryFileExistsOn, ); } @@ -2806,10 +2843,12 @@ export class ProjectService { if (toAddInfo !== info) { for (const project of toAddInfo.containingProjects) { // Add the projects only if they can use symLink targets and not already in the list - if (project.languageServiceEnabled && + if ( + project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && - !info.isAttached(project)) { + !info.isAttached(project) + ) { if (!projects) { projects = createMultiMap(); projects.add(toAddInfo.path, project); @@ -2827,9 +2866,11 @@ export class ProjectService { Debug.assert(!info.fileWatcher); // do not watch files with mixed content - server doesn't know how to interpret it // do not watch files in the global cache location - if (!info.isDynamicOrHasMixedContent() && + if ( + !info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || - !startsWith(info.path, this.globalCacheLocationDirectoryPath))) { + !startsWith(info.path, this.globalCacheLocationDirectoryPath)) + ) { const indexOfNodeModules = info.path.indexOf("/node_modules/"); if (!this.host.getModifiedTime || indexOfNodeModules === -1) { info.fileWatcher = this.watchFactory.watchFile( @@ -2837,7 +2878,7 @@ export class ProjectService { (_fileName, eventKind) => this.onSourceFileChanged(info, eventKind), PollingInterval.Medium, this.hostConfiguration.watchOptions, - WatchType.ClosedScriptInfo + WatchType.ClosedScriptInfo, ); } else { @@ -2857,9 +2898,11 @@ export class ProjectService { // Clear module specifier cache for any projects whose cache was affected by // dependency package.jsons in this node_modules directory const basename = getBaseFileName(fileOrDirectoryPath); - if (result.affectedModuleSpecifierCacheProjects?.size && ( - basename === "package.json" || basename === "node_modules" - )) { + if ( + result.affectedModuleSpecifierCacheProjects?.size && ( + basename === "package.json" || basename === "node_modules" + ) + ) { result.affectedModuleSpecifierCacheProjects.forEach(projectName => { this.findProject(projectName)?.getModuleSpecifierCache()?.clear(); }); @@ -2886,7 +2929,7 @@ export class ProjectService { }, WatchDirectoryFlags.Recursive, this.hostConfiguration.watchOptions, - WatchType.NodeModules + WatchType.NodeModules, ); const result: NodeModulesWatcher = { refreshScriptInfoRefCount: 0, @@ -3085,7 +3128,7 @@ export class ProjectService { { getCanonicalFileName: this.toCanonicalFileName, log: s => this.logger.info(s), getSourceFileLike: f => this.getSourceFileLike(f, projectName, declarationInfo) }, declarationInfo.fileName, declarationInfo.textStorage.getLineInfo(), - readMapFile + readMapFile, ); readMapFile = undefined; // Remove ref to project if (sourceMapFileInfo) { @@ -3100,9 +3143,9 @@ export class ProjectService { project.currentDirectory === this.currentDirectory ? mapFileNameFromDeclarationInfo : getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory), - declarationInfo.path + declarationInfo.path, ), - sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project) + sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project), }; } else { @@ -3174,7 +3217,7 @@ export class ProjectService { const lineOffset = info.positionToLineOffset(pos); return { line: lineOffset.line - 1, character: lineOffset.offset - 1 }; }, - getPositionOfLineAndCharacter: (line, character, allowEdits) => info.lineOffsetToPosition(line + 1, character + 1, allowEdits) + getPositionOfLineAndCharacter: (line, character, allowEdits) => info.lineOffsetToPosition(line + 1, character + 1, allowEdits), }; } return info.sourceFileLike; @@ -3212,9 +3255,11 @@ export class ProjectService { if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { // Load configured projects for external projects that are pending reload this.configuredProjects.forEach(project => { - if (project.hasExternalProjectRef() && + if ( + project.hasExternalProjectRef() && project.pendingReload === ConfigFileProgramReloadLevel.Full && - !this.pendingProjectUpdates.has(project.getProjectName())) { + !this.pendingProjectUpdates.has(project.getProjectName()) + ) { project.updateGraph(); } }); @@ -3348,7 +3393,7 @@ export class ProjectService { reloadChildProject(child); return projectContainsInfoDirectly(child, info); }, - ProjectReferenceProjectLoadKind.FindCreate + ProjectReferenceProjectLoadKind.FindCreate, ); if (referencedProject) { // Reload the project's tree that is already present @@ -3356,7 +3401,7 @@ export class ProjectService { project, /*fileName*/ undefined, reloadChildProject, - ProjectReferenceProjectLoadKind.Find + ProjectReferenceProjectLoadKind.Find, ); } } @@ -3387,10 +3432,12 @@ export class ProjectService { Debug.assert(info.containingProjects.length > 0); const firstProject = info.containingProjects[0]; - if (!firstProject.isOrphan() && + if ( + !firstProject.isOrphan() && isInferredProject(firstProject) && firstProject.isRoot(info) && - forEach(info.containingProjects, p => p !== firstProject && !p.isOrphan())) { + forEach(info.containingProjects, p => p !== firstProject && !p.isOrphan()) + ) { firstProject.removeFile(info, /*fileExists*/ true, /*detachFromProject*/ true); } } @@ -3485,7 +3532,7 @@ export class ProjectService { return projectContainsOriginalInfo(child) ? child : undefined; }, ProjectReferenceProjectLoadKind.FindCreateLoad, - `Creating project referenced in solution ${configuredProject.projectName} to find possible configured project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}` + `Creating project referenced in solution ${configuredProject.projectName} to find possible configured project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`, ); if (!configuredProject) return undefined; if (configuredProject === project) return originalLocation; @@ -3583,7 +3630,7 @@ export class ProjectService { } }, ProjectReferenceProjectLoadKind.FindCreateLoad, - `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open` + `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open`, ); } @@ -3638,7 +3685,8 @@ export class ProjectService { // Create configured project till project root while (true) { // Skip if project is not composite - if (!project.isInitialLoadPending() && + if ( + !project.isInitialLoadPending() && ( !project.getCompilerOptions().composite || project.getCompilerOptions().disableSolutionSearching @@ -3649,7 +3697,7 @@ export class ProjectService { const configFileName = this.getConfigFileNameForFile({ fileName: project.getConfigFilePath(), path: info.path, - configFileInfo: true + configFileInfo: true, }); if (!configFileName) return; @@ -3668,7 +3716,7 @@ export class ProjectService { loadAncestorProjectTree(forProjects?: ReadonlyCollection) { forProjects = forProjects || mapDefinedEntries( this.configuredProjects, - (key, project) => !project.isInitialLoadPending() ? [key, true] : undefined + (key, project) => !project.isInitialLoadPending() ? [key, true] : undefined, ); const seenProjects = new Set(); @@ -3745,7 +3793,7 @@ export class ProjectService { (_value, configuredProjectPath) => { const project = this.getConfiguredProjectByCanonicalConfigFilePath(configuredProjectPath); return project && retainConfiguredProject(project); - } + }, ); } }; @@ -3770,7 +3818,7 @@ export class ProjectService { // If the configured project for project reference has more than zero references, keep it alive forEachReferencedProject( project, - ref => isRetained(ref) && retainConfiguredProject(project) + ref => isRetained(ref) && retainConfiguredProject(project), ); } }); @@ -3808,10 +3856,12 @@ export class ProjectService { sourceInfos = info.sourceMapFilePath.sourceInfos; } if (!sourceInfos) return; - if (!forEachKey(sourceInfos, path => { - const info = this.getScriptInfoForPath(path); - return !!info && (info.isScriptOpen() || !info.isOrphan()); - })) { + if ( + !forEachKey(sourceInfos, path => { + const info = this.getScriptInfoForPath(path); + return !!info && (info.isScriptOpen() || !info.isOrphan()); + }) + ) { return; } } @@ -3878,8 +3928,8 @@ export class ProjectService { lastKnownProjectVersions: protocol.ProjectVersionInfo[], currentProjects: Iterable, includeProjectReferenceRedirectInfo: boolean | undefined, - result: ProjectFilesWithTSDiagnostics[] - ): void { + result: ProjectFilesWithTSDiagnostics[], + ): void { for (const proj of currentProjects) { const knownProject = find(lastKnownProjectVersions, p => p.projectName === proj.getProjectName()); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo)); @@ -3907,7 +3957,7 @@ export class ProjectService { file.content, tryConvertScriptKindName(file.scriptKind!), file.hasMixedContent, - file.projectRootPath ? toNormalizedPath(file.projectRootPath) : undefined + file.projectRootPath ? toNormalizedPath(file.projectRootPath) : undefined, ); (openScriptInfos || (openScriptInfos = [])).push(info); } @@ -4283,12 +4333,15 @@ export class ProjectService { } // Otherwise, load the plugin using `require` - this.endEnablePlugin(project, Project.importServicePluginSync( - pluginConfigEntry, - searchPaths, - this.host, - s => this.logger.info(s), - )); + this.endEnablePlugin( + project, + Project.importServicePluginSync( + pluginConfigEntry, + searchPaths, + this.host, + s => this.logger.info(s), + ), + ); } /** @@ -4437,8 +4490,10 @@ export class ProjectService { getNearestAncestorDirectoryWithPackageJson(fileName: string): string | undefined { return forEachAncestorDirectory(fileName, directory => { switch (this.packageJsonCache.directoryHasPackageJson(this.toPath(directory))) { - case Ternary.True: return directory; - case Ternary.False: return undefined; + case Ternary.True: + return directory; + case Ternary.False: + return undefined; case Ternary.Maybe: return this.host.fileExists(combinePaths(directory, "package.json")) ? directory @@ -4452,28 +4507,31 @@ export class ProjectService { const watchers = this.packageJsonFilesMap || (this.packageJsonFilesMap = new Map()); if (!watchers.has(path)) { this.invalidateProjectPackageJson(path); - watchers.set(path, this.watchFactory.watchFile( + watchers.set( path, - (fileName, eventKind) => { - const path = this.toPath(fileName); - switch (eventKind) { - case FileWatcherEventKind.Created: - return Debug.fail(); - case FileWatcherEventKind.Changed: - this.packageJsonCache.addOrUpdate(path); - this.invalidateProjectPackageJson(path); - break; - case FileWatcherEventKind.Deleted: - this.packageJsonCache.delete(path); - this.invalidateProjectPackageJson(path); - watchers.get(path)!.close(); - watchers.delete(path); - } - }, - PollingInterval.Low, - this.hostConfiguration.watchOptions, - WatchType.PackageJson, - )); + this.watchFactory.watchFile( + path, + (fileName, eventKind) => { + const path = this.toPath(fileName); + switch (eventKind) { + case FileWatcherEventKind.Created: + return Debug.fail(); + case FileWatcherEventKind.Changed: + this.packageJsonCache.addOrUpdate(path); + this.invalidateProjectPackageJson(path); + break; + case FileWatcherEventKind.Deleted: + this.packageJsonCache.delete(path); + this.invalidateProjectPackageJson(path); + watchers.get(path)!.close(); + watchers.delete(path); + } + }, + PollingInterval.Low, + this.hostConfiguration.watchOptions, + WatchType.PackageJson, + ), + ); } } @@ -4486,9 +4544,12 @@ export class ProjectService { /** @internal */ includePackageJsonAutoImports(): PackageJsonAutoImportPreference { switch (this.hostConfiguration.preferences.includePackageJsonAutoImports) { - case "on": return PackageJsonAutoImportPreference.On; - case "off": return PackageJsonAutoImportPreference.Off; - default: return PackageJsonAutoImportPreference.Auto; + case "on": + return PackageJsonAutoImportPreference.On; + case "off": + return PackageJsonAutoImportPreference.Off; + default: + return PackageJsonAutoImportPreference.Auto; } } @@ -4524,7 +4585,7 @@ function createIncompleteCompletionsCache(): IncompleteCompletionsCache { }, clear() { info = undefined; - } + }, }; } diff --git a/src/server/moduleSpecifierCache.ts b/src/server/moduleSpecifierCache.ts index 2f2142a5bb0fe..7a4499c434874 100644 --- a/src/server/moduleSpecifierCache.ts +++ b/src/server/moduleSpecifierCache.ts @@ -76,7 +76,7 @@ export function createModuleSpecifierCache(host: ModuleSpecifierResolutionCacheH }, count() { return cache ? cache.size : 0; - } + }, }; if (Debug.isDebugging) { Object.defineProperty(result, "__cache", { get: () => cache }); diff --git a/src/server/packageJsonCache.ts b/src/server/packageJsonCache.ts index d1c12c65d9bfb..dc62d64f69334 100644 --- a/src/server/packageJsonCache.ts +++ b/src/server/packageJsonCache.ts @@ -9,7 +9,9 @@ import { Ternary, tryFileExists, } from "./_namespaces/ts"; -import { ProjectService } from "./_namespaces/ts.server"; +import { + ProjectService, +} from "./_namespaces/ts.server"; /** @internal */ export interface PackageJsonCache { diff --git a/src/server/project.ts b/src/server/project.ts index 1c9e985c83c50..97451f224c7f7 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -169,12 +169,18 @@ export type Mutable = { -readonly [K in keyof T]: T[K]; }; /** @internal */ export function countEachFileTypes(infos: ScriptInfo[], includeSizes = false): FileStats { const result: Mutable = { - js: 0, jsSize: 0, - jsx: 0, jsxSize: 0, - ts: 0, tsSize: 0, - tsx: 0, tsxSize: 0, - dts: 0, dtsSize: 0, - deferred: 0, deferredSize: 0, + js: 0, + jsSize: 0, + jsx: 0, + jsxSize: 0, + ts: 0, + tsSize: 0, + tsx: 0, + tsxSize: 0, + dts: 0, + dtsSize: 0, + deferred: 0, + deferredSize: 0, }; for (const info of infos) { const fileSize = includeSizes ? info.textStorage.getTelemetryFileSize() : 0; @@ -255,7 +261,7 @@ export interface PluginModuleWithName { module: PluginModule; } -export type PluginModuleFactory = (mod: { typescript: typeof ts }) => PluginModule; +export type PluginModuleFactory = (mod: { typescript: typeof ts; }) => PluginModule; /** @internal */ export interface PluginImportResult { @@ -295,12 +301,11 @@ export interface EmitResult { const enum TypingWatcherType { FileWatcher = "FileWatcher", - DirectoryWatcher = "DirectoryWatcher" + DirectoryWatcher = "DirectoryWatcher", } type TypingWatchers = Map & { isInvoked?: boolean; }; - export abstract class Project implements LanguageServiceHost, ModuleResolutionHost { private rootFiles: ScriptInfo[] = []; private rootFilesMap = new Map(); @@ -563,7 +568,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo this.resolutionCache = createResolutionCache( this, this.currentDirectory, - /*logChangesWhenResolvingModule*/ true + /*logChangesWhenResolvingModule*/ true, ); this.languageService = createLanguageService(this, this.documentRegistry, this.projectService.serverMode); if (lastFileExceededProgramSize) { @@ -599,7 +604,8 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo if (this.program && !this.symlinks.hasProcessedResolutions()) { this.symlinks.setSymlinksFromResolutions( this.program.getSourceFiles(), - this.program.getAutomaticTypeDirectiveResolutions()); + this.program.getAutomaticTypeDirectiveResolutions(), + ); } return this.symlinks; } @@ -763,7 +769,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo flags, this.projectService.getWatchOptions(this), WatchType.FailedLookupLocations, - this + this, ); } @@ -775,7 +781,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo PollingInterval.High, this.projectService.getWatchOptions(this), WatchType.AffectingFileLocation, - this + this, ); } @@ -795,8 +801,10 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo /** @internal */ invalidateResolutionsOfFailedLookupLocations() { - if (this.clearInvalidateResolutionOfFailedLookupTimer() && - this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { + if ( + this.clearInvalidateResolutionOfFailedLookupTimer() && + this.resolutionCache.invalidateResolutionsOfFailedLookupLocations() + ) { this.markAsDirty(); this.projectService.delayEnsureProjectForOpenFiles(); } @@ -815,7 +823,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo flags, this.projectService.getWatchOptions(this), WatchType.TypeRoots, - this + this, ); } @@ -927,7 +935,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo this.cancellationToken, this.projectService.host, ), - sourceFile => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined + sourceFile => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined, ); } @@ -977,8 +985,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo for (const f of this.program.getSourceFiles()) { this.detachScriptInfoIfNotRoot(f.fileName); } - this.program.forEachResolvedProjectReference(ref => - this.detachScriptInfoFromProject(ref.sourceFile.fileName)); + this.program.forEachResolvedProjectReference(ref => this.detachScriptInfoFromProject(ref.sourceFile.fileName)); this.program = undefined; } } @@ -1185,7 +1192,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo: boolean) { return this.getFileNames().map((fileName): protocol.FileWithProjectReferenceRedirectInfo => ({ fileName, - isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName) + isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName), })); } @@ -1375,10 +1382,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo /** @internal */ updateTypingFiles(typingFiles: SortedReadonlyArray) { - if (enumerateInsertsAndDeletes(typingFiles, this.typingFiles, getStringComparer(!this.useCaseSensitiveFileNames()), - /*inserted*/ noop, - removed => this.detachScriptInfoFromProject(removed) - )) { + if (enumerateInsertsAndDeletes(typingFiles, this.typingFiles, getStringComparer(!this.useCaseSensitiveFileNames()), /*inserted*/ noop, removed => this.detachScriptInfoFromProject(removed))) { // If typing files changed, then only schedule project update this.typingFiles = typingFiles; // Invalidate files with unresolved imports @@ -1421,30 +1425,33 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo const canonicalPath = this.toPath(path); toRemove.delete(canonicalPath); if (!this.typingWatchers!.has(canonicalPath)) { - this.typingWatchers!.set(canonicalPath, typingsWatcherType === TypingWatcherType.FileWatcher ? - this.projectService.watchFactory.watchFile( - path, - () => !this.typingWatchers!.isInvoked ? - this.onTypingInstallerWatchInvoke() : - this.writeLog(`TypingWatchers already invoked`), - PollingInterval.High, - this.projectService.getWatchOptions(this), - WatchType.TypingInstallerLocationFile, - this, - ) : - this.projectService.watchFactory.watchDirectory( - path, - f => { - if (this.typingWatchers!.isInvoked) return this.writeLog(`TypingWatchers already invoked`); - if (!fileExtensionIs(f, Extension.Json)) return this.writeLog(`Ignoring files that are not *.json`); - if (comparePaths(f, combinePaths(this.projectService.typingsInstaller.globalTypingsCacheLocation!, "package.json"), !this.useCaseSensitiveFileNames())) return this.writeLog(`Ignoring package.json change at global typings location`); - this.onTypingInstallerWatchInvoke(); - }, - WatchDirectoryFlags.Recursive, - this.projectService.getWatchOptions(this), - WatchType.TypingInstallerLocationDirectory, - this, - ) + this.typingWatchers!.set( + canonicalPath, + typingsWatcherType === TypingWatcherType.FileWatcher ? + this.projectService.watchFactory.watchFile( + path, + () => + !this.typingWatchers!.isInvoked ? + this.onTypingInstallerWatchInvoke() : + this.writeLog(`TypingWatchers already invoked`), + PollingInterval.High, + this.projectService.getWatchOptions(this), + WatchType.TypingInstallerLocationFile, + this, + ) : + this.projectService.watchFactory.watchDirectory( + path, + f => { + if (this.typingWatchers!.isInvoked) return this.writeLog(`TypingWatchers already invoked`); + if (!fileExtensionIs(f, Extension.Json)) return this.writeLog(`Ignoring files that are not *.json`); + if (comparePaths(f, combinePaths(this.projectService.typingsInstaller.globalTypingsCacheLocation!, "package.json"), !this.useCaseSensitiveFileNames())) return this.writeLog(`Ignoring package.json change at global typings location`); + this.onTypingInstallerWatchInvoke(); + }, + WatchDirectoryFlags.Recursive, + this.projectService.getWatchOptions(this), + WatchType.TypingInstallerLocationDirectory, + this, + ), ); } }; @@ -1545,17 +1552,19 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo this.program, this.missingFilesMap || (this.missingFilesMap = new Map()), // Watch the missing files - missingFilePath => this.addMissingFileWatcher(missingFilePath) + missingFilePath => this.addMissingFileWatcher(missingFilePath), ); if (this.generatedFilesMap) { const outPath = outFile(this.compilerOptions); if (isGeneratedFileWatcher(this.generatedFilesMap)) { // --out - if (!outPath || !this.isValidGeneratedFileWatcher( - removeFileExtension(outPath) + Extension.Dts, - this.generatedFilesMap, - )) { + if ( + !outPath || !this.isValidGeneratedFileWatcher( + removeFileExtension(outPath) + Extension.Dts, + this.generatedFilesMap, + ) + ) { this.clearGeneratedFileWatch(); } } @@ -1567,12 +1576,14 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo else { this.generatedFilesMap.forEach((watcher, source) => { const sourceFile = this.program!.getSourceFileByPath(source); - if (!sourceFile || + if ( + !sourceFile || sourceFile.resolvedPath !== source || !this.isValidGeneratedFileWatcher( getDeclarationEmitOutputFilePathWorker(sourceFile.fileName, this.compilerOptions, this.currentDirectory, this.program!.getCommonSourceDirectory(), this.getCanonicalFileName), - watcher - )) { + watcher, + ) + ) { closeFileWatcherOf(watcher); (this.generatedFilesMap as Map).delete(source); } @@ -1616,15 +1627,17 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo const oldExternalFiles = this.externalFiles || emptyArray as SortedReadonlyArray; this.externalFiles = this.getExternalFiles(); - enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, getStringComparer(!this.useCaseSensitiveFileNames()), - // Ensure a ScriptInfo is created for new external files. This is performed indirectly + enumerateInsertsAndDeletes( + this.externalFiles, + oldExternalFiles, + getStringComparer(!this.useCaseSensitiveFileNames()), // Ensure a ScriptInfo is created for new external files. This is performed indirectly // by the host for files in the program when the program is retrieved above but // the program doesn't contain external files so this must be done explicitly. inserted => { const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, this.currentDirectory, this.directoryStructureHost); scriptInfo?.attachToProject(this); }, - removed => this.detachScriptInfoFromProject(removed) + removed => this.detachScriptInfoFromProject(removed), ); const elapsed = timestamp() - start; this.sendPerformanceEvent("UpdateGraph", elapsed); @@ -1687,7 +1700,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo PollingInterval.Medium, this.projectService.getWatchOptions(this), WatchType.MissingFile, - this + this, ); return fileWatcher; } @@ -1733,8 +1746,8 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo PollingInterval.High, this.projectService.getWatchOptions(this), WatchType.MissingGeneratedFile, - this - ) + this, + ), }; } @@ -1778,7 +1791,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo let strBuilder = `\tFiles (${sourceFiles.length})\n`; if (writeProjectFileNames) { for (const file of sourceFiles) { - strBuilder += `\t${file.fileName}${writeFileVersionAndText?` ${file.version} ${JSON.stringify(file.text)}` : ""}\n`; + strBuilder += `\t${file.fileName}${writeFileVersionAndText ? ` ${file.version} ${JSON.stringify(file.text)}` : ""}\n`; } if (writeFileExplaination) { strBuilder += "\n\n"; @@ -1842,13 +1855,13 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo /** @internal */ getChangesSinceVersion(lastKnownVersion?: number, includeProjectReferenceRedirectInfo?: boolean): ProjectFilesWithTSDiagnostics { - const includeProjectReferenceRedirectInfoIfRequested = - includeProjectReferenceRedirectInfo - ? (files: Map) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]): protocol.FileWithProjectReferenceRedirectInfo => ({ + const includeProjectReferenceRedirectInfoIfRequested = includeProjectReferenceRedirectInfo + ? (files: Map) => + arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]): protocol.FileWithProjectReferenceRedirectInfo => ({ fileName, - isSourceOfProjectReferenceRedirect + isSourceOfProjectReferenceRedirect, })) - : (files: Map) => arrayFrom(files.keys()); + : (files: Map) => arrayFrom(files.keys()); // Update the graph only if initial configured project load is not pending if (!this.isInitialLoadPending()) { @@ -1861,7 +1874,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo isInferred: isInferredProject(this), options: this.getCompilationSettings(), languageServiceDisabled: !this.languageServiceEnabled, - lastFileExceededProgramSize: this.lastFileExceededProgramSize + lastFileExceededProgramSize: this.lastFileExceededProgramSize, }; const updatedFileNames = this.updatedFileNames; this.updatedFileNames = undefined; @@ -1875,12 +1888,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo const lastReportedFileNames = this.lastReportedFileNames; const externalFiles = this.getExternalFiles().map((f): protocol.FileWithProjectReferenceRedirectInfo => ({ fileName: toNormalizedPath(f), - isSourceOfProjectReferenceRedirect: false + isSourceOfProjectReferenceRedirect: false, })); const currentFiles = arrayToMap( this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo).concat(externalFiles), info => info.fileName, - info => info.isSourceOfProjectReferenceRedirect + info => info.isSourceOfProjectReferenceRedirect, ); const added: Map = new Map(); @@ -1896,7 +1909,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo else if (includeProjectReferenceRedirectInfo && isSourceOfProjectReferenceRedirect !== lastReportedFileNames.get(fileName)) { updatedRedirects.push({ fileName, - isSourceOfProjectReferenceRedirect + isSourceOfProjectReferenceRedirect, }); } }); @@ -1915,12 +1928,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo updated: includeProjectReferenceRedirectInfo ? updated.map((fileName): protocol.FileWithProjectReferenceRedirectInfo => ({ fileName, - isSourceOfProjectReferenceRedirect: this.isSourceOfProjectReferenceRedirect(fileName) + isSourceOfProjectReferenceRedirect: this.isSourceOfProjectReferenceRedirect(fileName), })) : updated, - updatedRedirects: includeProjectReferenceRedirectInfo ? updatedRedirects : undefined + updatedRedirects: includeProjectReferenceRedirectInfo ? updatedRedirects : undefined, }, - projectErrors: this.getGlobalProjectErrors() + projectErrors: this.getGlobalProjectErrors(), }; } else { @@ -1928,19 +1941,19 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo const projectFileNames = this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo); const externalFiles = this.getExternalFiles().map((f): protocol.FileWithProjectReferenceRedirectInfo => ({ fileName: toNormalizedPath(f), - isSourceOfProjectReferenceRedirect: false + isSourceOfProjectReferenceRedirect: false, })); const allFiles = projectFileNames.concat(externalFiles); this.lastReportedFileNames = arrayToMap( allFiles, info => info.fileName, - info => info.isSourceOfProjectReferenceRedirect + info => info.isSourceOfProjectReferenceRedirect, ); this.lastReportedVersion = this.projectProgramVersion; return { info, files: includeProjectReferenceRedirectInfo ? allFiles : allFiles.map(f => f.fileName), - projectErrors: this.getGlobalProjectErrors() + projectErrors: this.getGlobalProjectErrors(), }; } } @@ -2009,7 +2022,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo languageService: this.languageService, languageServiceHost: this, serverHost: this.projectService.host, - session: this.projectService.session + session: this.projectService.session, }; const pluginModule = pluginModuleFactory({ typescript: ts }); @@ -2084,10 +2097,12 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo /** @internal */ includePackageJsonAutoImports(): PackageJsonAutoImportPreference { - if (this.projectService.includePackageJsonAutoImports() === PackageJsonAutoImportPreference.Off || + if ( + this.projectService.includePackageJsonAutoImports() === PackageJsonAutoImportPreference.Off || !this.languageServiceEnabled || isInsideNodeModules(this.currentDirectory) || - !this.isDefaultProjectForOpenFiles()) { + !this.isDefaultProjectForOpenFiles() + ) { return PackageJsonAutoImportPreference.Off; } return this.projectService.includePackageJsonAutoImports(); @@ -2149,7 +2164,8 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo private isDefaultProjectForOpenFiles(): boolean { return !!forEachEntry( this.projectService.openFiles, - (_, fileName) => this.projectService.tryGetDefaultProjectForFile(toNormalizedPath(fileName)) === this); + (_, fileName) => this.projectService.tryGetDefaultProjectForFile(toNormalizedPath(fileName)) === this, + ); } /** @internal */ @@ -2177,7 +2193,8 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient( pathToAdd, this.currentDirectory, - this.noDtsResolutionProject!.directoryStructureHost); + this.noDtsResolutionProject!.directoryStructureHost, + ); if (info) { this.noDtsResolutionProject!.addRoot(info, pathToAdd); } @@ -2215,8 +2232,7 @@ function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: const sourceFiles = program.getSourceFiles(); tracing?.push(tracing.Phase.Session, "getUnresolvedImports", { count: sourceFiles.length }); const ambientModules = program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); - const result = sortAndDeduplicate(flatMap(sourceFiles, sourceFile => - extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile))); + const result = sortAndDeduplicate(flatMap(sourceFiles, sourceFile => extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile))); tracing?.pop(); return result; } @@ -2226,9 +2242,11 @@ function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules let unresolvedImports: string[] | undefined; file.resolvedModules.forEach(({ resolvedModule }, name) => { // pick unresolved non-relative names - if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && + if ( + (!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && !isExternalModuleNameRelative(name) && - !ambientModules.some(m => m === name)) { + !ambientModules.some(m => m === name) + ) { unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName); } }); @@ -2284,8 +2302,10 @@ export class InferredProject extends Project { watchOptions: WatchOptions | undefined, projectRootPath: NormalizedPath | undefined, currentDirectory: string, - typeAcquisition: TypeAcquisition | undefined) { - super(projectService.newInferredProjectName(), + typeAcquisition: TypeAcquisition | undefined, + ) { + super( + projectService.newInferredProjectName(), ProjectKind.Inferred, projectService, documentRegistry, @@ -2296,7 +2316,8 @@ export class InferredProject extends Project { /*compileOnSaveEnabled*/ false, watchOptions, projectService.host, - currentDirectory); + currentDirectory, + ); this.typeAcquisition = typeAcquisition; this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); if (!projectRootPath && !projectService.useSingleInferredProject) { @@ -2350,7 +2371,7 @@ export class InferredProject extends Project { return this.typeAcquisition || { enable: allRootFilesAreJsOrDts(this), include: ts.emptyArray, - exclude: ts.emptyArray + exclude: ts.emptyArray, }; } } @@ -2358,17 +2379,7 @@ export class InferredProject extends Project { /** @internal */ export class AuxiliaryProject extends Project { constructor(projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, currentDirectory: string) { - super(projectService.newAuxiliaryProjectName(), - ProjectKind.Auxiliary, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ false, - /*lastFileExceededProgramSize*/ undefined, - compilerOptions, - /*compileOnSaveEnabled*/ false, - /*watchOptions*/ undefined, - projectService.host, - currentDirectory); + super(projectService.newAuxiliaryProjectName(), ProjectKind.Auxiliary, projectService, documentRegistry, /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ undefined, compilerOptions, /*compileOnSaveEnabled*/ false, /*watchOptions*/ undefined, projectService.host, currentDirectory); } override isOrphan(): boolean { @@ -2425,7 +2436,8 @@ export class AutoImportProviderProject extends Project { hostProject.currentDirectory, compilerOptions, host, - program.getModuleResolutionCache()); + program.getModuleResolutionCache(), + ); if (packageJson) { const entrypoints = getRootNamesFromPackageJson(packageJson, program, symlinkCache); if (entrypoints) { @@ -2444,7 +2456,8 @@ export class AutoImportProviderProject extends Project { directory, compilerOptions, host, - program.getModuleResolutionCache()); + program.getModuleResolutionCache(), + ); if (typesPackageJson) { const entrypoints = getRootNamesFromPackageJson(typesPackageJson, program, symlinkCache); rootNames = concatenate(rootNames, entrypoints); @@ -2484,7 +2497,8 @@ export class AutoImportProviderProject extends Project { compilerOptions, host, program.getModuleResolutionCache(), - resolveJs); + resolveJs, + ); if (entrypoints) { const real = host.realpath?.(packageJson.packageDirectory); const isSymlink = real && real !== packageJson.packageDirectory; @@ -2543,17 +2557,7 @@ export class AutoImportProviderProject extends Project { documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, ) { - super(hostProject.projectService.newAutoImportProviderProjectName(), - ProjectKind.AutoImportProvider, - hostProject.projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ false, - /*lastFileExceededProgramSize*/ undefined, - compilerOptions, - /*compileOnSaveEnabled*/ false, - hostProject.getWatchOptions(), - hostProject.projectService.host, - hostProject.currentDirectory); + super(hostProject.projectService.newAutoImportProviderProjectName(), ProjectKind.AutoImportProvider, hostProject.projectService, documentRegistry, /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ undefined, compilerOptions, /*compileOnSaveEnabled*/ false, hostProject.getWatchOptions(), hostProject.projectService.host, hostProject.currentDirectory); this.rootFileNames = initialRootNames; this.useSourceOfProjectReferenceRedirect = maybeBind(this.hostProject, this.hostProject.useSourceOfProjectReferenceRedirect); @@ -2576,7 +2580,8 @@ export class AutoImportProviderProject extends Project { this.hostProject.includePackageJsonAutoImports(), this.hostProject, this.hostProject.getHostForAutoImportProvider(), - this.getCompilationSettings()); + this.getCompilationSettings(), + ); } this.projectService.setFileNamesOfAutoImportProviderProject(this, rootFileNames); @@ -2692,23 +2697,8 @@ export class ConfiguredProject extends Project { private compilerHost?: CompilerHost; /** @internal */ - constructor(configFileName: NormalizedPath, - readonly canonicalConfigFilePath: NormalizedPath, - projectService: ProjectService, - documentRegistry: DocumentRegistry, - cachedDirectoryStructureHost: CachedDirectoryStructureHost) { - super(configFileName, - ProjectKind.Configured, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ false, - /*lastFileExceededProgramSize*/ undefined, - /*compilerOptions*/ {}, - /*compileOnSaveEnabled*/ false, - /*watchOptions*/ undefined, - cachedDirectoryStructureHost, - getDirectoryPath(configFileName) - ); + constructor(configFileName: NormalizedPath, readonly canonicalConfigFilePath: NormalizedPath, projectService: ProjectService, documentRegistry: DocumentRegistry, cachedDirectoryStructureHost: CachedDirectoryStructureHost) { + super(configFileName, ProjectKind.Configured, projectService, documentRegistry, /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ undefined, /*compilerOptions*/ {}, /*compileOnSaveEnabled*/ false, /*watchOptions*/ undefined, cachedDirectoryStructureHost, getDirectoryPath(configFileName)); } /** @internal */ @@ -2818,7 +2808,7 @@ export class ConfiguredProject extends Project { /** @internal */ forEachResolvedProjectReference( - cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined + cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined, ): T | undefined { return this.getCurrentProgram()?.forEachResolvedProjectReference(cb); } @@ -2869,8 +2859,7 @@ export class ConfiguredProject extends Project { } override close() { - this.projectService.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => - this.releaseParsedConfig(canonicalConfigFilePath)); + this.projectService.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.releaseParsedConfig(canonicalConfigFilePath)); this.projectErrors = undefined; this.openFileWatchTriggered.clear(); this.compilerHost = undefined; @@ -2902,10 +2891,11 @@ export class ConfiguredProject extends Project { return forEachResolvedProjectReferenceProject( this, info.path, - child => projectContainsInfoDirectly(child, info) ? - child : - undefined, - ProjectReferenceProjectLoadKind.Find + child => + projectContainsInfoDirectly(child, info) ? + child : + undefined, + ProjectReferenceProjectLoadKind.Find, ); } @@ -2936,18 +2926,18 @@ export class ConfiguredProject extends Project { // We know exact set of open files that get impacted by this configured project as the files in the project // The project is referenced only if open files impacted by this project are present in this project return !!configFileExistenceInfo.openFilesImpactedByConfigFile && forEachEntry( - configFileExistenceInfo.openFilesImpactedByConfigFile, - (_value, infoPath) => { - const info = this.projectService.getScriptInfoForPath(infoPath)!; - return this.containsScriptInfo(info) || - !!forEachResolvedProjectReferenceProject( - this, - info.path, - child => child.containsScriptInfo(info), - ProjectReferenceProjectLoadKind.Find - ); - } - ) || false; + configFileExistenceInfo.openFilesImpactedByConfigFile, + (_value, infoPath) => { + const info = this.projectService.getScriptInfoForPath(infoPath)!; + return this.containsScriptInfo(info) || + !!forEachResolvedProjectReferenceProject( + this, + info.path, + child => child.containsScriptInfo(info), + ProjectReferenceProjectLoadKind.Find, + ); + }, + ) || false; } /** @internal */ @@ -2972,25 +2962,8 @@ export class ConfiguredProject extends Project { export class ExternalProject extends Project { excludedFiles: readonly NormalizedPath[] = []; /** @internal */ - constructor(public externalProjectName: string, - projectService: ProjectService, - documentRegistry: DocumentRegistry, - compilerOptions: CompilerOptions, - lastFileExceededProgramSize: string | undefined, - public override compileOnSaveEnabled: boolean, - projectFilePath?: string, - watchOptions?: WatchOptions) { - super(externalProjectName, - ProjectKind.External, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ true, - lastFileExceededProgramSize, - compilerOptions, - compileOnSaveEnabled, - watchOptions, - projectService.host, - getDirectoryPath(projectFilePath || normalizeSlashes(externalProjectName))); + constructor(public externalProjectName: string, projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, lastFileExceededProgramSize: string | undefined, public override compileOnSaveEnabled: boolean, projectFilePath?: string, watchOptions?: WatchOptions) { + super(externalProjectName, ProjectKind.External, projectService, documentRegistry, /*hasExplicitListOfFiles*/ true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, projectService.host, getDirectoryPath(projectFilePath || normalizeSlashes(externalProjectName))); this.enableGlobalPlugins(this.getCompilerOptions()); } diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 50fbe3deb139f..1b0624497ef6c 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -172,7 +172,7 @@ export const enum CommandTypes { PrepareCallHierarchy = "prepareCallHierarchy", ProvideCallHierarchyIncomingCalls = "provideCallHierarchyIncomingCalls", ProvideCallHierarchyOutgoingCalls = "provideCallHierarchyOutgoingCalls", - ProvideInlayHints = "provideInlayHints" + ProvideInlayHints = "provideInlayHints", } /** @@ -295,8 +295,8 @@ export interface FileRequestArgs { file: string; /* - * Optional name of project that contains file - */ + * Optional name of project that contains file + */ projectFileName?: string; } @@ -707,7 +707,6 @@ export type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { interactiveRefactorArguments?: InteractiveRefactorArguments; }; - export interface GetEditsForRefactorResponse extends Response { body?: RefactorEditInfo; } @@ -792,7 +791,7 @@ export interface ApplyCodeActionCommandRequest extends Request { } // All we need is the `success` and `message` fields of Response. -export interface ApplyCodeActionCommandResponse extends Response { } +export interface ApplyCodeActionCommandResponse extends Response {} export interface FileRangeRequestArgs extends FileRequestArgs { /** @@ -935,12 +934,12 @@ export interface EncodedSemanticClassificationsRequestArgs extends FileRequestAr * Optional parameter for the semantic highlighting response, if absent it * defaults to "original". */ - format?: "original" | "2020" + format?: "original" | "2020"; } /** The response for a EncodedSemanticClassificationsRequest */ export interface EncodedSemanticClassificationsResponse extends Response { - body?: EncodedSemanticClassificationsResponseBody + body?: EncodedSemanticClassificationsResponseBody; } /** @@ -1136,7 +1135,7 @@ export interface JsxClosingTagRequest extends FileLocationRequest { readonly arguments: JsxClosingTagRequestArgs; } -export interface JsxClosingTagRequestArgs extends FileLocationRequestArgs { } +export interface JsxClosingTagRequestArgs extends FileLocationRequestArgs {} export interface JsxClosingTagResponse extends Response { readonly body: TextInsertion; @@ -1578,12 +1577,10 @@ export interface ChangedOpenFile { changes: TextChange[]; } - /** * Information found in a configure request. */ export interface ConfigureRequestArguments { - /** * Information about the host, for example 'Emacs 24.4' or * 'Sublime Text version 3075' @@ -2491,7 +2488,6 @@ export interface CompletionDetailsResponse extends Response { * Signature help information for a single parameter */ export interface SignatureHelpParameter { - /** * The parameter's name */ @@ -2517,7 +2513,6 @@ export interface SignatureHelpParameter { * Represents a single signature to show in signature help. */ export interface SignatureHelpItem { - /** * Whether the signature accepts a variable number of arguments. */ @@ -2558,7 +2553,6 @@ export interface SignatureHelpItem { * Signature help items found in the response of a signature help request. */ export interface SignatureHelpItems { - /** * The signature help items. */ @@ -3026,7 +3020,7 @@ export interface LargeFileReferencedEventBody { /** @internal */ export type AnyEvent = - RequestCompletedEvent + | RequestCompletedEvent | DiagnosticEvent | ConfigFileDiagnosticEvent | ProjectLanguageServiceStateEvent @@ -3388,7 +3382,7 @@ export interface NavTreeResponse extends Response { export interface CallHierarchyItem { name: string; kind: ScriptElementKind; - kindModifiers?: string + kindModifiers?: string; file: string; span: TextSpan; selectionSpan: TextSpan; @@ -3537,7 +3531,7 @@ export interface UserPreferences { readonly includeInlayParameterNameHints?: "none" | "literals" | "all"; readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean; - readonly includeInlayFunctionParameterTypeHints?: boolean, + readonly includeInlayFunctionParameterTypeHints?: boolean; readonly includeInlayVariableTypeHints?: boolean; readonly includeInlayVariableTypeHintsWhenTypeMatchesName?: boolean; readonly includeInlayPropertyDeclarationTypeHints?: boolean; @@ -3695,7 +3689,7 @@ export const enum ModuleKind { System = "System", ES6 = "ES6", ES2015 = "ES2015", - ESNext = "ESNext" + ESNext = "ESNext", } export const enum ModuleResolutionKind { @@ -3720,7 +3714,7 @@ export const enum ScriptTarget { ES2020 = "ES2020", ES2021 = "ES2021", ES2022 = "ES2022", - ESNext = "ESNext" + ESNext = "ESNext", } export const enum ClassificationType { diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 114e3f33d3518..57a9d06c911fb 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -209,10 +209,10 @@ export class TextStorage { return !!this.fileSize ? this.fileSize : !!this.text // Check text before svc because its length is cheaper - ? this.text.length // Could be wrong if this.pendingReloadFromDisk - : !!this.svc - ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk - : this.getSnapshot().getLength(); // Should be strictly correct + ? this.text.length // Could be wrong if this.pendingReloadFromDisk + : !!this.svc + ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk + : this.getSnapshot().getLength(); // Should be strictly correct } public getSnapshot(): IScriptSnapshot { @@ -264,7 +264,7 @@ export class TextStorage { return { line: line + 1, offset: character + 1 }; } - private getFileTextAndSize(tempFileName?: string): { text: string, fileSize?: number } { + private getFileTextAndSize(tempFileName?: string): { text: string; fileSize?: number; } { let text: string; const fileName = tempFileName || this.info.fileName; const getText = () => text === undefined ? (text = this.host.readFile(fileName) || "") : text; @@ -329,7 +329,7 @@ export class TextStorage { if (svc) { return { getLineCount: () => svc.getLineCount(), - getLineText: line => svc.getAbsolutePositionAndLineText(line + 1).lineText! + getLineText: line => svc.getAbsolutePositionAndLineText(line + 1).lineText!, }; } const lineMap = this.getLineMap(); @@ -405,7 +405,8 @@ export class ScriptInfo { readonly scriptKind: ScriptKind, public readonly hasMixedContent: boolean, readonly path: Path, - initialVersion?: number) { + initialVersion?: number, + ) { this.isDynamic = isDynamicFileName(fileName); this.textStorage = new TextStorage(host, this, initialVersion); @@ -428,8 +429,10 @@ export class ScriptInfo { public open(newText: string | undefined) { this.textStorage.isOpen = true; - if (newText !== undefined && - this.textStorage.reload(newText)) { + if ( + newText !== undefined && + this.textStorage.reload(newText) + ) { // reload new contents only if the existing contents changed this.markContainingProjectsAsDirty(); } @@ -479,8 +482,12 @@ export class ScriptInfo { return this.realpath && this.realpath !== this.path; } - getFormatCodeSettings(): FormatCodeSettings | undefined { return this.formatSettings; } - getPreferences(): protocol.UserPreferences | undefined { return this.preferences; } + getFormatCodeSettings(): FormatCodeSettings | undefined { + return this.formatSettings; + } + getPreferences(): protocol.UserPreferences | undefined { + return this.preferences; + } attachToProject(project: Project): boolean { const isNew = !this.isAttached(project); @@ -497,10 +504,14 @@ export class ScriptInfo { isAttached(project: Project) { // unrolled for common cases switch (this.containingProjects.length) { - case 0: return false; - case 1: return this.containingProjects[0] === project; - case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; - default: return contains(this.containingProjects, project); + case 0: + return false; + case 1: + return this.containingProjects[0] === project; + case 2: + return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: + return contains(this.containingProjects, project); } } @@ -575,8 +586,10 @@ export class ScriptInfo { if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { // If we havent found default configuredProject and // its not the last one, find it and use that one if there - if (defaultConfiguredProject === undefined && - index !== this.containingProjects.length - 1) { + if ( + defaultConfiguredProject === undefined && + index !== this.containingProjects.length - 1 + ) { defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; } if (defaultConfiguredProject === project) return project; @@ -591,11 +604,13 @@ export class ScriptInfo { firstInferredProject = project; } } - return ensurePrimaryProjectKind(defaultConfiguredProject || - firstNonSourceOfProjectReferenceRedirect || - firstConfiguredProject || - firstExternalProject || - firstInferredProject); + return ensurePrimaryProjectKind( + defaultConfiguredProject || + firstNonSourceOfProjectReferenceRedirect || + firstConfiguredProject || + firstExternalProject || + firstInferredProject, + ); } } @@ -668,7 +683,8 @@ export class ScriptInfo { isContainedByBackgroundProject() { return some( this.containingProjects, - p => p.projectKind === ProjectKind.AutoImportProvider || p.projectKind === ProjectKind.Auxiliary); + p => p.projectKind === ProjectKind.AutoImportProvider || p.projectKind === ProjectKind.Auxiliary, + ); } /** diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index af5faff067112..28449179243cf 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -37,7 +37,7 @@ export const enum CharRangeSection { Entire, Mid, End, - PostEnd + PostEnd, } /** @internal */ @@ -45,15 +45,15 @@ export interface LineIndexWalker { goSubtree: boolean; done: boolean; leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void; - pre?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, - parent: LineNode, nodeType: CharRangeSection): void; - post?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, - parent: LineNode, nodeType: CharRangeSection): void; + pre?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): void; + post?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): void; } class EditWalker implements LineIndexWalker { goSubtree = true; - get done() { return false; } + get done() { + return false; + } readonly lineIndex = new LineIndex(); // path to start of range @@ -261,8 +261,7 @@ class TextChange { } getTextChangeRange() { - return createTextChangeRange(createTextSpan(this.pos, this.deleteLen), - this.insertedText ? this.insertedText.length : 0); + return createTextChangeRange(createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0); } } @@ -292,14 +291,18 @@ export class ScriptVersionCache { // REVIEW: can optimize by coalescing simple edits edit(pos: number, deleteLen: number, insertedText?: string) { this.changes.push(new TextChange(pos, deleteLen, insertedText)); - if (this.changes.length > ScriptVersionCache.changeNumberThreshold || + if ( + this.changes.length > ScriptVersionCache.changeNumberThreshold || deleteLen > ScriptVersionCache.changeLengthThreshold || - insertedText && insertedText.length > ScriptVersionCache.changeLengthThreshold) { + insertedText && insertedText.length > ScriptVersionCache.changeLengthThreshold + ) { this.getSnapshot(); } } - getSnapshot(): IScriptSnapshot { return this._getSnapshot(); } + getSnapshot(): IScriptSnapshot { + return this._getSnapshot(); + } private _getSnapshot(): LineIndexSnapshot { let snap = this.versions[this.currentVersionToIndex()]; @@ -418,7 +421,7 @@ export class LineIndex { return { line: oneBasedLine, offset: zeroBasedColumn + 1 }; } - private positionToColumnAndLineText(position: number): { zeroBasedColumn: number, lineText: string | undefined } { + private positionToColumnAndLineText(position: number): { zeroBasedColumn: number; lineText: string | undefined; } { return this.root.charOffsetToLineInfo(1, position); } @@ -462,7 +465,7 @@ export class LineIndex { done: false, leaf: (relativeStart: number, relativeLength: number, ll: LineLeaf) => { accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength)); - } + }, }); } return accum; @@ -483,7 +486,7 @@ export class LineIndex { if (!f(ll, relativeStart, relativeLength)) { this.done = true; } - } + }, }; this.walk(rangeStart, rangeEnd - rangeStart, walkFns); return !walkFns.done; @@ -680,7 +683,7 @@ export class LineNode implements LineCollection { // Input position is relative to the start of this node. // Output line number is absolute. - charOffsetToLineInfo(lineNumberAccumulator: number, relativePosition: number): { oneBasedLine: number, zeroBasedColumn: number, lineText: string | undefined } { + charOffsetToLineInfo(lineNumberAccumulator: number, relativePosition: number): { oneBasedLine: number; zeroBasedColumn: number; lineText: string | undefined; } { if (this.children.length === 0) { // Root node might have no children if this is an empty document. return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined }; @@ -715,7 +718,7 @@ export class LineNode implements LineCollection { * Output line number is relative to the child. * positionAccumulator will be an absolute position once relativeLineNumber reaches 0. */ - lineNumberToInfo(relativeOneBasedLine: number, positionAccumulator: number): { position: number, leaf: LineLeaf | undefined } { + lineNumberToInfo(relativeOneBasedLine: number, positionAccumulator: number): { position: number; leaf: LineLeaf | undefined; } { for (const child of this.children) { const childLineCount = child.lineCount(); if (childLineCount >= relativeOneBasedLine) { diff --git a/src/server/session.ts b/src/server/session.ts index ed3872c8f4038..0cf89ad746a23 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -193,7 +193,7 @@ export interface ServerCancellationToken extends HostCancellationToken { export const nullCancellationToken: ServerCancellationToken = { isCancellationRequested: () => false, setRequest: () => void 0, - resetRequest: () => void 0 + resetRequest: () => void 0, }; function hrTimeToMilliseconds(time: [number, number]): number { @@ -216,15 +216,16 @@ function isDeclarationFileInJSOnlyNonConfiguredProject(project: Project, file: N // We still want to check .js files in a JS-only inferred or external project (e.g. if the // file has '// @ts-check'). - if ((isInferredProject(project) || isExternalProject(project)) && - project.isJsOnlyProject()) { + if ( + (isInferredProject(project) || isExternalProject(project)) && + project.isJsOnlyProject() + ) { const scriptInfo = project.getScriptInfoForNormalizedPath(file); return scriptInfo && !scriptInfo.isJavaScript(); } return false; } - function dtsChangeCanAffectEmit(compilationSettings: CompilerOptions) { return getEmitDeclarations(compilationSettings) || !!compilationSettings.emitDecoratorMetadata; } @@ -249,18 +250,18 @@ function formatRelatedInformation(info: DiagnosticRelatedInformation): protocol. return { message: flattenDiagnosticMessageText(info.messageText, "\n"), category: diagnosticCategoryName(info), - code: info.code + code: info.code, }; } return { span: { start: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start!)), end: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start! + info.length!)), // TODO: GH#18217 - file: info.file.fileName + file: info.file.fileName, }, message: flattenDiagnosticMessageText(info.messageText, "\n"), category: diagnosticCategoryName(info), - code: info.code + code: info.code, }; } @@ -355,7 +356,7 @@ class MultistepOperation implements NextStep { private timerHandle: any; private immediateId: number | undefined; - constructor(private readonly operationHost: MultistepOperationHost) { } + constructor(private readonly operationHost: MultistepOperationHost) {} public startNew(action: (next: NextStep) => void) { this.complete(); @@ -375,19 +376,27 @@ class MultistepOperation implements NextStep { public immediate(actionType: string, action: () => void) { const requestId = this.requestId!; Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id"); - this.setImmediateId(this.operationHost.getServerHost().setImmediate(() => { - this.immediateId = undefined; - this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); - }, actionType)); + this.setImmediateId( + this.operationHost.getServerHost().setImmediate(() => { + this.immediateId = undefined; + this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); + }, actionType), + ); } public delay(actionType: string, ms: number, action: () => void) { const requestId = this.requestId!; Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id"); - this.setTimerHandle(this.operationHost.getServerHost().setTimeout(() => { - this.timerHandle = undefined; - this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); - }, ms, actionType)); + this.setTimerHandle( + this.operationHost.getServerHost().setTimeout( + () => { + this.timerHandle = undefined; + this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); + }, + ms, + actionType, + ), + ); } private executeAction(action: (next: NextStep) => void) { @@ -453,7 +462,7 @@ export function toEvent(eventName: string, body: object): protocol.Event { seq: 0, type: "event", event: eventName, - body + body, }; } @@ -487,7 +496,7 @@ interface ProjectNavigateToItems { } function createDocumentSpanSet(): Set { - return createSet(({textSpan}) => textSpan.start + 100003 * textSpan.length, documentSpansEqual); + return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, documentSpansEqual); } function getRenameLocationsWorker( @@ -496,7 +505,7 @@ function getRenameLocationsWorker( initialLocation: DocumentPosition, findInStrings: boolean, findInComments: boolean, - preferences: protocol.UserPreferences + preferences: protocol.UserPreferences, ): readonly RenameLocation[] { const perProjectResults = getPerProjectReferences( projects, @@ -634,7 +643,7 @@ function getReferencesWorker( ...referencedSymbol.definition, textSpan: createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length), // Why would the length be the same in the original? fileName: mappedDefinitionFile.fileName, - contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project) + contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project), }; let symbolToAddTo = find(results, o => documentSpansEqual(o.definition, definition)); @@ -713,12 +722,16 @@ function getPerProjectReferences( const defaultDefinition = getDefinitionLocation(defaultProject, initialLocation, isForRename); // Don't call these unless !!defaultDefinition - const getGeneratedDefinition = memoize(() => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition!.fileName) ? - defaultDefinition : - defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition!)); - const getSourceDefinition = memoize(() => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition!.fileName) ? - defaultDefinition : - defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition!)); + const getGeneratedDefinition = memoize(() => + defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition!.fileName) ? + defaultDefinition : + defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition!) + ); + const getSourceDefinition = memoize(() => + defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition!.fileName) ? + defaultDefinition : + defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition!) + ); // The keys of resultsMap allow us to check which projects have already been searched, but we also // maintain a set of strings because that's what `loadAncestorProjectTree` wants. @@ -810,11 +823,13 @@ function mapDefinitionInProject( definition: DocumentPosition, project: Project, getGeneratedDefinition: () => DocumentPosition | undefined, - getSourceDefinition: () => DocumentPosition | undefined + getSourceDefinition: () => DocumentPosition | undefined, ): DocumentPosition | undefined { // If the definition is actually from the project, definition is correct as is - if (project.containsFile(toNormalizedPath(definition.fileName)) && - !isLocationProjectReferenceRedirect(project, definition)) { + if ( + project.containsFile(toNormalizedPath(definition.fileName)) && + !isLocationProjectReferenceRedirect(project, definition) + ) { return definition; } const generatedDefinition = getGeneratedDefinition(); @@ -993,7 +1008,7 @@ export class Session implements EventSender { getServerHost: () => this.host, logError: (err, cmd) => this.logError(err, cmd), sendRequestCompletedEvent: requestId => this.sendRequestCompletedEvent(requestId), - isCancellationRequested: () => this.cancellationToken.isCancellationRequested() + isCancellationRequested: () => this.cancellationToken.isCancellationRequested(), }; this.errorCheck = new MultistepOperation(multistepOperationHost); const settings: ProjectServiceOptions = { @@ -1073,7 +1088,8 @@ export class Session implements EventSender { const { project, reason } = event.data; this.event( { projectName: project.getProjectName(), reason }, - ProjectLoadingStartEvent); + ProjectLoadingStartEvent, + ); break; case ProjectLoadingFinishEvent: const { project: finishProject } = event.data; @@ -1089,14 +1105,14 @@ export class Session implements EventSender { this.event({ triggerFile, configFile, - diagnostics: bakedDiags + diagnostics: bakedDiags, }, ConfigFileDiagEvent); break; case ProjectLanguageServiceStateEvent: { const eventName: protocol.ProjectLanguageServiceStateEventName = ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), - languageServiceEnabled: event.data.languageServiceEnabled + languageServiceEnabled: event.data.languageServiceEnabled, }, eventName); break; } @@ -1121,7 +1137,7 @@ export class Session implements EventSender { // Send project changed event this.event({ - openFiles + openFiles, }, ProjectsUpdatedInBackgroundEvent); } } @@ -1149,10 +1165,9 @@ export class Session implements EventSender { msg += `\n\nFile text of ${fileRequest.file}:${indent(text)}\n`; } } - catch { } // eslint-disable-line no-empty + catch {} // eslint-disable-line no-empty } - if (err.ProgramFiles) { msg += `\n\nProgram files: ${JSON.stringify(err.ProgramFiles)}\n`; msg += `\n\nProjects::\n`; @@ -1200,7 +1215,7 @@ export class Session implements EventSender { command: cmdName, request_seq: reqSeq, success, - performanceData: this.performanceData + performanceData: this.performanceData, }; if (success) { @@ -1212,7 +1227,7 @@ export class Session implements EventSender { } else if (typeof info === "object") { if ((info as WithMetadata<{}>).metadata) { - const { metadata: infoMetadata, ...body } = (info as WithMetadata<{}>); + const { metadata: infoMetadata, ...body } = info as WithMetadata<{}>; res.body = body; metadata = infoMetadata; } @@ -1370,13 +1385,13 @@ export class Session implements EventSender { return projectFileName === undefined ? undefined : this.projectService.findProject(projectFileName); } - private getConfigFileAndProject(args: protocol.FileRequestArgs): { configFile: NormalizedPath | undefined, project: Project | undefined } { + private getConfigFileAndProject(args: protocol.FileRequestArgs): { configFile: NormalizedPath | undefined; project: Project | undefined; } { const project = this.getProject(args.projectFileName); const file = toNormalizedPath(args.file); return { configFile: project && project.hasConfigFile(file) ? file : undefined, - project + project, }; } @@ -1385,13 +1400,13 @@ export class Session implements EventSender { const optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); const diagnosticsForConfigFile = filter( concatenate(projectErrors, optionsErrors), - diagnostic => !!diagnostic.file && diagnostic.file.fileName === configFile + diagnostic => !!diagnostic.file && diagnostic.file.fileName === configFile, ); return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : map( diagnosticsForConfigFile, - diagnostic => formatDiagnosticToProtocol(diagnostic, /*includeFileName*/ false) + diagnostic => formatDiagnosticToProtocol(diagnostic, /*includeFileName*/ false), ); } @@ -1407,7 +1422,7 @@ export class Session implements EventSender { endLocation: (d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start! + d.length!)))!, // TODO: GH#18217 reportsUnnecessary: d.reportsUnnecessary, reportsDeprecated: d.reportsDeprecated, - relatedInformation: map(d.relatedInformation, formatRelatedInformation) + relatedInformation: map(d.relatedInformation, formatRelatedInformation), })); } @@ -1419,30 +1434,35 @@ export class Session implements EventSender { return this.convertToDiagnosticsWithLinePosition( filter( project.getLanguageService().getCompilerOptionsDiagnostics(), - diagnostic => !diagnostic.file + diagnostic => !diagnostic.file, ), - /*scriptInfo*/ undefined + /*scriptInfo*/ undefined, ); } private convertToDiagnosticsWithLinePosition(diagnostics: readonly Diagnostic[], scriptInfo: ScriptInfo | undefined): protocol.DiagnosticWithLinePosition[] { - return diagnostics.map(d => ({ - message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), - start: d.start, - length: d.length, - category: diagnosticCategoryName(d), - code: d.code, - source: d.source, - startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start!), // TODO: GH#18217 - endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start! + d.length!), - reportsUnnecessary: d.reportsUnnecessary, - reportsDeprecated: d.reportsDeprecated, - relatedInformation: map(d.relatedInformation, formatRelatedInformation), - }) as protocol.DiagnosticWithLinePosition); + return diagnostics.map(d => + ({ + message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), + start: d.start, + length: d.length, + category: diagnosticCategoryName(d), + code: d.code, + source: d.source, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start!), // TODO: GH#18217 + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start! + d.length!), + reportsUnnecessary: d.reportsUnnecessary, + reportsDeprecated: d.reportsDeprecated, + relatedInformation: map(d.relatedInformation, formatRelatedInformation), + }) as protocol.DiagnosticWithLinePosition + ); } private getDiagnosticsWorker( - args: protocol.FileRequestArgs, isSemantic: boolean, selector: (project: Project, file: string) => readonly Diagnostic[], includeLinePosition: boolean + args: protocol.FileRequestArgs, + isSemantic: boolean, + selector: (project: Project, file: string) => readonly Diagnostic[], + includeLinePosition: boolean, ): readonly protocol.DiagnosticWithLinePosition[] | readonly protocol.Diagnostic[] { const { project, file } = this.getFileAndProject(args); if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { @@ -1487,7 +1507,7 @@ export class Session implements EventSender { if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) { return { definitions: emptyArray, - textSpan: undefined! // TODO: GH#18217 + textSpan: undefined!, // TODO: GH#18217 }; } @@ -1497,7 +1517,7 @@ export class Session implements EventSender { if (simplifiedResult) { return { definitions: this.mapDefinitionInfo(definitions, project), - textSpan: toProtocolTextSpan(textSpan, scriptInfo) + textSpan: toProtocolTextSpan(textSpan, scriptInfo), }; } @@ -1514,7 +1534,8 @@ export class Session implements EventSender { let definitions: readonly DefinitionInfo[] = this.mapDefinitionInfoLocations(unmappedDefinitions || emptyArray, project).slice(); const needsJsResolution = this.projectService.serverMode === LanguageServiceMode.Semantic && ( !some(definitions, d => toNormalizedPath(d.fileName) !== file && !d.isAmbient) || - some(definitions, d => !!d.failedAliasResolution)); + some(definitions, d => !!d.failedAliasResolution) + ); if (needsJsResolution) { const definitionSet = createSet(d => d.textSpan.start, documentSpansEqual); @@ -1573,11 +1594,13 @@ export class Session implements EventSender { packageJson, { moduleResolution: ModuleResolutionKind.Node10 }, project, - project.getModuleResolutionCache()); + project.getModuleResolutionCache(), + ); // This substring is correct only because we checked for a single `/node_modules/` at the top. const packageNamePathPart = fileName.substring( nodeModulesPathParts.topLevelPackageNameIndex + 1, - nodeModulesPathParts.packageRootIndex); + nodeModulesPathParts.packageRootIndex, + ); const packageName = getPackageNameFromTypesPackageName(unmangleScopedPackageName(packageNamePathPart)); const path = project.toPath(fileName); if (entrypoints && some(entrypoints, e => project.toPath(e) === path)) { @@ -1599,7 +1622,7 @@ export class Session implements EventSender { // In 'foo.bar./**/baz', if we got not results on 'baz', see if we can get an ambient definition // for 'bar' or 'foo' (in that order) so we can search for declarations of 'baz' later. - function getAmbientCandidatesByClimbingAccessChain(): readonly { name: string, fileName: string }[] { + function getAmbientCandidatesByClimbingAccessChain(): readonly { name: string; fileName: string; }[] { const ls = project.getLanguageService(); const program = ls.getProgram()!; const initialNode = getTouchingPropertyName(program.getSourceFile(file)!, position); @@ -1610,7 +1633,7 @@ export class Session implements EventSender { ?.filter(d => toNormalizedPath(d.fileName) !== file && d.isAmbient) .map(d => ({ fileName: d.fileName, - name: getTextOfIdentifierOrLiteral(initialNode) + name: getTextOfIdentifierOrLiteral(initialNode), })); if (some(candidates)) { return candidates; @@ -1669,7 +1692,7 @@ export class Session implements EventSender { ...result, diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(result.diagnostics) : - result.diagnostics.map(d => formatDiagnosticToProtocol(d, /*includeFileName*/ true)) + result.diagnostics.map(d => formatDiagnosticToProtocol(d, /*includeFileName*/ true)), } : result; } @@ -1677,7 +1700,7 @@ export class Session implements EventSender { private mapJSDocTagInfo(tags: JSDocTagInfo[] | undefined, project: Project, richResponse: boolean): protocol.JSDocTagInfo[] { return tags ? tags.map(tag => ({ ...tag, - text: richResponse ? this.mapDisplayParts(tag.text, project) : tag.text?.map(part => part.text).join("") + text: richResponse ? this.mapDisplayParts(tag.text, project) : tag.text?.map(part => part.text).join(""), })) : []; } @@ -1685,10 +1708,12 @@ export class Session implements EventSender { if (!parts) { return []; } - return parts.map(part => part.kind !== "linkName" ? part : { - ...part, - target: this.toFileSpan((part as JSDocLinkDisplayPart).target.fileName, (part as JSDocLinkDisplayPart).target.textSpan, project), - }); + return parts.map(part => + part.kind !== "linkName" ? part : { + ...part, + target: this.toFileSpan((part as JSDocLinkDisplayPart).target.fileName, (part as JSDocLinkDisplayPart).target.textSpan, project), + } + ); } private mapSignatureHelpItems(items: SignatureHelpItem[], project: Project, richResponse: boolean): protocol.SignatureHelpItem[] { @@ -1710,7 +1735,7 @@ export class Session implements EventSender { * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a * set of additional fields, and does the reverse for VS (store the .d.ts location where * it used to be and stores the .ts location in the additional fields). - */ + */ private static mapToOriginalLocation(def: T): T { if (def.originalFileName) { Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is"); @@ -1721,7 +1746,7 @@ export class Session implements EventSender { targetFileName: def.fileName, targetTextSpan: def.textSpan, contextSpan: def.originalContextSpan, - targetContextSpan: def.contextSpan + targetContextSpan: def.contextSpan, }; } return def; @@ -1735,7 +1760,7 @@ export class Session implements EventSender { return { file: fileName, start: { line: start.line + 1, offset: start.character + 1 }, - end: { line: end.line + 1, offset: end.character + 1 } + end: { line: end.line + 1, offset: end.character + 1 }, }; } @@ -1833,8 +1858,8 @@ export class Session implements EventSender { file: fileName, highlightSpans: highlightSpans.map(({ textSpan, kind, contextSpan }) => ({ ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), - kind - })) + kind, + })), }; }); } @@ -1855,8 +1880,8 @@ export class Session implements EventSender { span: span && { start: scriptInfo.positionToLineOffset(span.start), end: scriptInfo.positionToLineOffset(span.start + span.length), - file: file! - } + file: file!, + }, })), }; }); @@ -1876,7 +1901,7 @@ export class Session implements EventSender { const projectInfo = { configFileName: project.getProjectName(), languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames(/*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles) : undefined + fileNames: needFileNameList ? project.getFileNames(/*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles) : undefined, }; return projectInfo; } @@ -1943,7 +1968,9 @@ export class Session implements EventSender { const defaultProject = this.getDefaultProject(args); const preferences = this.getPreferences(file); const renameInfo: protocol.RenameInfo = this.mapRenameInfo( - defaultProject.getLanguageService().getRenameInfo(file, position, preferences), Debug.checkDefined(this.projectService.getScriptInfo(file))); + defaultProject.getLanguageService().getRenameInfo(file, position, preferences), + Debug.checkDefined(this.projectService.getScriptInfo(file)), + ); if (!renameInfo.canRename) return simplifiedResult ? { info: renameInfo, locs: [] } : []; @@ -1963,7 +1990,8 @@ export class Session implements EventSender { if (info.canRename) { const { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan } = info; return identity( - { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) }); + { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) }, + ); } else { return info; @@ -2034,7 +2062,7 @@ export class Session implements EventSender { const refs = references.map(entry => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); return { refs, - symbolName: `"${args.file}"` + symbolName: `"${args.file}"`, }; } @@ -2046,11 +2074,11 @@ export class Session implements EventSender { this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath); } - private getPosition(args: protocol.Location & { position?: number }, scriptInfo: ScriptInfo): number { + private getPosition(args: protocol.Location & { position?: number; }, scriptInfo: ScriptInfo): number { return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); } - private getPositionInFile(args: protocol.Location & { position?: number }, file: NormalizedPath): number { + private getPositionInFile(args: protocol.Location & { position?: number; }, file: NormalizedPath): number { const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file)!; return this.getPosition(args, scriptInfo); } @@ -2063,11 +2091,11 @@ export class Session implements EventSender { const { file, project } = this.getFileAndProject(args); return { file, - languageService: project.getLanguageService(/*ensureSynchronized*/ false) + languageService: project.getLanguageService(/*ensureSynchronized*/ false), }; } - private getFileAndProjectWorker(uncheckedFileName: string, projectFileName: string | undefined): { file: NormalizedPath, project: Project } { + private getFileAndProjectWorker(uncheckedFileName: string, projectFileName: string | undefined): { file: NormalizedPath; project: Project; } { const file = toNormalizedPath(uncheckedFileName); const project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file); return { file, project }; @@ -2083,7 +2111,7 @@ export class Session implements EventSender { hintSpan: toProtocolTextSpan(s.hintSpan, scriptInfo), bannerText: s.bannerText, autoCollapse: s.autoCollapse, - kind: s.kind + kind: s.kind, })); } else { @@ -2159,7 +2187,7 @@ export class Session implements EventSender { else { return useDisplayParts ? quickInfo : { ...quickInfo, - tags: this.mapJSDocTagInfo(quickInfo.tags, project, /*richResponse*/ false) as JSDocTagInfo[] + tags: this.mapJSDocTagInfo(quickInfo.tags, project, /*richResponse*/ false) as JSDocTagInfo[], }; } } @@ -2203,8 +2231,7 @@ export class Session implements EventSender { const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file)!; const position = scriptInfo.lineOffsetToPosition(args.line, args.offset); const formatOptions = this.getFormatOptions(file); - const edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, - formatOptions); + const edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); // Check whether we should auto-indent. This will be when // the position is on a line containing only whitespace. // This should leave the edits returned from @@ -2233,7 +2260,7 @@ export class Session implements EventSender { const firstNoWhiteSpacePosition = absolutePosition + i; edits.push({ span: createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition), - newText: formatting.getIndentationString(preferredIndent, formatOptions) + newText: formatting.getIndentationString(preferredIndent, formatOptions), }); } } @@ -2243,11 +2270,11 @@ export class Session implements EventSender { return undefined; } - return edits.map((edit) => { + return edits.map(edit => { return { start: scriptInfo.positionToLineOffset(edit.span.start), end: scriptInfo.positionToLineOffset(textSpanEnd(edit.span)), - newText: edit.newText ? edit.newText : "" + newText: edit.newText ? edit.newText : "", }; }); } @@ -2292,7 +2319,8 @@ export class Session implements EventSender { isRecommended, isPackageJsonImport, isImportStatementCompletion, - data } = entry; + data, + } = entry; const convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. return { @@ -2311,7 +2339,7 @@ export class Session implements EventSender { isRecommended, isPackageJsonImport, isImportStatementCompletion, - data + data, }; } }); @@ -2376,9 +2404,9 @@ export class Session implements EventSender { return { projectFileName: project.getProjectName(), fileNames: project.getCompileOnSaveAffectedFileList(info), - projectUsesOutFile: !!outFile(compilationSettings) + projectUsesOutFile: !!outFile(compilationSettings), }; - } + }, ); } @@ -2397,7 +2425,7 @@ export class Session implements EventSender { emitSkipped, diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) : - diagnostics.map(d => formatDiagnosticToProtocol(d, /*includeFileName*/ true)) + diagnostics.map(d => formatDiagnosticToProtocol(d, /*includeFileName*/ true)), } : !emitSkipped; } @@ -2414,7 +2442,7 @@ export class Session implements EventSender { ...helpItems, applicableSpan: { start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(span.start + span.length) + end: scriptInfo.positionToLineOffset(span.start + span.length), }, items: this.mapSignatureHelpItems(helpItems.items, project, useDisplayParts), }; @@ -2425,7 +2453,7 @@ export class Session implements EventSender { else { return { ...helpItems, - items: helpItems.items.map(item => ({ ...item, tags: this.mapJSDocTagInfo(item.tags, project, /*richResponse*/ false) as JSDocTagInfo[] })) + items: helpItems.items.map(item => ({ ...item, tags: this.mapJSDocTagInfo(item.tags, project, /*richResponse*/ false) as JSDocTagInfo[] })), }; } } @@ -2455,10 +2483,13 @@ export class Session implements EventSender { const end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { this.changeSeq++; - this.projectService.applyChangesToFile(scriptInfo, singleIterator({ - span: { start, length: end - start }, - newText: args.insertString! // TODO: GH#18217 - })); + this.projectService.applyChangesToFile( + scriptInfo, + singleIterator({ + span: { start, length: end - start }, + newText: args.insertString!, // TODO: GH#18217 + }), + ); } } @@ -2497,7 +2528,7 @@ export class Session implements EventSender { kindModifiers: item.kindModifiers, spans: item.spans.map(span => toProtocolTextSpan(span, scriptInfo)), childItems: this.mapLocationNavigationBarItems(item.childItems, scriptInfo), - indent: item.indent + indent: item.indent, })); } @@ -2507,8 +2538,8 @@ export class Session implements EventSender { return !items ? undefined : simplifiedResult - ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)!) - : items; + ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)!) + : items; } private toLocationNavigationTree(tree: NavigationTree, scriptInfo: ScriptInfo): protocol.NavigationTree { @@ -2518,7 +2549,7 @@ export class Session implements EventSender { kindModifiers: tree.kindModifiers, spans: tree.spans.map(span => toProtocolTextSpan(span, scriptInfo)), nameSpan: tree.nameSpan && toProtocolTextSpan(tree.nameSpan, scriptInfo), - childItems: map(tree.childItems, item => this.toLocationNavigationTree(item, scriptInfo)) + childItems: map(tree.childItems, item => this.toLocationNavigationTree(item, scriptInfo)), }; } @@ -2528,8 +2559,8 @@ export class Session implements EventSender { return !tree ? undefined : simplifiedResult - ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)!) - : tree; + ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)!) + : tree; } private getNavigateToItems(args: protocol.NavtoRequestArgs, simplifiedResult: boolean): readonly protocol.NavtoItem[] | readonly NavigateToItem[] { @@ -2538,29 +2569,30 @@ export class Session implements EventSender { flatMap(full, ({ navigateToItems }) => navigateToItems) : flatMap( full, - ({ project, navigateToItems }) => navigateToItems.map(navItem => { - const scriptInfo = project.getScriptInfo(navItem.fileName)!; - const bakedItem: protocol.NavtoItem = { - name: navItem.name, - kind: navItem.kind, - kindModifiers: navItem.kindModifiers, - isCaseSensitive: navItem.isCaseSensitive, - matchKind: navItem.matchKind, - file: navItem.fileName, - start: scriptInfo.positionToLineOffset(navItem.textSpan.start), - end: scriptInfo.positionToLineOffset(textSpanEnd(navItem.textSpan)) - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }) + ({ project, navigateToItems }) => + navigateToItems.map(navItem => { + const scriptInfo = project.getScriptInfo(navItem.fileName)!; + const bakedItem: protocol.NavtoItem = { + name: navItem.name, + kind: navItem.kind, + kindModifiers: navItem.kindModifiers, + isCaseSensitive: navItem.isCaseSensitive, + matchKind: navItem.matchKind, + file: navItem.fileName, + start: scriptInfo.positionToLineOffset(navItem.textSpan.start), + end: scriptInfo.positionToLineOffset(textSpanEnd(navItem.textSpan)), + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }), ); } @@ -2705,12 +2737,12 @@ export class Session implements EventSender { args.refactor, args.action, this.getPreferences(file), - args.interactiveRefactorArguments + args.interactiveRefactorArguments, ); if (result === undefined) { return { - edits: [] + edits: [], }; } @@ -2731,7 +2763,7 @@ export class Session implements EventSender { return result; } - private getMoveToRefactoringFileSuggestions(args: protocol.GetMoveToRefactoringFileSuggestionsRequestArgs): { newFileName: string, files: string[] }{ + private getMoveToRefactoringFileSuggestions(args: protocol.GetMoveToRefactoringFileSuggestionsRequestArgs): { newFileName: string; files: string[]; } { const { file, project } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file)!; return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); @@ -2747,7 +2779,7 @@ export class Session implements EventSender { type: "file", }, this.getFormatOptions(file), - this.getPreferences(file) + this.getPreferences(file), ); if (simplifiedResult) { return this.mapTextChangesToCodeEdits(changes); @@ -2763,7 +2795,6 @@ export class Session implements EventSender { const formatOptions = this.getHostFormatOptions(); const preferences = this.getHostPreferences(); - const seenFiles = new Set(); const textChanges: FileTextChanges[] = []; // TODO (https://github.com/microsoft/TypeScript/issues/47839) @@ -2797,15 +2828,16 @@ export class Session implements EventSender { try { codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); } - catch(e) { + catch (e) { const ls = project.getLanguageService(); const existingDiagCodes = [ ...ls.getSyntacticDiagnostics(file), ...ls.getSemanticDiagnostics(file), - ...ls.getSuggestionDiagnostics(file) + ...ls.getSuggestionDiagnostics(file), ].map(d => decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start!, d.length!) - && d.code); + && d.code + ); const badCode = args.errorCodes.find(c => !existingDiagCodes.includes(c)); if (badCode !== undefined) { e.message = `BADCLIENT: Bad error code, ${badCode} not found in range ${startPosition}..${endPosition} (found: ${existingDiagCodes.join(", ")}); could have caused this error:\n${e.message}`; @@ -2832,8 +2864,9 @@ export class Session implements EventSender { for (const command of toArray(commands)) { const { file, project } = this.getFileAndProject(command); project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then( - _result => { /* TODO: GH#20447 report success message? */ }, - _error => { /* TODO: GH#20447 report errors */ }); + _result => {/* TODO: GH#20447 report success message? */}, + _error => {/* TODO: GH#20447 report errors */}, + ); } return {}; } @@ -2889,7 +2922,7 @@ export class Session implements EventSender { return { start: scriptInfo.positionToLineOffset(change.span.start), end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), - newText: change.newText ? change.newText : "" + newText: change.newText ? change.newText : "", }; } @@ -2902,8 +2935,8 @@ export class Session implements EventSender { return !spans ? undefined : simplifiedResult - ? spans.map(span => toProtocolTextSpan(span, scriptInfo)) - : spans; + ? spans.map(span => toProtocolTextSpan(span, scriptInfo)) + : spans; } private getDiagnosticsForProject(next: NextStep, delay: number, fileName: string): void { @@ -3065,7 +3098,7 @@ export class Session implements EventSender { file: item.file, containerName: item.containerName, span: toProtocolTextSpan(item.span, scriptInfo), - selectionSpan: toProtocolTextSpan(item.selectionSpan, scriptInfo) + selectionSpan: toProtocolTextSpan(item.selectionSpan, scriptInfo), }; } @@ -3073,14 +3106,14 @@ export class Session implements EventSender { const scriptInfo = this.getScriptInfoFromProjectService(incomingCall.from.file); return { from: this.toProtocolCallHierarchyItem(incomingCall.from), - fromSpans: incomingCall.fromSpans.map(fromSpan => toProtocolTextSpan(fromSpan, scriptInfo)) + fromSpans: incomingCall.fromSpans.map(fromSpan => toProtocolTextSpan(fromSpan, scriptInfo)), }; } private toProtocolCallHierarchyOutgoingCall(outgoingCall: CallHierarchyOutgoingCall, scriptInfo: ScriptInfo): protocol.CallHierarchyOutgoingCall { return { to: this.toProtocolCallHierarchyItem(outgoingCall.to), - fromSpans: outgoingCall.fromSpans.map(fromSpan => toProtocolTextSpan(fromSpan, scriptInfo)) + fromSpans: outgoingCall.fromSpans.map(fromSpan => toProtocolTextSpan(fromSpan, scriptInfo)), }; } @@ -3114,7 +3147,7 @@ export class Session implements EventSender { return normalizePath(name); } - exit() { /*overridden*/ } + exit() {/*overridden*/} private notRequired(): HandlerResponse { return { responseRequired: false }; @@ -3157,7 +3190,7 @@ export class Session implements EventSender { info: p.info, changes: p.changes, files: p.files, - projectErrors: this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ undefined) + projectErrors: this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ undefined), }; }); return this.requiredResponse(converted); @@ -3169,7 +3202,7 @@ export class Session implements EventSender { fileName: file.file, content: file.fileContent, scriptKind: file.scriptKindName, - projectRootPath: file.projectRootPath + projectRootPath: file.projectRootPath, })), request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, file => ({ fileName: file.fileName, @@ -3178,9 +3211,9 @@ export class Session implements EventSender { const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset); const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset); return start >= 0 ? { span: { start, length: end - start }, newText: change.newText } : undefined; - }) + }), })), - request.arguments.closedFiles + request.arguments.closedFiles, ); return this.requiredResponse(/*response*/ true); }, @@ -3191,9 +3224,9 @@ export class Session implements EventSender { request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, file => ({ fileName: file.fileName, // apply changes in reverse order - changes: arrayReverseIterator(file.changes) + changes: arrayReverseIterator(file.changes), })), - request.arguments.closedFiles + request.arguments.closedFiles, ); // TODO: report errors return this.requiredResponse(/*response*/ true); @@ -3249,7 +3282,8 @@ export class Session implements EventSender { toNormalizedPath(request.arguments.file), request.arguments.fileContent, convertScriptKindName(request.arguments.scriptKindName!), // TODO: GH#18217 - request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : undefined); + request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : undefined, + ); return this.notRequired(); }, [protocol.CommandTypes.Quickinfo]: (request: protocol.QuickInfoRequest) => { @@ -3521,7 +3555,7 @@ export class Session implements EventSender { }, [protocol.CommandTypes.ProvideInlayHints]: (request: protocol.InlayHintsRequest) => { return this.requiredResponse(this.provideInlayHints(request.arguments)); - } + }, })); public addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse) { @@ -3634,7 +3668,8 @@ export class Session implements EventSender { request ? request.command : protocol.CommandTypes.Unknown, request ? request.seq : 0, /*success*/ false, - "Error processing request. " + (err as StackTraceError).message + "\n" + (err as StackTraceError).stack); + "Error processing request. " + (err as StackTraceError).message + "\n" + (err as StackTraceError).stack, + ); } } @@ -3671,7 +3706,7 @@ interface FileAndProject { function toProtocolTextSpan(textSpan: TextSpan, scriptInfo: ScriptInfo): protocol.TextSpan { return { start: scriptInfo.positionToLineOffset(textSpan.start), - end: scriptInfo.positionToLineOffset(textSpanEnd(textSpan)) + end: scriptInfo.positionToLineOffset(textSpanEnd(textSpan)), }; } @@ -3693,13 +3728,13 @@ function positionToLineOffset(info: ScriptInfoOrConfig, position: number): proto function convertLinkedEditInfoToRanges(linkedEdit: LinkedEditingInfo, scriptInfo: ScriptInfo): protocol.LinkedEditingRangesBody { const ranges = linkedEdit.ranges.map( - r => { - return { - start: scriptInfo.positionToLineOffset(r.start), - end: scriptInfo.positionToLineOffset(r.start + r.length), - }; - } - ); + r => { + return { + start: scriptInfo.positionToLineOffset(r.start), + end: scriptInfo.positionToLineOffset(r.start + r.length), + }; + }, + ); if (!linkedEdit.wordPattern) return { ranges }; return { ranges, wordPattern: linkedEdit.wordPattern }; } @@ -3720,7 +3755,8 @@ export interface HandlerResponse { responseRequired?: boolean; } -/** @internal */ // Exported only for tests +/** @internal */ +// Exported only for tests export function getLocationInNewDocument(oldText: string, renameFilename: string, renameLocation: number, edits: readonly FileTextChanges[]): protocol.Location { const newText = applyEdits(oldText, renameFilename, edits); const { line, character } = computeLineAndCharacterOfPosition(computeLineStarts(newText), renameLocation); @@ -3751,7 +3787,7 @@ function referenceEntryToReferencesResponseItem(projectService: ProjectService, ...span, lineText, isWriteAccess, - isDefinition + isDefinition, }; } @@ -3762,8 +3798,8 @@ function getLineText(scriptInfo: ScriptInfo, span: protocol.TextSpanWithContext) function isCompletionEntryData(data: any): data is CompletionEntryData { return data === undefined || data && typeof data === "object" - && typeof data.exportName === "string" - && (data.fileName === undefined || typeof data.fileName === "string") - && (data.ambientModuleName === undefined || typeof data.ambientModuleName === "string" - && (data.isPackageJsonImport === undefined || typeof data.isPackageJsonImport === "boolean")); + && typeof data.exportName === "string" + && (data.fileName === undefined || typeof data.fileName === "string") + && (data.ambientModuleName === undefined || typeof data.ambientModuleName === "string" + && (data.isPackageJsonImport === undefined || typeof data.isPackageJsonImport === "boolean")); } diff --git a/src/server/types.ts b/src/server/types.ts index 8e1c38f9a42a3..4a6aa56f7fb46 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -12,7 +12,7 @@ export interface CompressedData { data: any; } -export type ModuleImportResult = { module: {}, error: undefined } | { module: undefined, error: { stack?: string, message?: string } }; +export type ModuleImportResult = { module: {}; error: undefined; } | { module: undefined; error: { stack?: string; message?: string; }; }; /** @deprecated Use {@link ModuleImportResult} instead. */ export type RequireResult = ModuleImportResult; diff --git a/src/server/typingsCache.ts b/src/server/typingsCache.ts index 42c91be6047d1..6f905fce17bbf 100644 --- a/src/server/typingsCache.ts +++ b/src/server/typingsCache.ts @@ -41,7 +41,7 @@ export const nullTypingsInstaller: ITypingsInstaller = { enqueueInstallTypingsRequest: noop, attach: noop, onProjectClosed: noop, - globalTypingsCacheLocation: undefined! // TODO: GH#18217 + globalTypingsCacheLocation: undefined!, // TODO: GH#18217 }; interface TypingsCacheEntry { @@ -123,11 +123,13 @@ export class TypingsCache { } const entry = this.perProjectCache.get(project.getProjectName()); - if (forceRefresh || + if ( + forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || - unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { + unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports) + ) { // Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options. // instead it acts as a placeholder to prevent issuing multiple requests this.perProjectCache.set(project.getProjectName(), { @@ -135,7 +137,7 @@ export class TypingsCache { typeAcquisition, typings: entry ? entry.typings : emptyArray, unresolvedImports, - poisoned: true + poisoned: true, }); // something has been changed, issue a request to update typings this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); @@ -149,7 +151,7 @@ export class TypingsCache { typeAcquisition, typings, unresolvedImports, - poisoned: false + poisoned: false, }); return !typeAcquisition || !typeAcquisition.enable ? emptyArray : typings; } diff --git a/src/server/utilitiesPublic.ts b/src/server/utilitiesPublic.ts index b6b6b8d11f7bf..ac8e0f3c131c3 100644 --- a/src/server/utilitiesPublic.ts +++ b/src/server/utilitiesPublic.ts @@ -16,7 +16,7 @@ export enum LogLevel { terse, normal, requestTime, - verbose + verbose, } export const emptyArray: SortedReadonlyArray = createSortedArray(); @@ -50,7 +50,7 @@ export function createInstallTypingsRequest(project: Project, typeAcquisition: T unresolvedImports, projectRootPath: project.getCurrentDirectory() as Path, cachePath, - kind: "discover" + kind: "discover", }; } @@ -66,7 +66,7 @@ export namespace Errors { } } -export type NormalizedPath = string & { __normalizedPathTag: any }; +export type NormalizedPath = string & { __normalizedPathTag: any; }; export function toNormalizedPath(fileName: string): NormalizedPath { return normalizePath(fileName) as NormalizedPath; @@ -102,7 +102,7 @@ export function createNormalizedPathMap(): NormalizedPathMap { }, remove(path) { map.delete(path); - } + }, }; } diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index f06f85142b862..8963a5dcf0d73 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -346,11 +346,13 @@ export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: num // Set breakpoint on identifier element of destructuring pattern // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern - if ((node.kind === SyntaxKind.Identifier || - node.kind === SyntaxKind.SpreadElement || - node.kind === SyntaxKind.PropertyAssignment || - node.kind === SyntaxKind.ShorthandPropertyAssignment) && - isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { + if ( + (node.kind === SyntaxKind.Identifier || + node.kind === SyntaxKind.SpreadElement || + node.kind === SyntaxKind.PropertyAssignment || + node.kind === SyntaxKind.ShorthandPropertyAssignment) && + isArrayLiteralOrObjectLiteralDestructuringPattern(parent) + ) { return textSpan(node); } @@ -362,7 +364,8 @@ export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: num // {a, b, c} = expression if (isArrayLiteralOrObjectLiteralDestructuringPattern(left)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern( - left as ArrayLiteralExpression | ObjectLiteralExpression); + left as ArrayLiteralExpression | ObjectLiteralExpression, + ); } if (operatorToken.kind === SyntaxKind.EqualsToken && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { @@ -411,8 +414,10 @@ export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: num switch (node.parent.kind) { case SyntaxKind.PropertyAssignment: // If this is name of property assignment, set breakpoint in the initializer - if ((node.parent as PropertyAssignment).name === node && - !isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { + if ( + (node.parent as PropertyAssignment).name === node && + !isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent) + ) { return spanInNode((node.parent as PropertyAssignment).initializer); } break; @@ -476,14 +481,18 @@ export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: num // Breakpoint is possible in variableDeclaration only if there is initialization // or its declaration from 'for of' - if ((hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer) || + if ( + (hasOnlyExpressionInitializer(variableDeclaration) && variableDeclaration.initializer) || hasSyntacticModifier(variableDeclaration, ModifierFlags.Export) || - parent.parent.kind === SyntaxKind.ForOfStatement) { + parent.parent.kind === SyntaxKind.ForOfStatement + ) { return textSpanFromVariableDeclaration(variableDeclaration); } - if (isVariableDeclarationList(variableDeclaration.parent) && - variableDeclaration.parent.declarations[0] !== variableDeclaration) { + if ( + isVariableDeclarationList(variableDeclaration.parent) && + variableDeclaration.parent.declarations[0] !== variableDeclaration + ) { // If we cannot set breakpoint on this declaration, set it on previous one // Because the variable declaration may be binding pattern and // we would like to set breakpoint in last binding element if that's the case, @@ -603,8 +612,7 @@ export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: num function spanInBindingPattern(bindingPattern: BindingPattern): TextSpan | undefined { // Set breakpoint in first binding element - const firstBindingElement = forEach(bindingPattern.elements, - element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined); + const firstBindingElement = forEach(bindingPattern.elements, element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined); if (firstBindingElement) { return spanInNode(firstBindingElement); @@ -623,8 +631,7 @@ export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: num Debug.assert(node.kind !== SyntaxKind.ArrayBindingPattern && node.kind !== SyntaxKind.ObjectBindingPattern); const elements: NodeArray = node.kind === SyntaxKind.ArrayLiteralExpression ? node.elements : node.properties; - const firstBindingElement = forEach(elements, - element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined); + const firstBindingElement = forEach(elements, element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined); if (firstBindingElement) { return spanInNode(firstBindingElement); @@ -725,9 +732,11 @@ export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: num } function spanInOpenParenToken(node: Node): TextSpan | undefined { - if (node.parent.kind === SyntaxKind.DoStatement || // Go to while keyword and do action instead + if ( + node.parent.kind === SyntaxKind.DoStatement || // Go to while keyword and do action instead node.parent.kind === SyntaxKind.CallExpression || - node.parent.kind === SyntaxKind.NewExpression) { + node.parent.kind === SyntaxKind.NewExpression + ) { return spanInPreviousNode(node); } @@ -767,9 +776,11 @@ export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: num function spanInColonToken(node: Node): TextSpan | undefined { // Is this : specifying return annotation of the function declaration - if (isFunctionLike(node.parent) || + if ( + isFunctionLike(node.parent) || node.parent.kind === SyntaxKind.PropertyAssignment || - node.parent.kind === SyntaxKind.Parameter) { + node.parent.kind === SyntaxKind.Parameter + ) { return spanInPreviousNode(node); } diff --git a/src/services/callHierarchy.ts b/src/services/callHierarchy.ts index a2d32e6da717f..aa8373081f984 100644 --- a/src/services/callHierarchy.ts +++ b/src/services/callHierarchy.ts @@ -108,9 +108,8 @@ import { /** @internal */ export type NamedExpression = - | ClassExpression & { name: Identifier } - | FunctionExpression & { name: Identifier } - ; + | ClassExpression & { name: Identifier; } + | FunctionExpression & { name: Identifier; }; /** Indictates whether a node is named function or class expression. */ function isNamedExpression(node: Node): node is NamedExpression { @@ -119,10 +118,9 @@ function isNamedExpression(node: Node): node is NamedExpression { /** @internal */ export type ConstNamedExpression = - | ClassExpression & { name: undefined, parent: VariableDeclaration & { name: Identifier } } - | FunctionExpression & { name: undefined, parent: VariableDeclaration & { name: Identifier } } - | ArrowFunction & { name: undefined, parent: VariableDeclaration & { name: Identifier } } - ; + | ClassExpression & { name: undefined; parent: VariableDeclaration & { name: Identifier; }; } + | FunctionExpression & { name: undefined; parent: VariableDeclaration & { name: Identifier; }; } + | ArrowFunction & { name: undefined; parent: VariableDeclaration & { name: Identifier; }; }; /** Indicates whether a node is a function, arrow, or class expression assigned to a constant variable. */ function isConstNamedExpression(node: Node): node is ConstNamedExpression { @@ -136,7 +134,7 @@ function isConstNamedExpression(node: Node): node is ConstNamedExpression { /** @internal */ export type CallHierarchyDeclaration = | SourceFile - | ModuleDeclaration & { name: Identifier } + | ModuleDeclaration & { name: Identifier; } | FunctionDeclaration | ClassDeclaration | ClassStaticBlockDeclaration @@ -144,8 +142,7 @@ export type CallHierarchyDeclaration = | GetAccessorDeclaration | SetAccessorDeclaration | NamedExpression - | ConstNamedExpression - ; + | ConstNamedExpression; /** * Indicates whether a node could possibly be a call hierarchy declaration. @@ -204,7 +201,7 @@ function getSymbolOfCallHierarchyDeclaration(typeChecker: TypeChecker, node: Exc } /** Gets the text and range for the name of a call hierarchy declaration. */ -function getCallHierarchyItemName(program: Program, node: CallHierarchyDeclaration): { text: string, pos: number, end: number } { +function getCallHierarchyItemName(program: Program, node: CallHierarchyDeclaration): { text: string; pos: number; end: number; } { if (isSourceFile(node)) { return { text: node.fileName, pos: 0, end: 0 }; } @@ -229,11 +226,10 @@ function getCallHierarchyItemName(program: Program, node: CallHierarchyDeclarati const declName = isConstNamedExpression(node) ? node.parent.name : Debug.checkDefined(getNameOfDeclaration(node), "Expected call hierarchy item to have a name"); - let text = - isIdentifier(declName) ? idText(declName) : + let text = isIdentifier(declName) ? idText(declName) : isStringOrNumericLiteralLike(declName) ? declName.text : isComputedPropertyName(declName) ? - isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text : + isStringOrNumericLiteralLike(declName.expression) ? declName.expression.text : undefined : undefined; if (text === undefined) { @@ -432,12 +428,14 @@ interface CallSite { function convertEntryToCallSite(entry: FindAllReferences.Entry): CallSite | undefined { if (entry.kind === FindAllReferences.EntryKind.Node) { const { node } = entry; - if (isCallOrNewExpressionTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) + if ( + isCallOrNewExpressionTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isTaggedTemplateTag(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isDecoratorTarget(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isJsxOpeningLikeElementTagName(node, /*includeElementAccess*/ true, /*skipPastOuterExpressions*/ true) || isRightSideOfPropertyAccess(node) - || isArgumentExpressionOfElementAccess(node)) { + || isArgumentExpressionOfElementAccess(node) + ) { const sourceFile = node.getSourceFile(); const ancestor = findAncestor(node, isValidCallHierarchyDeclaration) || sourceFile; return { declaration: ancestor, range: createTextRangeFromNode(node, sourceFile) }; @@ -474,8 +472,7 @@ export function getIncomingCalls(program: Program, declaration: CallHierarchyDec function createCallSiteCollector(program: Program, callSites: CallSite[]): (node: Node | undefined) => void { function recordCallSite(node: CallExpression | NewExpression | TaggedTemplateExpression | PropertyAccessExpression | ElementAccessExpression | Decorator | JsxOpeningLikeElement | ClassStaticBlockDeclaration) { - const target = - isTaggedTemplateExpression(node) ? node.tag : + const target = isTaggedTemplateExpression(node) ? node.tag : isJsxOpeningLikeElement(node) ? node.tagName : isAccessExpression(node) ? node : isClassStaticBlockDeclaration(node) ? node : diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 9e2a34583e5cb..df9b7d3e14880 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -160,7 +160,8 @@ export function createClassifier(): Classifier { endOfLineState = end; } } - } while (token !== SyntaxKind.EndOfFileToken); + } + while (token !== SyntaxKind.EndOfFileToken); function handleToken(): void { switch (token) { @@ -257,21 +258,25 @@ export function createClassifier(): Classifier { /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. -const noRegexTable: true[] = arrayToNumericMap([ - SyntaxKind.Identifier, - SyntaxKind.StringLiteral, - SyntaxKind.NumericLiteral, - SyntaxKind.BigIntLiteral, - SyntaxKind.RegularExpressionLiteral, - SyntaxKind.ThisKeyword, - SyntaxKind.PlusPlusToken, - SyntaxKind.MinusMinusToken, - SyntaxKind.CloseParenToken, - SyntaxKind.CloseBracketToken, - SyntaxKind.CloseBraceToken, - SyntaxKind.TrueKeyword, - SyntaxKind.FalseKeyword, -], token => token, () => true); +const noRegexTable: true[] = arrayToNumericMap( + [ + SyntaxKind.Identifier, + SyntaxKind.StringLiteral, + SyntaxKind.NumericLiteral, + SyntaxKind.BigIntLiteral, + SyntaxKind.RegularExpressionLiteral, + SyntaxKind.ThisKeyword, + SyntaxKind.PlusPlusToken, + SyntaxKind.MinusMinusToken, + SyntaxKind.CloseParenToken, + SyntaxKind.CloseBracketToken, + SyntaxKind.CloseBraceToken, + SyntaxKind.TrueKeyword, + SyntaxKind.FalseKeyword, + ], + token => token, + () => true, +); function getNewEndOfLineState(scanner: Scanner, token: SyntaxKind, lastOnTemplateStack: SyntaxKind | undefined): EndOfLineState | undefined { switch (token) { @@ -363,14 +368,22 @@ function convertClassificationsToResult(classifications: Classifications, text: function convertClassification(type: ClassificationType): TokenClass { switch (type) { - case ClassificationType.comment: return TokenClass.Comment; - case ClassificationType.keyword: return TokenClass.Keyword; - case ClassificationType.numericLiteral: return TokenClass.NumberLiteral; - case ClassificationType.bigintLiteral: return TokenClass.BigIntLiteral; - case ClassificationType.operator: return TokenClass.Operator; - case ClassificationType.stringLiteral: return TokenClass.StringLiteral; - case ClassificationType.whiteSpace: return TokenClass.Whitespace; - case ClassificationType.punctuation: return TokenClass.Punctuation; + case ClassificationType.comment: + return TokenClass.Comment; + case ClassificationType.keyword: + return TokenClass.Keyword; + case ClassificationType.numericLiteral: + return TokenClass.NumberLiteral; + case ClassificationType.bigintLiteral: + return TokenClass.BigIntLiteral; + case ClassificationType.operator: + return TokenClass.Operator; + case ClassificationType.stringLiteral: + return TokenClass.StringLiteral; + case ClassificationType.whiteSpace: + return TokenClass.Whitespace; + case ClassificationType.punctuation: + return TokenClass.Punctuation; case ClassificationType.identifier: case ClassificationType.className: case ClassificationType.enumName: @@ -405,7 +418,7 @@ function canFollow(keyword1: SyntaxKind, keyword2: SyntaxKind): boolean { } } -function getPrefixFromLexState(lexState: EndOfLineState): { readonly prefix: string, readonly pushTemplate?: true } { +function getPrefixFromLexState(lexState: EndOfLineState): { readonly prefix: string; readonly pushTemplate?: true; } { // If we're in a string literal, then prepend: "\ // (and a newline). That way when we lex we'll think we're still in a string literal. // @@ -413,7 +426,7 @@ function getPrefixFromLexState(lexState: EndOfLineState): { readonly prefix: str // (and a newline). That way when we lex we'll think we're still in a multiline comment. switch (lexState) { case EndOfLineState.InDoubleQuoteStringLiteral: - return { prefix: "\"\\\n" }; + return { prefix: '"\\\n' }; case EndOfLineState.InSingleQuoteStringLiteral: return { prefix: "'\\\n" }; case EndOfLineState.InMultiLineCommentTrivia: @@ -626,37 +639,61 @@ function classifySymbol(symbol: Symbol, meaningAtPosition: SemanticMeaning, chec /** Returns true if there exists a module that introduces entities on the value side. */ function hasValueSideModule(symbol: Symbol): boolean { - return some(symbol.declarations, declaration => - isModuleDeclaration(declaration) && getModuleInstanceState(declaration) === ModuleInstanceState.Instantiated); + return some(symbol.declarations, declaration => isModuleDeclaration(declaration) && getModuleInstanceState(declaration) === ModuleInstanceState.Instantiated); } function getClassificationTypeName(type: ClassificationType): ClassificationTypeNames { switch (type) { - case ClassificationType.comment: return ClassificationTypeNames.comment; - case ClassificationType.identifier: return ClassificationTypeNames.identifier; - case ClassificationType.keyword: return ClassificationTypeNames.keyword; - case ClassificationType.numericLiteral: return ClassificationTypeNames.numericLiteral; - case ClassificationType.bigintLiteral: return ClassificationTypeNames.bigintLiteral; - case ClassificationType.operator: return ClassificationTypeNames.operator; - case ClassificationType.stringLiteral: return ClassificationTypeNames.stringLiteral; - case ClassificationType.whiteSpace: return ClassificationTypeNames.whiteSpace; - case ClassificationType.text: return ClassificationTypeNames.text; - case ClassificationType.punctuation: return ClassificationTypeNames.punctuation; - case ClassificationType.className: return ClassificationTypeNames.className; - case ClassificationType.enumName: return ClassificationTypeNames.enumName; - case ClassificationType.interfaceName: return ClassificationTypeNames.interfaceName; - case ClassificationType.moduleName: return ClassificationTypeNames.moduleName; - case ClassificationType.typeParameterName: return ClassificationTypeNames.typeParameterName; - case ClassificationType.typeAliasName: return ClassificationTypeNames.typeAliasName; - case ClassificationType.parameterName: return ClassificationTypeNames.parameterName; - case ClassificationType.docCommentTagName: return ClassificationTypeNames.docCommentTagName; - case ClassificationType.jsxOpenTagName: return ClassificationTypeNames.jsxOpenTagName; - case ClassificationType.jsxCloseTagName: return ClassificationTypeNames.jsxCloseTagName; - case ClassificationType.jsxSelfClosingTagName: return ClassificationTypeNames.jsxSelfClosingTagName; - case ClassificationType.jsxAttribute: return ClassificationTypeNames.jsxAttribute; - case ClassificationType.jsxText: return ClassificationTypeNames.jsxText; - case ClassificationType.jsxAttributeStringLiteralValue: return ClassificationTypeNames.jsxAttributeStringLiteralValue; - default: return undefined!; // TODO: GH#18217 Debug.assertNever(type); + case ClassificationType.comment: + return ClassificationTypeNames.comment; + case ClassificationType.identifier: + return ClassificationTypeNames.identifier; + case ClassificationType.keyword: + return ClassificationTypeNames.keyword; + case ClassificationType.numericLiteral: + return ClassificationTypeNames.numericLiteral; + case ClassificationType.bigintLiteral: + return ClassificationTypeNames.bigintLiteral; + case ClassificationType.operator: + return ClassificationTypeNames.operator; + case ClassificationType.stringLiteral: + return ClassificationTypeNames.stringLiteral; + case ClassificationType.whiteSpace: + return ClassificationTypeNames.whiteSpace; + case ClassificationType.text: + return ClassificationTypeNames.text; + case ClassificationType.punctuation: + return ClassificationTypeNames.punctuation; + case ClassificationType.className: + return ClassificationTypeNames.className; + case ClassificationType.enumName: + return ClassificationTypeNames.enumName; + case ClassificationType.interfaceName: + return ClassificationTypeNames.interfaceName; + case ClassificationType.moduleName: + return ClassificationTypeNames.moduleName; + case ClassificationType.typeParameterName: + return ClassificationTypeNames.typeParameterName; + case ClassificationType.typeAliasName: + return ClassificationTypeNames.typeAliasName; + case ClassificationType.parameterName: + return ClassificationTypeNames.parameterName; + case ClassificationType.docCommentTagName: + return ClassificationTypeNames.docCommentTagName; + case ClassificationType.jsxOpenTagName: + return ClassificationTypeNames.jsxOpenTagName; + case ClassificationType.jsxCloseTagName: + return ClassificationTypeNames.jsxCloseTagName; + case ClassificationType.jsxSelfClosingTagName: + return ClassificationTypeNames.jsxSelfClosingTagName; + case ClassificationType.jsxAttribute: + return ClassificationTypeNames.jsxAttribute; + case ClassificationType.jsxText: + return ClassificationTypeNames.jsxText; + case ClassificationType.jsxAttributeStringLiteralValue: + return ClassificationTypeNames.jsxAttributeStringLiteralValue; + default: + return undefined!; // TODO: GH#18217 Debug.assertNever(type); } } @@ -667,7 +704,7 @@ function convertClassificationsToSpans(classifications: Classifications): Classi for (let i = 0; i < dense.length; i += 3) { result.push({ textSpan: createTextSpan(dense[i], dense[i + 1]), - classificationType: getClassificationTypeName(dense[i + 2]) + classificationType: getClassificationTypeName(dense[i + 2]), }); } @@ -1088,18 +1125,22 @@ export function getEncodedSyntacticClassifications(cancellationToken: Cancellati const parent = token.parent; if (tokenKind === SyntaxKind.EqualsToken) { // the '=' in a variable declaration is special cased here. - if (parent.kind === SyntaxKind.VariableDeclaration || + if ( + parent.kind === SyntaxKind.VariableDeclaration || parent.kind === SyntaxKind.PropertyDeclaration || parent.kind === SyntaxKind.Parameter || - parent.kind === SyntaxKind.JsxAttribute) { + parent.kind === SyntaxKind.JsxAttribute + ) { return ClassificationType.operator; } } - if (parent.kind === SyntaxKind.BinaryExpression || + if ( + parent.kind === SyntaxKind.BinaryExpression || parent.kind === SyntaxKind.PrefixUnaryExpression || parent.kind === SyntaxKind.PostfixUnaryExpression || - parent.kind === SyntaxKind.ConditionalExpression) { + parent.kind === SyntaxKind.ConditionalExpression + ) { return ClassificationType.operator; } } diff --git a/src/services/classifier2020.ts b/src/services/classifier2020.ts index 96e246a85db80..1fa90584974f5 100644 --- a/src/services/classifier2020.ts +++ b/src/services/classifier2020.ts @@ -48,17 +48,33 @@ import { /** @internal */ export const enum TokenEncodingConsts { typeOffset = 8, - modifierMask = (1 << typeOffset) - 1 + modifierMask = (1 << typeOffset) - 1, } /** @internal */ export const enum TokenType { - class, enum, interface, namespace, typeParameter, type, parameter, variable, enumMember, property, function, member + class, + enum, + interface, + namespace, + typeParameter, + type, + parameter, + variable, + enumMember, + property, + function, + member, } /** @internal */ export const enum TokenModifier { - declaration, static, async, readonly, defaultLibrary, local + declaration, + static, + async, + readonly, + defaultLibrary, + local, } /** @@ -75,7 +91,7 @@ export function getSemanticClassifications(program: Program, cancellationToken: for (let i = 0; i < dense.length; i += 3) { result.push({ textSpan: createTextSpan(dense[i], dense[i + 1]), - classificationType: dense[i + 2] + classificationType: dense[i + 2], }); } @@ -86,7 +102,7 @@ export function getSemanticClassifications(program: Program, cancellationToken: export function getEncodedSemanticClassifications(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, span: TextSpan): Classifications { return { spans: getSemanticTokens(program, sourceFile, span, cancellationToken), - endOfLineState: EndOfLineState.None + endOfLineState: EndOfLineState.None, }; } @@ -109,7 +125,7 @@ function collectTokens(program: Program, sourceFile: SourceFile, span: TextSpan, let inJSXElement = false; function visit(node: Node) { - switch(node.kind) { + switch (node.kind) { case SyntaxKind.ModuleDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: @@ -141,7 +157,7 @@ function collectTokens(program: Program, sourceFile: SourceFile, span: TextSpan, if (typeIdx !== undefined) { let modifierSet = 0; if (node.parent) { - const parentIsDeclaration = (isBindingElement(node.parent) || tokenFromDeclarationMapping.get(node.parent.kind) === typeIdx); + const parentIsDeclaration = isBindingElement(node.parent) || tokenFromDeclarationMapping.get(node.parent.kind) === typeIdx; if (parentIsDeclaration && (node.parent as NamedDeclaration).name === node) { modifierSet = 1 << TokenModifier.declaration; } @@ -181,7 +197,6 @@ function collectTokens(program: Program, sourceFile: SourceFile, span: TextSpan, } collector(node, typeIdx, modifierSet); - } } } @@ -200,7 +215,7 @@ function classifySymbol(symbol: Symbol, meaning: SemanticMeaning): TokenType | u else if (flags & SymbolFlags.Enum) { return TokenType.enum; } - else if (flags & SymbolFlags.TypeAlias) { + else if (flags & SymbolFlags.TypeAlias) { return TokenType.type; } else if (flags & SymbolFlags.Interface) { @@ -296,5 +311,5 @@ const tokenFromDeclarationMapping = new Map([ [SyntaxKind.TypeAliasDeclaration, TokenType.type], [SyntaxKind.TypeParameter, TokenType.typeParameter], [SyntaxKind.PropertyAssignment, TokenType.property], - [SyntaxKind.ShorthandPropertyAssignment, TokenType.property] + [SyntaxKind.ShorthandPropertyAssignment, TokenType.property], ]); diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index 67dbdbc9a9280..7ca63871fb2de 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -127,6 +127,6 @@ function getDiagnostics({ program, sourceFile, cancellationToken }: CodeFixConte return [ ...program.getSemanticDiagnostics(sourceFile, cancellationToken), ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), - ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken) + ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken), ]; } diff --git a/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts b/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts index 0360e9d117a52..4b27aee72c953 100644 --- a/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts +++ b/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts @@ -29,12 +29,13 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const assertion = getAssertion(diag.file, diag.start); - if (assertion) { - makeChange(changes, diag.file, assertion); - } - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const assertion = getAssertion(diag.file, diag.start); + if (assertion) { + makeChange(changes, diag.file, assertion); + } + }), }); function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, assertion: AsExpression | TypeAssertion) { diff --git a/src/services/codefixes/addEmptyExportDeclaration.ts b/src/services/codefixes/addEmptyExportDeclaration.ts index b490c66af5ecd..d1c9bbf9a6e54 100644 --- a/src/services/codefixes/addEmptyExportDeclaration.ts +++ b/src/services/codefixes/addEmptyExportDeclaration.ts @@ -21,10 +21,10 @@ registerCodeFix({ /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), - /*moduleSpecifier*/ undefined + /*moduleSpecifier*/ undefined, ); changes.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration); }); return [createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, Diagnostics.Add_export_to_make_this_file_into_a_module)]; }, -}); \ No newline at end of file +}); diff --git a/src/services/codefixes/addMissingAsync.ts b/src/services/codefixes/addMissingAsync.ts index bb0510a90d0ad..ef1087ad0ba11 100644 --- a/src/services/codefixes/addMissingAsync.ts +++ b/src/services/codefixes/addMissingAsync.ts @@ -40,7 +40,7 @@ const fixId = "addMissingAsync"; const errorCodes = [ Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Type_0_is_not_comparable_to_type_1.code + Diagnostics.Type_0_is_not_comparable_to_type_1.code, ]; registerCodeFix({ @@ -89,11 +89,13 @@ function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: Source fixedDeclarations?.add(getNodeId(insertionSite)); const cloneWithModifier = factory.updateModifiers( getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ true), - factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | ModifierFlags.Async))); + factory.createNodeArray(factory.createModifiersFromModifierFlags(getSyntacticModifierFlags(insertionSite) | ModifierFlags.Async)), + ); changeTracker.replaceNode( sourceFile, insertionSite, - cloneWithModifier); + cloneWithModifier, + ); } function getFixableErrorSpanDeclaration(sourceFile: SourceFile, span: TextSpan | undefined): FixableDeclaration | undefined { diff --git a/src/services/codefixes/addMissingAwait.ts b/src/services/codefixes/addMissingAwait.ts index 267ecca7e01e1..61c2692b3a8b5 100644 --- a/src/services/codefixes/addMissingAwait.ts +++ b/src/services/codefixes/addMissingAwait.ts @@ -93,7 +93,8 @@ registerCodeFix({ const trackChanges: ContextualTrackChangesFunction = cb => textChanges.ChangeTracker.with(context, cb); return compact([ getDeclarationSiteFix(context, expression, errorCode, checker, trackChanges), - getUseSiteFix(context, expression, errorCode, checker, trackChanges)]); + getUseSiteFix(context, expression, errorCode, checker, trackChanges), + ]); }, getAllCodeActions: context => { const { sourceFile, program, cancellationToken } = context; @@ -114,8 +115,8 @@ registerCodeFix({ function getAwaitErrorSpanExpression(sourceFile: SourceFile, errorCode: number, span: TextSpan, cancellationToken: CancellationToken, program: Program) { const expression = getFixableErrorSpanExpression(sourceFile, span); return expression - && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) - && isInsideAwaitableBody(expression) ? expression : undefined; + && isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) + && isInsideAwaitableBody(expression) ? expression : undefined; } function getDeclarationSiteFix(context: CodeFixContext | CodeFixAllContext, expression: Expression, errorCode: number, checker: TypeChecker, trackChanges: ContextualTrackChangesFunction, fixedDeclarations?: Set) { @@ -135,7 +136,8 @@ function getDeclarationSiteFix(context: CodeFixContext | CodeFixAllContext, expr initializerChanges, awaitableInitializers.initializers.length === 1 ? [Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] - : Diagnostics.Add_await_to_initializers); + : Diagnostics.Add_await_to_initializers, + ); } } @@ -187,13 +189,15 @@ function findAwaitableInitializers( const declaration = tryCast(symbol.valueDeclaration, isVariableDeclaration); const variableName = declaration && tryCast(declaration.name, isIdentifier); const variableStatement = getAncestor(declaration, SyntaxKind.VariableStatement); - if (!declaration || !variableStatement || + if ( + !declaration || !variableStatement || declaration.type || !declaration.initializer || variableStatement.getSourceFile() !== sourceFile || hasSyntacticModifier(variableStatement, ModifierFlags.Export) || !variableName || - !isInsideAwaitableBody(declaration.initializer)) { + !isInsideAwaitableBody(declaration.initializer) + ) { isCompleteFix = false; continue; } @@ -271,10 +275,11 @@ function isInsideAwaitableBody(node: Node) { return node.flags & NodeFlags.AwaitContext || !!findAncestor(node, ancestor => ancestor.parent && isArrowFunction(ancestor.parent) && ancestor.parent.body === ancestor || isBlock(ancestor) && ( - ancestor.parent.kind === SyntaxKind.FunctionDeclaration || - ancestor.parent.kind === SyntaxKind.FunctionExpression || - ancestor.parent.kind === SyntaxKind.ArrowFunction || - ancestor.parent.kind === SyntaxKind.MethodDeclaration)); + ancestor.parent.kind === SyntaxKind.FunctionDeclaration || + ancestor.parent.kind === SyntaxKind.FunctionExpression || + ancestor.parent.kind === SyntaxKind.ArrowFunction || + ancestor.parent.kind === SyntaxKind.MethodDeclaration + )); } function makeChange(changeTracker: textChanges.ChangeTracker, errorCode: number, sourceFile: SourceFile, checker: TypeChecker, insertionSite: Expression, fixedDeclarations?: Set) { @@ -310,7 +315,8 @@ function makeChange(changeTracker: textChanges.ChangeTracker, errorCode: number, changeTracker.replaceNode( sourceFile, insertionSite.parent.expression, - factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite.parent.expression))); + factory.createParenthesizedExpression(factory.createAwaitExpression(insertionSite.parent.expression)), + ); insertLeadingSemicolonIfNeeded(changeTracker, insertionSite.parent.expression, sourceFile); } else if (contains(callableConstructableErrorCodes, errorCode) && isCallOrNewExpression(insertionSite.parent)) { diff --git a/src/services/codefixes/addMissingConst.ts b/src/services/codefixes/addMissingConst.ts index 8a848c2616f80..87adb892cd9f6 100644 --- a/src/services/codefixes/addMissingConst.ts +++ b/src/services/codefixes/addMissingConst.ts @@ -27,7 +27,7 @@ import { const fixId = "addMissingConst"; const errorCodes = [ Diagnostics.Cannot_find_name_0.code, - Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code + Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code, ]; registerCodeFix({ @@ -49,8 +49,7 @@ function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: Source const token = getTokenAtPosition(sourceFile, pos); const forInitializer = findAncestor(token, node => isForInOrOfStatement(node.parent) ? node.parent.initializer === node : - isPossiblyPartOfDestructuring(node) ? false : "quit" - ); + isPossiblyPartOfDestructuring(node) ? false : "quit"); if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); const parent = token.parent; @@ -69,8 +68,7 @@ function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: Source const commaExpression = findAncestor(token, node => isExpressionStatement(node.parent) ? true : - isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit" - ); + isPossiblyPartOfCommaSeperatedInitializer(node) ? false : "quit"); if (commaExpression) { const checker = program.getTypeChecker(); if (!expressionCouldBeVariableDeclaration(commaExpression, checker)) { @@ -101,8 +99,7 @@ function isPossiblyPartOfDestructuring(node: Node): boolean { } function arrayElementCouldBeVariableDeclaration(expression: Expression, checker: TypeChecker): boolean { - const identifier = - isIdentifier(expression) ? expression : + const identifier = isIdentifier(expression) ? expression : isAssignmentExpression(expression, /*excludeCompoundAssignment*/ true) && isIdentifier(expression.left) ? expression.left : undefined; return !!identifier && !checker.getSymbolAtLocation(identifier); diff --git a/src/services/codefixes/addMissingDeclareProperty.ts b/src/services/codefixes/addMissingDeclareProperty.ts index c46c353b37f3e..e78a76e25e96d 100644 --- a/src/services/codefixes/addMissingDeclareProperty.ts +++ b/src/services/codefixes/addMissingDeclareProperty.ts @@ -40,8 +40,10 @@ function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: Source return; } const declaration = token.parent; - if (declaration.kind === SyntaxKind.PropertyDeclaration && - (!fixedNodes || tryAddToSet(fixedNodes, declaration))) { + if ( + declaration.kind === SyntaxKind.PropertyDeclaration && + (!fixedNodes || tryAddToSet(fixedNodes, declaration)) + ) { changeTracker.insertModifierBefore(sourceFile, SyntaxKind.DeclareKeyword, declaration); } } diff --git a/src/services/codefixes/addNameToNamelessParameter.ts b/src/services/codefixes/addNameToNamelessParameter.ts index dc36931d79237..a4d662fa913b9 100644 --- a/src/services/codefixes/addNameToNamelessParameter.ts +++ b/src/services/codefixes/addNameToNamelessParameter.ts @@ -44,6 +44,7 @@ function makeChange(changeTracker: textChanges.ChangeTracker, sourceFile: Source "arg" + i, param.questionToken, param.dotDotDotToken ? factory.createArrayTypeNode(typeNode) : typeNode, - param.initializer); + param.initializer, + ); changeTracker.replaceNode(sourceFile, param, replacement); } diff --git a/src/services/codefixes/addOptionalPropertyUndefined.ts b/src/services/codefixes/addOptionalPropertyUndefined.ts index 7664bea35be10..4b584c3f617ca 100644 --- a/src/services/codefixes/addOptionalPropertyUndefined.ts +++ b/src/services/codefixes/addOptionalPropertyUndefined.ts @@ -79,7 +79,7 @@ function shouldUseParentTypeOfProperty(sourceNode: Node, targetNode: Node, check * Find the source and target of the incorrect assignment. * The call is recursive for property assignments. */ -function getSourceTarget(errorNode: Node | undefined, checker: TypeChecker): { source: Node, target: Node } | undefined { +function getSourceTarget(errorNode: Node | undefined, checker: TypeChecker): { source: Node; target: Node; } | undefined { if (!errorNode) { return undefined; } @@ -98,8 +98,10 @@ function getSourceTarget(errorNode: Node | undefined, checker: TypeChecker): { s const name = (n.valueDeclaration as any as SignatureDeclaration).parameters[i].name; if (isIdentifier(name)) return { source: errorNode, target: name }; } - else if (isPropertyAssignment(errorNode.parent) && isIdentifier(errorNode.parent.name) || - isShorthandPropertyAssignment(errorNode.parent)) { + else if ( + isPropertyAssignment(errorNode.parent) && isIdentifier(errorNode.parent.name) || + isShorthandPropertyAssignment(errorNode.parent) + ) { const parentTarget = getSourceTarget(errorNode.parent.parent, checker); if (!parentTarget) return undefined; const prop = checker.getPropertyOfType(checker.getTypeAtLocation(parentTarget.target), (errorNode.parent.name as Identifier).text); @@ -107,7 +109,7 @@ function getSourceTarget(errorNode: Node | undefined, checker: TypeChecker): { s if (!declaration) return undefined; return { source: isPropertyAssignment(errorNode.parent) ? errorNode.parent.initializer : errorNode.parent.name, - target: declaration + target: declaration, }; } return undefined; @@ -119,7 +121,7 @@ function addUndefinedToOptionalProperty(changes: textChanges.ChangeTracker, toAd if (d && (isPropertySignature(d) || isPropertyDeclaration(d)) && d.type) { const t = factory.createUnionTypeNode([ ...d.type.kind === SyntaxKind.UnionType ? (d.type as UnionTypeNode).types : [d.type], - factory.createTypeReferenceNode("undefined") + factory.createTypeReferenceNode("undefined"), ]); changes.replaceNode(d.getSourceFile(), d.type, t); } diff --git a/src/services/codefixes/annotateWithTypeFromJSDoc.ts b/src/services/codefixes/annotateWithTypeFromJSDoc.ts index a2cfc5e97224c..f989025b5cc4c 100644 --- a/src/services/codefixes/annotateWithTypeFromJSDoc.ts +++ b/src/services/codefixes/annotateWithTypeFromJSDoc.ts @@ -59,10 +59,11 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId, Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const decl = getDeclaration(diag.file, diag.start); - if (decl) doChange(changes, diag.file, decl); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const decl = getDeclaration(diag.file, diag.start); + if (decl) doChange(changes, diag.file, decl); + }), }); function getDeclaration(file: SourceFile, pos: number): DeclarationWithType | undefined { @@ -155,7 +156,8 @@ function transformJSDocTypeLiteral(node: JSDocTypeLiteral) { /*modifiers*/ undefined, isIdentifier(tag.name) ? tag.name : tag.name.right, isOptionalJSDocPropertyLikeTag(tag) ? factory.createToken(SyntaxKind.QuestionToken) : undefined, - tag.typeExpression && visitNode(tag.typeExpression.type, transformJSDocType, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword)))); + tag.typeExpression && visitNode(tag.typeExpression.type, transformJSDocType, isTypeNode) || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword), + ))); setEmitFlags(typeNode, EmitFlags.SingleLine); return typeNode; } @@ -225,7 +227,8 @@ function transformJSDocIndexSignature(node: TypeReferenceNode) { node.typeArguments![0].kind === SyntaxKind.NumberKeyword ? "n" : "s", /*questionToken*/ undefined, factory.createTypeReferenceNode(node.typeArguments![0].kind === SyntaxKind.NumberKeyword ? "number" : "string", []), - /*initializer*/ undefined); + /*initializer*/ undefined, + ); const indexSignature = factory.createTypeLiteralNode([factory.createIndexSignature(/*modifiers*/ undefined, [index], node.typeArguments![1])]); setEmitFlags(indexSignature, EmitFlags.SingleLine); return indexSignature; diff --git a/src/services/codefixes/convertConstToLet.ts b/src/services/codefixes/convertConstToLet.ts index d9817ab8250b2..fb1cefbc859b3 100644 --- a/src/services/codefixes/convertConstToLet.ts +++ b/src/services/codefixes/convertConstToLet.ts @@ -50,7 +50,7 @@ registerCodeFix({ }); })); }, - fixIds: [fixId] + fixIds: [fixId], }); interface Info { diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index 5073d687a67ed..92d1c85f269f6 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -72,13 +72,11 @@ const errorCodes = [Diagnostics.This_constructor_function_may_be_converted_to_a_ registerCodeFix({ errorCodes, getCodeActions(context: CodeFixContext) { - const changes = textChanges.ChangeTracker.with(context, t => - doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); return [createCodeFixAction(fixId, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId, Diagnostics.Convert_all_constructor_functions_to_classes)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, err) => - doChange(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())), + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, err) => doChange(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())), }); function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, position: number, checker: TypeChecker, preferences: UserPreferences, compilerOptions: CompilerOptions): void { @@ -116,7 +114,8 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, po if (member.name === "prototype" && member.declarations) { const firstDeclaration = member.declarations[0]; // only one "x.prototype = { ... }" will pass - if (member.declarations.length === 1 && + if ( + member.declarations.length === 1 && isPropertyAccessExpression(firstDeclaration) && isBinaryExpression(firstDeclaration.parent) && firstDeclaration.parent.operatorToken.kind === SyntaxKind.EqualsToken && @@ -188,13 +187,15 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, po return; } - if (some(members, m => { - const name = getNameOfDeclaration(m); - if (name && isIdentifier(name) && idText(name) === symbolName(symbol)) { - return true; // class member already made for this name - } - return false; - })) { + if ( + some(members, m => { + const name = getNameOfDeclaration(m); + if (name && isIdentifier(name) && idText(name) === symbolName(symbol)) { + return true; // class member already made for this name + } + return false; + }) + ) { return; } @@ -204,8 +205,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, po changes.delete(sourceFile, nodeToDelete); if (!assignmentExpr) { - members.push(factory.createPropertyDeclaration(modifiers, symbol.name, /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, /*initializer*/ undefined)); + members.push(factory.createPropertyDeclaration(modifiers, symbol.name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); return; } @@ -233,7 +233,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, po // Drop constructor assignments if (isConstructorAssignment(property)) return; return; - } + }, ); return; } @@ -254,8 +254,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, po function createFunctionExpressionMember(members: ClassElement[], functionExpression: FunctionExpression, name: PropertyName) { const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, SyntaxKind.AsyncKeyword)); - const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); return; @@ -274,8 +273,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, po bodyBlock = factory.createBlock([factory.createReturnStatement(arrowFunctionBody)]); } const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, SyntaxKind.AsyncKeyword)); - const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + const method = factory.createMethodDeclaration(fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); copyLeadingComments(assignmentBinaryExpression, method, sourceFile); members.push(method); } @@ -294,8 +292,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, po } const modifiers = getModifierKindFromSource(node.parent.parent, SyntaxKind.ExportKeyword); - const cls = factory.createClassDeclaration(modifiers, node.name, - /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + const cls = factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } @@ -307,8 +304,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, po } const modifiers = getModifierKindFromSource(node, SyntaxKind.ExportKeyword); - const cls = factory.createClassDeclaration(modifiers, node.name, - /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + const cls = factory.createClassDeclaration(modifiers, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); // Don't call copyComments here because we'll already leave them in place return cls; } diff --git a/src/services/codefixes/convertLiteralTypeToMappedType.ts b/src/services/codefixes/convertLiteralTypeToMappedType.ts index 1e68d28758d1c..bde76824b8ce6 100644 --- a/src/services/codefixes/convertLiteralTypeToMappedType.ts +++ b/src/services/codefixes/convertLiteralTypeToMappedType.ts @@ -33,16 +33,17 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, [Diagnostics.Convert_0_to_1_in_0, constraint, name], fixId, Diagnostics.Convert_all_type_literals_to_mapped_type)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(diag.file, diag.start); - if (info) { - doChange(changes, diag.file, info); - } - }) + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file, diag.start); + if (info) { + doChange(changes, diag.file, info); + } + }), }); interface Info { - container: TypeLiteralNode, + container: TypeLiteralNode; typeNode: TypeNode | undefined; constraint: string; name: string; @@ -64,11 +65,16 @@ function getInfo(sourceFile: SourceFile, pos: number): Info | undefined { } function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, { container, typeNode, constraint, name }: Info): void { - changes.replaceNode(sourceFile, container, factory.createMappedTypeNode( - /*readonlyToken*/ undefined, - factory.createTypeParameterDeclaration(/*modifiers*/ undefined, name, factory.createTypeReferenceNode(constraint)), - /*nameType*/ undefined, - /*questionToken*/ undefined, - typeNode, - /*members*/ undefined)); + changes.replaceNode( + sourceFile, + container, + factory.createMappedTypeNode( + /*readonlyToken*/ undefined, + factory.createTypeParameterDeclaration(/*modifiers*/ undefined, name, factory.createTypeReferenceNode(constraint)), + /*nameType*/ undefined, + /*questionToken*/ undefined, + typeNode, + /*members*/ undefined, + ), + ); } diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 734f1b09ec44a..cb122865c66ac 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -91,7 +91,7 @@ registerCodeFix({ errorCodes, getCodeActions(context: CodeFixContext) { codeActionSucceeded = true; - const changes = textChanges.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker())); + const changes = textChanges.ChangeTracker.with(context, t => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker())); return codeActionSucceeded ? [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], @@ -140,8 +140,10 @@ function convertToAsyncFunction(changes: textChanges.ChangeTracker, sourceFile: let functionToConvert: FunctionLikeDeclaration | undefined; // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name - if (isIdentifier(tokenAtPosition) && isVariableDeclaration(tokenAtPosition.parent) && - tokenAtPosition.parent.initializer && isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + if ( + isIdentifier(tokenAtPosition) && isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && isFunctionLikeDeclaration(tokenAtPosition.parent.initializer) + ) { functionToConvert = tokenAtPosition.parent.initializer; } else { @@ -213,8 +215,10 @@ function getAllPromiseExpressionsToReturn(func: FunctionLikeDeclaration, checker setOfExpressionsToReturn.add(getNodeId(node)); forEach(node.arguments, visit); } - else if (isPromiseReturningCallExpression(node, checker, "catch") || - isPromiseReturningCallExpression(node, checker, "finally")) { + else if ( + isPromiseReturningCallExpression(node, checker, "catch") || + isPromiseReturningCallExpression(node, checker, "finally") + ) { setOfExpressionsToReturn.add(getNodeId(node)); // if .catch() or .finally() is the last call in the chain, move leftward in the chain until we hit something else that should be returned forEachChild(node, visit); @@ -255,8 +259,10 @@ function getExplicitPromisedTypeOfPromiseReturningCallExpression(node: PromiseRe // type argument supplied for the callback. For other promise types we would need a more complex heuristic to determine // which type argument is safe to use as an annotation. const promiseType = checker.getTypeAtLocation(node.expression.expression); - if (isReferenceToType(promiseType, checker.getPromiseType()) || - isReferenceToType(promiseType, checker.getPromiseLikeType())) { + if ( + isReferenceToType(promiseType, checker.getPromiseType()) || + isReferenceToType(promiseType, checker.getPromiseLikeType()) + ) { if (node.expression.name.escapedText === "then") { if (callback === elementAt(node.arguments, 0)) { // for the `onfulfilled` callback, use the first type argument @@ -306,8 +312,8 @@ function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: if (lastCallSignature && !isParameter(node.parent) && !isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { const firstParameter = firstOrUndefined(lastCallSignature.parameters); const ident = firstParameter?.valueDeclaration - && isParameter(firstParameter.valueDeclaration) - && tryCast(firstParameter.valueDeclaration.name, isIdentifier) + && isParameter(firstParameter.valueDeclaration) + && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || factory.createUniqueName("result", GeneratedIdentifierFlags.Optimistic); const synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); @@ -343,7 +349,8 @@ function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: original.dotDotDotToken, original.propertyName || original.name, renameInfo, - original.initializer); + original.initializer, + ); } } else if (isIdentifier(original)) { @@ -471,9 +478,10 @@ function finishCatchOrFinallyTransform(node: PromiseReturningCallExpression<"the getSynthesizedDeepClone(declareSynthBindingPattern(continuationArgName)), /*exclamationToken*/ undefined, /*type*/ undefined, - varDeclIdentifier - )], - NodeFlags.Const))); + varDeclIdentifier, + ), + ], NodeFlags.Const), + )); } return statements; @@ -597,8 +605,11 @@ function createVariableOrAssignmentOrExpressionStatement(variableName: SynthBind getSynthesizedDeepClone(declareSynthBindingName(variableName)), /*exclamationToken*/ undefined, typeAnnotation, - rightHandSide)], - NodeFlags.Const))]; + rightHandSide, + ), + ], NodeFlags.Const), + ), + ]; } function maybeAnnotateAndReturn(expressionToReturn: Expression | undefined, typeAnnotation: TypeNode | undefined): Statement[] { @@ -606,7 +617,7 @@ function maybeAnnotateAndReturn(expressionToReturn: Expression | undefined, type const name = factory.createUniqueName("result", GeneratedIdentifierFlags.Optimistic); return [ ...createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), - factory.createReturnStatement(name) + factory.createReturnStatement(name), ]; } return [factory.createReturnStatement(expressionToReturn)]; @@ -688,7 +699,7 @@ function transformCallbackArgument(func: Expression, hasContinuation: boolean, c // However, branching returns in the outermost continuation are acceptable as no other continuation follows it: // // source | result - //--------------------------------------|--------------------------------------- + // --------------------------------------|--------------------------------------- // function f() { | async function f() { // return foo().then(res => { | const res = await foo(); // if (res.ok) { | if (res.ok) { @@ -720,7 +731,8 @@ function transformCallbackArgument(func: Expression, hasContinuation: boolean, c refactoredStmts, continuationArgName, transformer, - seenReturnStatement); + seenReturnStatement, + ); } else { const inlinedStatements = isFixablePromiseHandler(funcBody, transformer.checker) ? @@ -780,8 +792,7 @@ function removeReturns(stmts: readonly Statement[], prevArgName: SynthBindingNam ret.push(factory.createExpressionStatement(factory.createAssignment(referenceSynthIdentifier(prevArgName), possiblyAwaitedExpression))); } else { - ret.push(factory.createVariableStatement(/*modifiers*/ undefined, - (factory.createVariableDeclarationList([factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ undefined, /*type*/ undefined, possiblyAwaitedExpression)], NodeFlags.Const)))); + ret.push(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ undefined, /*type*/ undefined, possiblyAwaitedExpression)], NodeFlags.Const))); } } } @@ -792,8 +803,7 @@ function removeReturns(stmts: readonly Statement[], prevArgName: SynthBindingNam // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables if (!seenReturnStatement && prevArgName !== undefined) { - ret.push(factory.createVariableStatement(/*modifiers*/ undefined, - (factory.createVariableDeclarationList([factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ undefined, /*type*/ undefined, factory.createIdentifier("undefined"))], NodeFlags.Const)))); + ret.push(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(declareSynthBindingName(prevArgName), /*exclamationToken*/ undefined, /*type*/ undefined, factory.createIdentifier("undefined"))], NodeFlags.Const))); } return ret; diff --git a/src/services/codefixes/convertToEsModule.ts b/src/services/codefixes/convertToEsModule.ts index b15a0521c1cb1..1a5d2ad8ad2c8 100644 --- a/src/services/codefixes/convertToEsModule.ts +++ b/src/services/codefixes/convertToEsModule.ts @@ -162,8 +162,10 @@ function collectExportRenames(sourceFile: SourceFile, checker: TypeChecker, iden const res = new Map(); forEachExportReference(sourceFile, node => { const { text } = node.name; - if (!res.has(text) && (isIdentifierANonContextualKeyword(node.name) - || checker.resolveName(text, node, SymbolFlags.Value, /*excludeGlobals*/ true))) { + if ( + !res.has(text) && (isIdentifierANonContextualKeyword(node.name) + || checker.resolveName(text, node, SymbolFlags.Value, /*excludeGlobals*/ true)) + ) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName(`_${text}`, identifiers)); } @@ -181,11 +183,11 @@ function convertExportsAccesses(sourceFile: SourceFile, exports: ExportRenames, }); } -function forEachExportReference(sourceFile: SourceFile, cb: (node: (PropertyAccessExpression & { name: Identifier }), isAssignmentLhs: boolean) => void): void { +function forEachExportReference(sourceFile: SourceFile, cb: (node: PropertyAccessExpression & { name: Identifier; }, isAssignmentLhs: boolean) => void): void { sourceFile.forEachChild(function recur(node) { if (isPropertyAccessExpression(node) && isExportsOrModuleExportsOrAlias(sourceFile, node.expression) && isIdentifier(node.name)) { const { parent } = node; - cb(node as typeof node & { name: Identifier }, isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === SyntaxKind.EqualsToken); + cb(node as typeof node & { name: Identifier; }, isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === SyntaxKind.EqualsToken); } node.forEachChild(recur); }); @@ -203,7 +205,7 @@ function convertStatement( target: ScriptTarget, exports: ExportRenames, useSitesToUnqualify: Map | undefined, - quotePreference: QuotePreference + quotePreference: QuotePreference, ): ModuleExportsChanged { switch (statement.kind) { case SyntaxKind.VariableStatement: @@ -282,7 +284,7 @@ function convertPropertyAccessImport(name: BindingName, propertyName: string, mo case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` - const tmp = makeUniqueName(propertyName, identifiers); + const tmp = makeUniqueName(propertyName, identifiers); return convertedImports([ makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, name, factory.createIdentifier(tmp)), @@ -329,7 +331,7 @@ function convertAssignment( } } else if (isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { - convertNamedExport(sourceFile, assignment as BinaryExpression & { left: PropertyAccessExpression }, changes, exports); + convertNamedExport(sourceFile, assignment as BinaryExpression & { left: PropertyAccessExpression; }, changes, exports); } return false; @@ -362,7 +364,7 @@ function tryChangeModuleExportsObject(object: ObjectLiteralExpression, useSitesT function convertNamedExport( sourceFile: SourceFile, - assignment: BinaryExpression & { left: PropertyAccessExpression }, + assignment: BinaryExpression & { left: PropertyAccessExpression; }, changes: textChanges.ChangeTracker, exports: ExportRenames, ): void { @@ -402,7 +404,7 @@ function reExportDefault(moduleSpecifier: string): ExportDeclaration { return makeExportDeclaration([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, "default")], moduleSpecifier); } -function convertExportsPropertyAssignment({ left, right, parent }: BinaryExpression & { left: PropertyAccessExpression }, sourceFile: SourceFile, changes: textChanges.ChangeTracker): void { +function convertExportsPropertyAssignment({ left, right, parent }: BinaryExpression & { left: PropertyAccessExpression; }, sourceFile: SourceFile, changes: textChanges.ChangeTracker): void { const name = left.name.text; if ((isFunctionExpression(right) || isArrowFunction(right) || isClassExpression(right)) && (!right.name || right.name.text === name)) { // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. @@ -415,9 +417,7 @@ function convertExportsPropertyAssignment({ left, right, parent }: BinaryExpress } else { // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` - changes.replaceNodeRangeWithNodes(sourceFile, left.expression, findChildOfKind(left, SyntaxKind.DotToken, sourceFile)!, - [factory.createToken(SyntaxKind.ExportKeyword), factory.createToken(SyntaxKind.ConstKeyword)], - { joiner: " ", suffix: " " }); + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, findChildOfKind(left, SyntaxKind.DotToken, sourceFile)!, [factory.createToken(SyntaxKind.ExportKeyword), factory.createToken(SyntaxKind.ConstKeyword)], { joiner: " ", suffix: " " }); } } @@ -559,15 +559,14 @@ function convertSingleIdentifierImport(name: Identifier, moduleSpecifier: String } } - const namedBindings = namedBindingsNames.size === 0 ? undefined : arrayFrom(mapIterator(namedBindingsNames.entries(), ([propertyName, idName]) => - factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName === idName ? undefined : factory.createIdentifier(propertyName), factory.createIdentifier(idName)))); + const namedBindings = namedBindingsNames.size === 0 ? undefined : arrayFrom(mapIterator(namedBindingsNames.entries(), ([propertyName, idName]) => factory.createImportSpecifier(/*isTypeOnly*/ false, propertyName === idName ? undefined : factory.createIdentifier(propertyName), factory.createIdentifier(idName)))); if (!namedBindings) { // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } return convertedImports( [makeImport(needDefaultImport ? getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)], - useSitesToUnqualify + useSitesToUnqualify, ); } @@ -632,7 +631,8 @@ function functionExpressionToDeclaration(name: string | undefined, additionalMod getSynthesizedDeepClones(fn.typeParameters), getSynthesizedDeepClones(fn.parameters), getSynthesizedDeepClone(fn.type), - factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body!, useSitesToUnqualify))); + factory.converters.convertToFunctionBlock(replaceImportUseSites(fn.body!, useSitesToUnqualify)), + ); } function classExpressionToDeclaration(name: string | undefined, additionalModifiers: readonly Modifier[], cls: ClassExpression, useSitesToUnqualify: Map | undefined): ClassDeclaration { @@ -641,7 +641,8 @@ function classExpressionToDeclaration(name: string | undefined, additionalModifi name, getSynthesizedDeepClones(cls.typeParameters), getSynthesizedDeepClones(cls.heritageClauses), - replaceImportUseSites(cls.members, useSitesToUnqualify)); + replaceImportUseSites(cls.members, useSitesToUnqualify), + ); } function makeSingleImport(localName: string, propertyName: string, moduleSpecifier: StringLiteralLike, quotePreference: QuotePreference): ImportDeclaration { @@ -659,7 +660,9 @@ function makeConst(modifiers: readonly Modifier[] | undefined, name: string | Bi modifiers, factory.createVariableDeclarationList( [factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, /*type*/ undefined, init)], - NodeFlags.Const)); + NodeFlags.Const, + ), + ); } function makeExportDeclaration(exportSpecifiers: ExportSpecifier[] | undefined, moduleSpecifier?: string): ExportDeclaration { @@ -667,7 +670,8 @@ function makeExportDeclaration(exportSpecifiers: ExportSpecifier[] | undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, exportSpecifiers && factory.createNamedExports(exportSpecifiers), - moduleSpecifier === undefined ? undefined : factory.createStringLiteral(moduleSpecifier)); + moduleSpecifier === undefined ? undefined : factory.createStringLiteral(moduleSpecifier), + ); } interface ConvertedImports { @@ -678,6 +682,6 @@ interface ConvertedImports { function convertedImports(newImports: readonly Node[], useSitesToUnqualify?: Map): ConvertedImports { return { newImports, - useSitesToUnqualify + useSitesToUnqualify, }; } diff --git a/src/services/codefixes/convertToMappedObjectType.ts b/src/services/codefixes/convertToMappedObjectType.ts index 1a3b8498a49f5..f07987f258c6b 100644 --- a/src/services/codefixes/convertToMappedObjectType.ts +++ b/src/services/codefixes/convertToMappedObjectType.ts @@ -44,13 +44,17 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [Diagnostics.Convert_0_to_mapped_object_type, name])]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(diag.file, diag.start); - if (info) doChange(changes, diag.file, info); - }) + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file, diag.start); + if (info) doChange(changes, diag.file, info); + }), }); -interface Info { readonly indexSignature: IndexSignatureDeclaration; readonly container: FixableDeclaration; } +interface Info { + readonly indexSignature: IndexSignatureDeclaration; + readonly container: FixableDeclaration; +} function getInfo(sourceFile: SourceFile, pos: number): Info | undefined { const token = getTokenAtPosition(sourceFile, pos); const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration); @@ -77,7 +81,8 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, { /*nameType*/ undefined, indexSignature.questionToken, indexSignature.type, - /*members*/ undefined); + /*members*/ undefined, + ); const intersectionType = factory.createIntersectionTypeNode([ ...getAllSuperTypeNodes(container), mappedIntersectionType, diff --git a/src/services/codefixes/convertToTypeOnlyExport.ts b/src/services/codefixes/convertToTypeOnlyExport.ts index b0e67f43b4cbd..36a75c5ddefaa 100644 --- a/src/services/codefixes/convertToTypeOnlyExport.ts +++ b/src/services/codefixes/convertToTypeOnlyExport.ts @@ -43,7 +43,7 @@ registerCodeFix({ fixSingleExportDeclaration(changes, exportSpecifier, context); } }); - } + }, }); function getExportSpecifierForDiagnosticSpan(span: TextSpan, sourceFile: SourceFile) { @@ -68,19 +68,19 @@ function fixSingleExportDeclaration(changes: textChanges.ChangeTracker, exportSp /*isTypeOnly*/ false, factory.updateNamedExports(exportClause, filter(exportClause.elements, e => !contains(typeExportSpecifiers, e))), exportDeclaration.moduleSpecifier, - /*assertClause*/ undefined + /*assertClause*/ undefined, ); const typeExportDeclaration = factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ true, factory.createNamedExports(typeExportSpecifiers), exportDeclaration.moduleSpecifier, - /*assertClause*/ undefined + /*assertClause*/ undefined, ); changes.replaceNode(context.sourceFile, exportDeclaration, valueExportDeclaration, { leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude + trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude, }); changes.insertNodeAfter(context.sourceFile, exportDeclaration, typeExportDeclaration); } @@ -94,7 +94,8 @@ function getTypeExportSpecifiers(originExportSpecifier: ExportSpecifier, context const diagnostics = getDiagnosticsWithinSpan( createTextSpanFromNode(exportClause), - context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken)); + context.program.getSemanticDiagnostics(context.sourceFile, context.cancellationToken), + ); return filter(exportClause.elements, element => { return element === originExportSpecifier || findDiagnosticForNode(element, diagnostics)?.code === errorCodes[0]; diff --git a/src/services/codefixes/convertToTypeOnlyImport.ts b/src/services/codefixes/convertToTypeOnlyImport.ts index fd5cd3cc2eefc..5578ddc5d6902 100644 --- a/src/services/codefixes/convertToTypeOnlyImport.ts +++ b/src/services/codefixes/convertToTypeOnlyImport.ts @@ -47,12 +47,13 @@ registerCodeFix({ ? [Diagnostics.Use_type_0, declaration.propertyName?.text ?? declaration.name.text] : Diagnostics.Use_import_type, fixId, - Diagnostics.Fix_all_with_type_only_imports); + Diagnostics.Fix_all_with_type_only_imports, + ); if (some(importDeclarationChanges)) { return [ createCodeFixActionWithoutFixAll(fixId, importDeclarationChanges, Diagnostics.Use_import_type), - mainAction + mainAction, ]; } return [mainAction]; @@ -68,7 +69,8 @@ registerCodeFix({ doChange(changes, diag.file, errorDeclaration); fixedImportDeclarations.add(errorDeclaration); } - else if (errorDeclaration?.kind === SyntaxKind.ImportSpecifier + else if ( + errorDeclaration?.kind === SyntaxKind.ImportSpecifier && !fixedImportDeclarations.has(errorDeclaration.parent.parent.parent) && canConvertImportDeclarationForSpecifier(errorDeclaration, diag.file, context.program) ) { @@ -79,7 +81,7 @@ registerCodeFix({ doChange(changes, diag.file, errorDeclaration); } }); - } + }, }); function getDeclaration(sourceFile: SourceFile, pos: number) { @@ -87,7 +89,6 @@ function getDeclaration(sourceFile: SourceFile, pos: number) { return isImportSpecifier(parent) || isImportDeclaration(parent) && parent.importClause ? parent : undefined; } - function canConvertImportDeclarationForSpecifier(specifier: ImportSpecifier, sourceFile: SourceFile, program: Program): boolean { if (specifier.parent.parent.name) { // An import declaration with a default import and named bindings can't be type-only @@ -138,10 +139,10 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, de const newNamedBindings = importClause.namedBindings?.kind === SyntaxKind.NamedImports ? factory.updateNamedImports( importClause.namedBindings, - sameMap(importClause.namedBindings.elements, e => factory.updateImportSpecifier(e, /*isTypeOnly*/ false, e.propertyName, e.name))) + sameMap(importClause.namedBindings.elements, e => factory.updateImportSpecifier(e, /*isTypeOnly*/ false, e.propertyName, e.name)), + ) : importClause.namedBindings; - const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, - factory.updateImportClause(importClause, /*isTypeOnly*/ true, importClause.name, newNamedBindings), declaration.moduleSpecifier, declaration.assertClause); + const importDeclaration = factory.updateImportDeclaration(declaration, declaration.modifiers, factory.updateImportClause(importClause, /*isTypeOnly*/ true, importClause.name, newNamedBindings), declaration.moduleSpecifier, declaration.assertClause); changes.replaceNode(sourceFile, declaration, importDeclaration); } } diff --git a/src/services/codefixes/convertTypedefToType.ts b/src/services/codefixes/convertTypedefToType.ts index ea233c1d2d1d1..395ee58f1378f 100644 --- a/src/services/codefixes/convertTypedefToType.ts +++ b/src/services/codefixes/convertTypedefToType.ts @@ -24,7 +24,11 @@ import { textChanges, TypeAliasDeclaration, } from "../_namespaces/ts"; -import { codeFixAll, createCodeFixAction, registerCodeFix } from "../_namespaces/ts.codefix"; +import { + codeFixAll, + createCodeFixAction, + registerCodeFix, +} from "../_namespaces/ts.codefix"; const fixId = "convertTypedefToType"; const errorCodes = [Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type.code]; @@ -35,7 +39,7 @@ registerCodeFix({ const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); const node = getTokenAtPosition( context.sourceFile, - context.span.start + context.span.start, ); if (!node) return; @@ -53,16 +57,17 @@ registerCodeFix({ ]; } }, - getAllCodeActions: context => codeFixAll( - context, - errorCodes, - (changes, diag) => { - const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); - const node = getTokenAtPosition(diag.file, diag.start); - const fixAll = true; - if (node) doChange(changes, node, diag.file, newLineCharacter, fixAll); - } - ) + getAllCodeActions: context => + codeFixAll( + context, + errorCodes, + (changes, diag) => { + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); + const node = getTokenAtPosition(diag.file, diag.start); + const fixAll = true; + if (node) doChange(changes, node, diag.file, newLineCharacter, fixAll); + }, + ), }); function doChange( @@ -70,7 +75,7 @@ function doChange( node: Node, sourceFile: SourceFile, newLine: string, - fixAll = false + fixAll = false, ) { if (!isJSDocTypedefTag(node)) return; @@ -120,13 +125,12 @@ function doChange( changes.replaceRange(sourceFile, { pos, end }, declaration, { prefix, suffix }); } -function getLeftAndRightSiblings(typedefNode: JSDocTypedefTag): { leftSibling?: Node, rightSibling?: Node } { - +function getLeftAndRightSiblings(typedefNode: JSDocTypedefTag): { leftSibling?: Node; rightSibling?: Node; } { const commentNode = typedefNode.parent; const maxChildIndex = commentNode.getChildCount() - 1; const currentNodeIndex = commentNode.getChildren().findIndex( - (n) => n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd() + n => n.getStart() === typedefNode.getStart() && n.getEnd() === typedefNode.getEnd(), ); const leftSibling = currentNodeIndex > 0 ? commentNode.getChildAt(currentNodeIndex - 1) : undefined; @@ -143,7 +147,7 @@ function findEndOfTextBetween(jsDocComment: JSDoc, from: number, to: number): nu const comment = jsDocComment.getText().substring(from - jsDocComment.getStart(), to - jsDocComment.getStart()); for (let i = comment.length; i > 0; i--) { - if(!/[*/\s]/g.test(comment.substring(i - 1, i))) { + if (!/[*/\s]/g.test(comment.substring(i - 1, i))) { return from + i; } } @@ -171,7 +175,7 @@ function createDeclaration(tag: JSDocTypedefTag): InterfaceDeclaration | TypeAli function createInterfaceForTypeLiteral( typeName: string, - typeLiteral: JSDocTypeLiteral + typeLiteral: JSDocTypeLiteral, ): InterfaceDeclaration | undefined { const propertySignatures = createSignatureFromTypeLiteral(typeLiteral); if (!some(propertySignatures)) return; @@ -187,7 +191,7 @@ function createInterfaceForTypeLiteral( function createTypeAliasForTypeExpression( typeName: string, - typeExpression: JSDocTypeExpression + typeExpression: JSDocTypeExpression, ): TypeAliasDeclaration | undefined { const typeReference = getSynthesizedDeepClone(typeExpression.type); if (!typeReference) return; @@ -196,7 +200,7 @@ function createTypeAliasForTypeExpression( /*modifiers*/ undefined, factory.createIdentifier(typeName), /*typeParameters*/ undefined, - typeReference + typeReference, ); } @@ -227,7 +231,7 @@ function createSignatureFromTypeLiteral(typeLiteral: JSDocTypeLiteral): Property /*modifiers*/ undefined, name, questionToken, - typeReference + typeReference, ); } }; @@ -242,7 +246,7 @@ function getPropertyName(tag: JSDocPropertyLikeTag): string | undefined { /** @internal */ export function getJSDocTypedefNodes(node: Node): readonly JSDocTag[] { if (hasJSDocNodes(node)) { - return flatMap(node.jsDoc, (doc) => doc.tags?.filter((tag) => isJSDocTypedefTag(tag))); + return flatMap(node.jsDoc, doc => doc.tags?.filter(tag => isJSDocTypedefTag(tag))); } return []; diff --git a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts index 466a8a9bcd719..3dbcb5e8f2180 100644 --- a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts +++ b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts @@ -29,24 +29,26 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], - getAllCodeActions: (context) => codeFixAll(context, errorCodes, (changes, diag) => { - const q = getQualifiedName(diag.file, diag.start); - if (q) { - doChange(changes, diag.file, q); - } - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const q = getQualifiedName(diag.file, diag.start); + if (q) { + doChange(changes, diag.file, q); + } + }), }); -function getQualifiedName(sourceFile: SourceFile, pos: number): QualifiedName & { left: Identifier } | undefined { +function getQualifiedName(sourceFile: SourceFile, pos: number): QualifiedName & { left: Identifier; } | undefined { const qualifiedName = findAncestor(getTokenAtPosition(sourceFile, pos), isQualifiedName)!; Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); - return isIdentifier(qualifiedName.left) ? qualifiedName as QualifiedName & { left: Identifier } : undefined; + return isIdentifier(qualifiedName.left) ? qualifiedName as QualifiedName & { left: Identifier; } : undefined; } function doChange(changeTracker: textChanges.ChangeTracker, sourceFile: SourceFile, qualifiedName: QualifiedName): void { const rightText = qualifiedName.right.text; const replacement = factory.createIndexedAccessTypeNode( factory.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), - factory.createLiteralTypeNode(factory.createStringLiteral(rightText))); + factory.createLiteralTypeNode(factory.createStringLiteral(rightText)), + ); changeTracker.replaceNode(sourceFile, qualifiedName, replacement); } diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index 96202931ae090..09d7a00d0c6c5 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -44,11 +44,15 @@ registerCodeFix({ createCodeFixActionWithoutFixAll( fixName, [createFileTextChanges(sourceFile.fileName, [ - createTextChange(sourceFile.checkJsDirective - ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) - : createTextSpan(0, 0), `// @ts-nocheck${newLineCharacter}`), + createTextChange( + sourceFile.checkJsDirective + ? createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : createTextSpan(0, 0), + `// @ts-nocheck${newLineCharacter}`, + ), ])], - Diagnostics.Disable_checking_for_this_file), + Diagnostics.Disable_checking_for_this_file, + ), ]; if (textChanges.isValidLocationToAddComment(sourceFile, span.start)) { diff --git a/src/services/codefixes/fixAddMissingConstraint.ts b/src/services/codefixes/fixAddMissingConstraint.ts index c5b2bd3573789..df99139e709c7 100644 --- a/src/services/codefixes/fixAddMissingConstraint.ts +++ b/src/services/codefixes/fixAddMissingConstraint.ts @@ -76,7 +76,7 @@ registerCodeFix({ return undefined; }); })); - } + }, }); interface Info { diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 5c9efb68258fe..90b718fe8437d 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -138,7 +138,7 @@ const errorCodes = [ Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2.code, Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more.code, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, - Diagnostics.Cannot_find_name_0.code + Diagnostics.Cannot_find_name_0.code, ]; enum InfoKind { @@ -216,10 +216,12 @@ registerCodeFix({ const supers = isTypeLiteralNode(declaration) ? undefined : getAllSupers(declaration, checker); for (const info of infos) { // If some superclass added this property, don't add it again. - if (supers?.some(superClassOrInterface => { - const superInfos = typeDeclToMembers.get(superClassOrInterface); - return !!superInfos && superInfos.some(({ token }) => token.text === info.token.text); - })) continue; + if ( + supers?.some(superClassOrInterface => { + const superInfos = typeDeclToMembers.get(superClassOrInterface); + return !!superInfos && superInfos.some(({ token }) => token.text === info.token.text); + }) + ) continue; const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info; // Always prefer to add a method declaration if possible. @@ -428,7 +430,8 @@ function addMissingMemberInJs(changeTracker: textChanges.ChangeTracker, sourceFi tokenName, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, - /*initializer*/ undefined); + /*initializer*/ undefined, + ); const lastProp = getNodeToInsertPropertyAfter(classDeclaration); if (lastProp) { @@ -521,11 +524,13 @@ function createAddIndexSignatureAction(context: CodeFixContext, sourceFile: Sour "x", /*questionToken*/ undefined, stringTypeNode, - /*initializer*/ undefined); + /*initializer*/ undefined, + ); const indexSignature = factory.createIndexSignature( /*modifiers*/ undefined, [indexingParameter], - typeNode); + typeNode, + ); const changes = textChanges.ChangeTracker.with(context, t => t.insertMemberAtStart(sourceFile, node, indexSignature)); // No fixId here because code-fix-all currently only works on adding individual named properties. @@ -581,15 +586,20 @@ function addEnumMemberDeclaration(changes: textChanges.ChangeTracker, checker: T }); const enumMember = factory.createEnumMember(token, hasStringInitializer ? factory.createStringLiteral(token.text) : undefined); - changes.replaceNode(parentDeclaration.getSourceFile(), parentDeclaration, factory.updateEnumDeclaration( + changes.replaceNode( + parentDeclaration.getSourceFile(), parentDeclaration, - parentDeclaration.modifiers, - parentDeclaration.name, - concatenate(parentDeclaration.members, singleElementArray(enumMember)) - ), { - leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude - }); + factory.updateEnumDeclaration( + parentDeclaration, + parentDeclaration.modifiers, + parentDeclaration.name, + concatenate(parentDeclaration.members, singleElementArray(enumMember)), + ), + { + leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude, + }, + ); } function addFunctionDeclaration(changes: textChanges.ChangeTracker, context: CodeFixContextBase, info: FunctionInfo | SignatureInfo) { @@ -640,7 +650,7 @@ function addObjectLiteralProperties(changes: textChanges.ChangeTracker, context: const options = { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude, - indentation: info.indentation + indentation: info.indentation, }; changes.replaceNode(context.sourceFile, info.parentDeclaration, factory.createObjectLiteralExpression([...info.parentDeclaration.properties, ...props], /*multiLine*/ true), options); importAdder.writeFixes(changes); @@ -703,8 +713,7 @@ function tryGetValueFromType(context: CodeFixContextBase, checker: TypeChecker, const signature = checker.getSignaturesOfType(type, SignatureKind.Call); if (signature === undefined) return createUndefined(); - const func = createSignatureDeclarationFromSignature(SyntaxKind.FunctionExpression, context, quotePreference, signature[0], - createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder) as FunctionExpression | undefined; + const func = createSignatureDeclarationFromSignature(SyntaxKind.FunctionExpression, context, quotePreference, signature[0], createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), /*name*/ undefined, /*modifiers*/ undefined, /*optional*/ undefined, /*enclosingDeclaration*/ enclosingDeclaration, importAdder) as FunctionExpression | undefined; return func ?? createUndefined(); } if (getObjectFlags(type) & ObjectFlags.Class) { @@ -747,8 +756,7 @@ function getUnmatchedAttributes(checker: TypeChecker, target: ScriptTarget, sour } } } - return filter(targetProps, targetProp => - isIdentifierText(targetProp.name, target, LanguageVariant.JSX) && !((targetProp.flags & SymbolFlags.Optional || getCheckFlags(targetProp) & CheckFlags.Partial) || seenNames.has(targetProp.escapedName))); + return filter(targetProps, targetProp => isIdentifierText(targetProp.name, target, LanguageVariant.JSX) && !((targetProp.flags & SymbolFlags.Optional || getCheckFlags(targetProp) & CheckFlags.Partial) || seenNames.has(targetProp.escapedName))); } function tryGetContainingMethodDeclaration(node: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode, callExpression: CallExpression) { diff --git a/src/services/codefixes/fixAddMissingNewOperator.ts b/src/services/codefixes/fixAddMissingNewOperator.ts index 32b17b39233d8..8a44e267fb5f7 100644 --- a/src/services/codefixes/fixAddMissingNewOperator.ts +++ b/src/services/codefixes/fixAddMissingNewOperator.ts @@ -26,8 +26,7 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Add_missing_new_operator_to_call, fixId, Diagnostics.Add_missing_new_operator_to_all_calls)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => - addMissingNewOperator(changes, context.sourceFile, diag)), + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => addMissingNewOperator(changes, context.sourceFile, diag)), }); function addMissingNewOperator(changes: textChanges.ChangeTracker, sourceFile: SourceFile, span: TextSpan): void { diff --git a/src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts b/src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts index 20e76fbb1bf23..830e76d60f9c8 100644 --- a/src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts +++ b/src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts @@ -27,8 +27,7 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Add_missing_typeof, fixId, Diagnostics.Add_missing_typeof)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => - doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start))), + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start))), }); function getImportTypeNode(sourceFile: SourceFile, pos: number): ImportTypeNode { diff --git a/src/services/codefixes/fixAddVoidToPromise.ts b/src/services/codefixes/fixAddVoidToPromise.ts index 4abb3cdedda2d..82114594c92fb 100644 --- a/src/services/codefixes/fixAddVoidToPromise.ts +++ b/src/services/codefixes/fixAddVoidToPromise.ts @@ -35,7 +35,7 @@ const fixName = "addVoidToPromise"; const fixId = "addVoidToPromise"; const errorCodes = [ Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code, - Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code + Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code, ]; registerCodeFix({ errorCodes, @@ -48,7 +48,7 @@ registerCodeFix({ }, getAllCodeActions(context: CodeFixAllContext) { return codeFixAll(context, errorCodes, (changes, diag) => makeChange(changes, diag.file, diag, context.program, new Set())); - } + }, }); function makeChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, span: TextSpan, program: Program, seen?: Set) { diff --git a/src/services/codefixes/fixAwaitInSyncFunction.ts b/src/services/codefixes/fixAwaitInSyncFunction.ts index ee1f5f73a4c31..e1f78e928cd00 100644 --- a/src/services/codefixes/fixAwaitInSyncFunction.ts +++ b/src/services/codefixes/fixAwaitInSyncFunction.ts @@ -31,7 +31,7 @@ const errorCodes = [ Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, - Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code + Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code, ]; registerCodeFix({ errorCodes, @@ -57,14 +57,16 @@ function getReturnType(expr: FunctionDeclaration | MethodDeclaration | FunctionE if (expr.type) { return expr.type; } - if (isVariableDeclaration(expr.parent) && + if ( + isVariableDeclaration(expr.parent) && expr.parent.type && - isFunctionTypeNode(expr.parent.type)) { + isFunctionTypeNode(expr.parent.type) + ) { return expr.parent.type.type; } } -function getNodes(sourceFile: SourceFile, start: number): { insertBefore: Node, returnType: TypeNode | undefined } | undefined { +function getNodes(sourceFile: SourceFile, start: number): { insertBefore: Node; returnType: TypeNode | undefined; } | undefined { const token = getTokenAtPosition(sourceFile, start); const containingFunction = getContainingFunction(token); if (!containingFunction) { @@ -90,15 +92,15 @@ function getNodes(sourceFile: SourceFile, start: number): { insertBefore: Node, return insertBefore && { insertBefore, - returnType: getReturnType(containingFunction) + returnType: getReturnType(containingFunction), }; } function doChange( changes: textChanges.ChangeTracker, sourceFile: SourceFile, - { insertBefore, returnType }: { insertBefore: Node, returnType: TypeNode | undefined }): void { - + { insertBefore, returnType }: { insertBefore: Node; returnType: TypeNode | undefined; }, +): void { if (returnType) { const entityName = getEntityNameFromTypeNode(returnType); if (!entityName || entityName.kind !== SyntaxKind.Identifier || entityName.text !== "Promise") { diff --git a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts index 80649e31bc5dd..44c14f724c126 100644 --- a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts +++ b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts @@ -33,8 +33,7 @@ registerCodeFix({ errorCodes, getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) { const { sourceFile, span } = context; - const changes = textChanges.ChangeTracker.with(context, t => - addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences)); + const changes = textChanges.ChangeTracker.with(context, t => addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences)); return changes.length === 0 ? undefined : [createCodeFixAction(fixId, changes, Diagnostics.Implement_inherited_abstract_class, fixId, Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index f91c49c9bece9..7c5e3652af32a 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -40,7 +40,7 @@ import { 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 + 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({ diff --git a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts index 02276f8d7a482..66032b9f315ee 100644 --- a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts +++ b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts @@ -55,7 +55,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, co changes.delete(sourceFile, superCall); } -function getNodes(sourceFile: SourceFile, pos: number): { readonly constructor: ConstructorDeclaration, readonly superCall: ExpressionStatement } | undefined { +function getNodes(sourceFile: SourceFile, pos: number): { readonly constructor: ConstructorDeclaration; readonly superCall: ExpressionStatement; } | undefined { const token = getTokenAtPosition(sourceFile, pos); if (token.kind !== SyntaxKind.ThisKeyword) return undefined; const constructor = getContainingFunction(token) as ConstructorDeclaration; @@ -65,10 +65,10 @@ function getNodes(sourceFile: SourceFile, pos: number): { readonly constructor: return superCall && !superCall.expression.arguments.some(arg => isPropertyAccessExpression(arg) && arg.expression === token) ? { constructor, superCall } : undefined; } -function findSuperCall(n: Node): ExpressionStatement & { expression: CallExpression } | undefined { +function findSuperCall(n: Node): ExpressionStatement & { expression: CallExpression; } | undefined { return isExpressionStatement(n) && isSuperCall(n.expression) - ? n as ExpressionStatement & { expression: CallExpression } + ? n as ExpressionStatement & { expression: CallExpression; } : isFunctionLike(n) - ? undefined - : forEachChild(n, findSuperCall); + ? undefined + : forEachChild(n, findSuperCall); } diff --git a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts index feee99da0d0cf..20e0cb3b35d9a 100644 --- a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts +++ b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts @@ -26,8 +26,7 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Add_missing_super_call, fixId, Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => - doChange(changes, context.sourceFile, getNode(diag.file, diag.start))), + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, context.sourceFile, getNode(diag.file, diag.start))), }); function getNode(sourceFile: SourceFile, pos: number): ConstructorDeclaration { diff --git a/src/services/codefixes/fixEnableJsxFlag.ts b/src/services/codefixes/fixEnableJsxFlag.ts index 4870e021120f7..6d00ac88e072b 100644 --- a/src/services/codefixes/fixEnableJsxFlag.ts +++ b/src/services/codefixes/fixEnableJsxFlag.ts @@ -21,11 +21,9 @@ registerCodeFix({ return undefined; } - const changes = textChanges.ChangeTracker.with(context, changeTracker => - doChange(changeTracker, configFile) - ); + const changes = textChanges.ChangeTracker.with(context, changeTracker => doChange(changeTracker, configFile)); return [ - createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) + createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file), ]; }, fixIds: [fixID], @@ -37,7 +35,7 @@ registerCodeFix({ } doChange(changes, configFile); - }) + }), }); function doChange(changeTracker: textChanges.ChangeTracker, configFile: TsConfigSourceFile) { diff --git a/src/services/codefixes/fixExpectedComma.ts b/src/services/codefixes/fixExpectedComma.ts index ed571ab443352..352760d482a28 100644 --- a/src/services/codefixes/fixExpectedComma.ts +++ b/src/services/codefixes/fixExpectedComma.ts @@ -33,17 +33,20 @@ registerCodeFix({ changes, [Diagnostics.Change_0_to_1, ";", ","], fixId, - [Diagnostics.Change_0_to_1, ";", ","] + [Diagnostics.Change_0_to_1, ";", ","], )]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(diag.file, diag.start, diag.code); - if (info) doChange(changes, context.sourceFile, info); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file, diag.start, diag.code); + if (info) doChange(changes, context.sourceFile, info); + }), }); -interface Info { readonly node: Node; } +interface Info { + readonly node: Node; +} function getInfo(sourceFile: SourceFile, pos: number, _: number): Info | undefined { const node = getTokenAtPosition(sourceFile, pos); @@ -51,7 +54,7 @@ function getInfo(sourceFile: SourceFile, pos: number, _: number): Info | undefin return (node.kind === SyntaxKind.SemicolonToken && node.parent && (isObjectLiteralExpression(node.parent) || - isArrayLiteralExpression(node.parent))) ? { node } : undefined; + isArrayLiteralExpression(node.parent))) ? { node } : undefined; } function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, { node }: Info): void { diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index 7beffebd59986..65595a78b8b6a 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -29,10 +29,11 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Change_extends_to_implements, fixId, Diagnostics.Change_all_extended_interfaces_to_implements)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const nodes = getNodes(diag.file, diag.start); - if (nodes) doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const nodes = getNodes(diag.file, diag.start); + if (nodes) doChanges(changes, diag.file, nodes.extendsToken, nodes.heritageClauses); + }), }); function getNodes(sourceFile: SourceFile, pos: number) { @@ -46,10 +47,11 @@ function doChanges(changes: textChanges.ChangeTracker, sourceFile: SourceFile, e changes.replaceNode(sourceFile, extendsToken, factory.createToken(SyntaxKind.ImplementsKeyword)); // If there is already an implements clause, replace the implements keyword with a comma. - if (heritageClauses.length === 2 && + if ( + heritageClauses.length === 2 && heritageClauses[0].token === SyntaxKind.ExtendsKeyword && - heritageClauses[1].token === SyntaxKind.ImplementsKeyword) { - + heritageClauses[1].token === SyntaxKind.ImplementsKeyword + ) { const implementsToken = heritageClauses[1].getFirstToken()!; const implementsFullStart = implementsToken.getFullStart(); changes.replaceRange(sourceFile, { pos: implementsFullStart, end: implementsFullStart }, factory.createToken(SyntaxKind.CommaToken)); diff --git a/src/services/codefixes/fixForgottenThisPropertyAccess.ts b/src/services/codefixes/fixForgottenThisPropertyAccess.ts index ae8d0cd294f0b..1bd0de54296ee 100644 --- a/src/services/codefixes/fixForgottenThisPropertyAccess.ts +++ b/src/services/codefixes/fixForgottenThisPropertyAccess.ts @@ -36,10 +36,11 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, [Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(diag.file, diag.start, diag.code); - if (info) doChange(changes, context.sourceFile, info); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file, diag.start, diag.code); + if (info) doChange(changes, context.sourceFile, info); + }), }); interface Info { diff --git a/src/services/codefixes/fixImplicitThis.ts b/src/services/codefixes/fixImplicitThis.ts index 86c8adad40bd3..9a867574cac10 100644 --- a/src/services/codefixes/fixImplicitThis.ts +++ b/src/services/codefixes/fixImplicitThis.ts @@ -37,9 +37,10 @@ registerCodeFix({ return diagnostic ? [createCodeFixAction(fixId, changes, diagnostic, fixId, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - doChange(changes, diag.file, diag.start, context.program.getTypeChecker()); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + doChange(changes, diag.file, diag.start, context.program.getTypeChecker()); + }), }); function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, pos: number, checker: TypeChecker): DiagnosticOrDiagnosticAndArguments | undefined { diff --git a/src/services/codefixes/fixImportNonExportedMember.ts b/src/services/codefixes/fixImportNonExportedMember.ts index ba25afcbf5505..51202cc8c32e2 100644 --- a/src/services/codefixes/fixImportNonExportedMember.ts +++ b/src/services/codefixes/fixImportNonExportedMember.ts @@ -91,7 +91,7 @@ registerCodeFix({ } }); })); - } + }, }); interface ModuleExports { @@ -167,24 +167,31 @@ function doChanges(changes: textChanges.ChangeTracker, program: Program, sourceF } function tryGetExportDeclaration(sourceFile: SourceFile, isTypeOnly: boolean) { - const predicate = (node: Node): node is ExportDeclaration => - isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); + const predicate = (node: Node): node is ExportDeclaration => isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); return findLast(sourceFile.statements, predicate); } function updateExport(changes: textChanges.ChangeTracker, program: Program, sourceFile: SourceFile, node: ExportDeclaration, names: ExportName[]) { const namedExports = node.exportClause && isNamedExports(node.exportClause) ? node.exportClause.elements : factory.createNodeArray([]); const allowTypeModifier = !node.isTypeOnly && !!(getIsolatedModules(program.getCompilerOptions()) || find(namedExports, e => e.isTypeOnly)); - changes.replaceNode(sourceFile, node, - factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, + changes.replaceNode( + sourceFile, + node, + factory.updateExportDeclaration( + node, + node.modifiers, + node.isTypeOnly, factory.createNamedExports( - factory.createNodeArray([...namedExports, ...createExportSpecifiers(names, allowTypeModifier)], /*hasTrailingComma*/ namedExports.hasTrailingComma)), node.moduleSpecifier, node.assertClause)); + factory.createNodeArray([...namedExports, ...createExportSpecifiers(names, allowTypeModifier)], /*hasTrailingComma*/ namedExports.hasTrailingComma), + ), + node.moduleSpecifier, + node.assertClause, + ), + ); } function createExport(changes: textChanges.ChangeTracker, program: Program, sourceFile: SourceFile, names: ExportName[]) { - changes.insertNodeAtEndOfScope(sourceFile, sourceFile, - factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, - factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ getIsolatedModules(program.getCompilerOptions()))), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined)); + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ getIsolatedModules(program.getCompilerOptions()))), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined)); } function createExportSpecifiers(names: ExportName[], allowTypeModifier: boolean) { diff --git a/src/services/codefixes/fixIncorrectNamedTupleSyntax.ts b/src/services/codefixes/fixIncorrectNamedTupleSyntax.ts index f7e8345b217f0..4c831bac51529 100644 --- a/src/services/codefixes/fixIncorrectNamedTupleSyntax.ts +++ b/src/services/codefixes/fixIncorrectNamedTupleSyntax.ts @@ -19,7 +19,7 @@ import { const fixId = "fixIncorrectNamedTupleSyntax"; const errorCodes = [ Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code, - Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code + Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code, ]; registerCodeFix({ @@ -30,7 +30,7 @@ registerCodeFix({ const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, namedTupleMember)); return [createCodeFixAction(fixId, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels)]; }, - fixIds: [fixId] + fixIds: [fixId], }); function getNamedTupleMember(sourceFile: SourceFile, pos: number) { @@ -58,7 +58,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, na namedTupleMember.dotDotDotToken || (sawRest ? factory.createToken(SyntaxKind.DotDotDotToken) : undefined), namedTupleMember.name, namedTupleMember.questionToken || (sawOptional ? factory.createToken(SyntaxKind.QuestionToken) : undefined), - unwrappedType + unwrappedType, ); if (updated === namedTupleMember) { return; diff --git a/src/services/codefixes/fixInvalidImportSyntax.ts b/src/services/codefixes/fixInvalidImportSyntax.ts index bae3f2d2c0f16..6301bf0ba6e16 100644 --- a/src/services/codefixes/fixInvalidImportSyntax.ts +++ b/src/services/codefixes/fixInvalidImportSyntax.ts @@ -43,12 +43,17 @@ function getCodeFixesForImportDeclaration(context: CodeFixContext, node: ImportD if (getEmitModuleKind(opts) === ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); - variations.push(createAction(context, sourceFile, node, factory.createImportEqualsDeclaration( - /*modifiers*/ undefined, - /*isTypeOnly*/ false, - namespace.name, - factory.createExternalModuleReference(node.moduleSpecifier) - ))); + variations.push(createAction( + context, + sourceFile, + node, + factory.createImportEqualsDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + namespace.name, + factory.createExternalModuleReference(node.moduleSpecifier), + ), + )); } return variations; @@ -64,7 +69,7 @@ registerCodeFix({ Diagnostics.This_expression_is_not_callable.code, Diagnostics.This_expression_is_not_constructable.code, ], - getCodeActions: getActionsForUsageOfInvalidImport + getCodeActions: getActionsForUsageOfInvalidImport, }); function getActionsForUsageOfInvalidImport(context: CodeFixContext): CodeFixAction[] | undefined { @@ -93,7 +98,7 @@ registerCodeFix({ Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code, ], - getCodeActions: getActionsForInvalidImportLocation + getCodeActions: getActionsForInvalidImportLocation, }); function getActionsForInvalidImportLocation(context: CodeFixContext): CodeFixAction[] | undefined { diff --git a/src/services/codefixes/fixInvalidJsxCharacters.ts b/src/services/codefixes/fixInvalidJsxCharacters.ts index aea34c0c42cef..744354c7fb87b 100644 --- a/src/services/codefixes/fixInvalidJsxCharacters.ts +++ b/src/services/codefixes/fixInvalidJsxCharacters.ts @@ -17,7 +17,7 @@ const fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity"; const errorCodes = [ Diagnostics.Unexpected_token_Did_you_mean_or_gt.code, - Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code + Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code, ]; registerCodeFix({ @@ -30,12 +30,12 @@ registerCodeFix({ return [ createCodeFixAction(fixIdExpression, changeToExpression, Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, Diagnostics.Wrap_all_invalid_characters_in_an_expression_container), - createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code) + createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code), ]; }, getAllCodeActions(context) { return codeFixAll(context, errorCodes, (changes, diagnostic) => doChange(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); - } + }, }); const htmlEntity = { diff --git a/src/services/codefixes/fixJSDocTypes.ts b/src/services/codefixes/fixJSDocTypes.ts index 3a50e7579675c..2a35ba3fdb3a9 100644 --- a/src/services/codefixes/fixJSDocTypes.ts +++ b/src/services/codefixes/fixJSDocTypes.ts @@ -78,25 +78,21 @@ registerCodeFix({ const fixedType = typeNode.kind === SyntaxKind.JSDocNullableType && fixId === fixIdNullable ? checker.getNullableType(type, TypeFlags.Undefined) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); - } + }, }); function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, oldTypeNode: TypeNode, newType: Type, checker: TypeChecker): void { changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)!); // TODO: GH#18217 } -function getInfo(sourceFile: SourceFile, pos: number, checker: TypeChecker): { readonly typeNode: TypeNode, readonly type: Type } | undefined { +function getInfo(sourceFile: SourceFile, pos: number, checker: TypeChecker): { readonly typeNode: TypeNode; readonly type: Type; } | undefined { const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer); const typeNode = decl && decl.type; return typeNode && { typeNode, type: getType(checker, typeNode) }; } // TODO: GH#19856 Node & { type: TypeNode } -type TypeContainer = - | AsExpression | CallSignatureDeclaration | ConstructSignatureDeclaration | FunctionDeclaration - | GetAccessorDeclaration | IndexSignatureDeclaration | MappedTypeNode | MethodDeclaration - | MethodSignature | ParameterDeclaration | PropertyDeclaration | PropertySignature | SetAccessorDeclaration - | TypeAliasDeclaration | TypeAssertion | VariableDeclaration; +type TypeContainer = AsExpression | CallSignatureDeclaration | ConstructSignatureDeclaration | FunctionDeclaration | GetAccessorDeclaration | IndexSignatureDeclaration | MappedTypeNode | MethodDeclaration | MethodSignature | ParameterDeclaration | PropertyDeclaration | PropertySignature | SetAccessorDeclaration | TypeAliasDeclaration | TypeAssertion | VariableDeclaration; function isTypeContainer(node: Node): node is TypeContainer { // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments @@ -130,7 +126,8 @@ function getType(checker: TypeChecker, node: TypeNode) { return type; } return checker.getUnionType( - append([type, checker.getUndefinedType()], node.postfix ? undefined : checker.getNullType())); + append([type, checker.getUndefinedType()], node.postfix ? undefined : checker.getNullType()), + ); } return checker.getTypeFromTypeNode(node); } diff --git a/src/services/codefixes/fixMissingCallParentheses.ts b/src/services/codefixes/fixMissingCallParentheses.ts index 4fcc89c87fcc0..5a254bc1392dc 100644 --- a/src/services/codefixes/fixMissingCallParentheses.ts +++ b/src/services/codefixes/fixMissingCallParentheses.ts @@ -31,14 +31,15 @@ registerCodeFix({ const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, callName)); return [createCodeFixAction(fixId, changes, Diagnostics.Add_missing_call_parentheses, fixId, Diagnostics.Add_all_missing_call_parentheses)]; }, - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const callName = getCallName(diag.file, diag.start); - if (callName) doChange(changes, diag.file, callName); - }) + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const callName = getCallName(diag.file, diag.start); + if (callName) doChange(changes, diag.file, callName); + }), }); function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, name: Identifier | PrivateIdentifier): void { - changes.replaceNodeWithText(sourceFile, name, `${ name.text }()`); + changes.replaceNodeWithText(sourceFile, name, `${name.text}()`); } function getCallName(sourceFile: SourceFile, start: number): Identifier | PrivateIdentifier | undefined { diff --git a/src/services/codefixes/fixModuleAndTargetOptions.ts b/src/services/codefixes/fixModuleAndTargetOptions.ts index 0cc3e489ab25d..7446e4babe1d2 100644 --- a/src/services/codefixes/fixModuleAndTargetOptions.ts +++ b/src/services/codefixes/fixModuleAndTargetOptions.ts @@ -60,5 +60,5 @@ registerCodeFix({ } return codeFixes.length ? codeFixes : undefined; - } + }, }); diff --git a/src/services/codefixes/fixNaNEquality.ts b/src/services/codefixes/fixNaNEquality.ts index 4370bd0d1c584..53db6b1b8b8d6 100644 --- a/src/services/codefixes/fixNaNEquality.ts +++ b/src/services/codefixes/fixNaNEquality.ts @@ -46,7 +46,7 @@ registerCodeFix({ doChange(changes, diag.file, info.arg, info.expression); } }); - } + }, }); interface Info { @@ -73,11 +73,17 @@ function getInfo(program: Program, sourceFile: SourceFile, span: TextSpan): Info function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, arg: Expression, expression: BinaryExpression) { const callExpression = factory.createCallExpression( - factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), /*typeArguments*/ undefined, [arg]); - const operator = expression.operatorToken.kind ; - changes.replaceNode(sourceFile, expression, + factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), + /*typeArguments*/ undefined, + [arg], + ); + const operator = expression.operatorToken.kind; + changes.replaceNode( + sourceFile, + expression, operator === SyntaxKind.ExclamationEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsToken - ? factory.createPrefixUnaryExpression(SyntaxKind.ExclamationToken, callExpression) : callExpression); + ? factory.createPrefixUnaryExpression(SyntaxKind.ExclamationToken, callExpression) : callExpression, + ); } function getSuggestion(messageText: string | DiagnosticMessageChain) { diff --git a/src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts b/src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts index 7a35126032924..3ae9b9045e223 100644 --- a/src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts +++ b/src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts @@ -20,7 +20,7 @@ import { const fixId = "fixNoPropertyAccessFromIndexSignature"; const errorCodes = [ - Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code + Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code, ]; registerCodeFix({ @@ -32,8 +32,7 @@ registerCodeFix({ const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, property, preferences)); return [createCodeFixAction(fixId, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId, Diagnostics.Use_element_access_for_all_undeclared_properties)]; }, - getAllCodeActions: context => - codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, getPropertyAccessExpression(diag.file, diag.start), context.preferences)) + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, getPropertyAccessExpression(diag.file, diag.start), context.preferences)), }); function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, node: PropertyAccessExpression, preferences: UserPreferences): void { @@ -44,7 +43,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, no node, isPropertyAccessChain(node) ? factory.createElementAccessChain(node.expression, node.questionDotToken, argumentsExpression) : - factory.createElementAccessExpression(node.expression, argumentsExpression) + factory.createElementAccessExpression(node.expression, argumentsExpression), ); } diff --git a/src/services/codefixes/fixOverrideModifier.ts b/src/services/codefixes/fixOverrideModifier.ts index f76a8420e0699..2c3f8242a7ff5 100644 --- a/src/services/codefixes/fixOverrideModifier.ts +++ b/src/services/codefixes/fixOverrideModifier.ts @@ -78,7 +78,7 @@ const errorCodeFixIdMap: Record = { [Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code]: { descriptions: Diagnostics.Add_override_modifier, fixId: fixAddOverrideId, - fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers + fixAllDescriptions: Diagnostics.Add_all_missing_override_modifiers, }, // case #2: [Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code]: { @@ -89,7 +89,7 @@ const errorCodeFixIdMap: Record = { [Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code]: { descriptions: Diagnostics.Remove_override_modifier, fixId: fixRemoveOverrideId, - fixAllDescriptions: Diagnostics.Remove_override_modifier + fixAllDescriptions: Diagnostics.Remove_override_modifier, }, // case #3: [Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code]: { @@ -118,7 +118,7 @@ const errorCodeFixIdMap: Record = { descriptions: Diagnostics.Remove_override_modifier, fixId: fixRemoveOverrideId, fixAllDescriptions: Diagnostics.Remove_all_unnecessary_override_modifiers, - } + }, }; registerCodeFix({ @@ -133,7 +133,7 @@ registerCodeFix({ const changes = textChanges.ChangeTracker.with(context, changes => dispatchChanges(changes, context, errorCode, span.start)); return [ - createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions) + createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions), ]; }, fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], @@ -146,14 +146,15 @@ registerCodeFix({ } dispatchChanges(changes, context, code, start); - }) + }), }); function dispatchChanges( changeTracker: textChanges.ChangeTracker, context: CodeFixContext | CodeFixAllContext, errorCode: number, - pos: number) { + pos: number, +) { switch (errorCode) { case Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: case Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: @@ -227,4 +228,3 @@ function findContainerClassElementLike(sourceFile: SourceFile, pos: number) { Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); return classElement; } - diff --git a/src/services/codefixes/fixPropertyAssignment.ts b/src/services/codefixes/fixPropertyAssignment.ts index 2f1ef5a198044..d75fb8b365ac3 100644 --- a/src/services/codefixes/fixPropertyAssignment.ts +++ b/src/services/codefixes/fixPropertyAssignment.ts @@ -17,7 +17,7 @@ import { const fixId = "fixPropertyAssignment"; const errorCodes = [ - Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code + Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, ]; registerCodeFix({ @@ -29,8 +29,7 @@ registerCodeFix({ const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, property)); return [createCodeFixAction(fixId, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])]; }, - getAllCodeActions: context => - codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, getProperty(diag.file, diag.start))) + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, getProperty(diag.file, diag.start))), }); function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, node: ShorthandPropertyAssignment): void { diff --git a/src/services/codefixes/fixPropertyOverrideAccessor.ts b/src/services/codefixes/fixPropertyOverrideAccessor.ts index 954a90ba6f34a..4ee42dbbeee1e 100644 --- a/src/services/codefixes/fixPropertyOverrideAccessor.ts +++ b/src/services/codefixes/fixPropertyOverrideAccessor.ts @@ -35,14 +35,15 @@ registerCodeFix({ }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const edits = doChange(diag.file, diag.start, diag.length, diag.code, context); - if (edits) { - for (const edit of edits) { - changes.pushRaw(context.sourceFile, edit); + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const edits = doChange(diag.file, diag.start, diag.length, diag.code, context); + if (edits) { + for (const edit of edits) { + changes.pushRaw(context.sourceFile, edit); + } } - } - }), + }), }); function doChange(file: SourceFile, start: number, length: number, code: number, context: CodeFixContext | CodeFixAllContext) { diff --git a/src/services/codefixes/fixReturnTypeInAsyncFunction.ts b/src/services/codefixes/fixReturnTypeInAsyncFunction.ts index a7071d6e143f4..8b33ec0c8cede 100644 --- a/src/services/codefixes/fixReturnTypeInAsyncFunction.ts +++ b/src/services/codefixes/fixReturnTypeInAsyncFunction.ts @@ -42,17 +42,20 @@ registerCodeFix({ const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info; const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, returnTypeNode, promisedTypeNode)); return [createCodeFixAction( - fixId, changes, - [Diagnostics.Replace_0_with_Promise_1, - checker.typeToString(returnType), checker.typeToString(promisedType)], - fixId, Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions)]; + fixId, + changes, + [Diagnostics.Replace_0_with_Promise_1, checker.typeToString(returnType), checker.typeToString(promisedType)], + fixId, + Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions, + )]; }, - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(diag.file, context.program.getTypeChecker(), diag.start); - if (info) { - doChange(changes, diag.file, info.returnTypeNode, info.promisedTypeNode); - } - }) + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file, context.program.getTypeChecker(), diag.start); + if (info) { + doChange(changes, diag.file, info.returnTypeNode, info.promisedTypeNode); + } + }), }); function getInfo(sourceFile: SourceFile, checker: TypeChecker, pos: number): Info | undefined { diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts index 8e3574aa60cde..222851cb99f96 100644 --- a/src/services/codefixes/fixSpelling.ts +++ b/src/services/codefixes/fixSpelling.ts @@ -75,24 +75,28 @@ registerCodeFix({ return [createCodeFixAction("spelling", changes, [Diagnostics.Change_spelling_to_0, symbolName(suggestedSymbol)], fixId, Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(diag.file, diag.start, context, diag.code); - const target = getEmitScriptTarget(context.host.getCompilationSettings()); - if (info) doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file, diag.start, context, diag.code); + const target = getEmitScriptTarget(context.host.getCompilationSettings()); + if (info) doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target); + }), }); -function getInfo(sourceFile: SourceFile, pos: number, context: CodeFixContextBase, errorCode: number): { node: Node, suggestedSymbol: Symbol } | undefined { +function getInfo(sourceFile: SourceFile, pos: number, context: CodeFixContextBase, errorCode: number): { node: Node; suggestedSymbol: Symbol; } | undefined { // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ const node = getTokenAtPosition(sourceFile, pos); const parent = node.parent; // Only fix spelling for No_overload_matches_this_call emitted on the React class component - if (( - errorCode === Diagnostics.No_overload_matches_this_call.code || - errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && - !isJsxAttribute(parent)) return undefined; + if ( + ( + errorCode === Diagnostics.No_overload_matches_this_call.code || + errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code + ) && + !isJsxAttribute(parent) + ) return undefined; const checker = context.program.getTypeChecker(); let suggestedSymbol: Symbol | undefined; diff --git a/src/services/codefixes/fixStrictClassInitialization.ts b/src/services/codefixes/fixStrictClassInitialization.ts index fa78042e08217..d42e858964a1b 100644 --- a/src/services/codefixes/fixStrictClassInitialization.ts +++ b/src/services/codefixes/fixStrictClassInitialization.ts @@ -108,7 +108,7 @@ function addDefiniteAssignmentAssertion(changeTracker: textChanges.ChangeTracker propertyDeclaration.name, factory.createToken(SyntaxKind.ExclamationToken), propertyDeclaration.type, - propertyDeclaration.initializer + propertyDeclaration.initializer, ); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } @@ -149,7 +149,7 @@ function addInitializer(changeTracker: textChanges.ChangeTracker, propertyDeclar propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, - initializer + initializer, ); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } diff --git a/src/services/codefixes/fixUnmatchedParameter.ts b/src/services/codefixes/fixUnmatchedParameter.ts index 267e207a6ccac..bba50c32e589f 100644 --- a/src/services/codefixes/fixUnmatchedParameter.ts +++ b/src/services/codefixes/fixUnmatchedParameter.ts @@ -68,18 +68,17 @@ registerCodeFix({ } }); })); - } + }, }); function getDeleteAction(context: CodeFixContext, { name, jsDocHost, jsDocParameterTag }: Info) { - const changes = textChanges.ChangeTracker.with(context, changeTracker => - changeTracker.filterJSDocTags(context.sourceFile, jsDocHost, t => t !== jsDocParameterTag)); + const changes = textChanges.ChangeTracker.with(context, changeTracker => changeTracker.filterJSDocTags(context.sourceFile, jsDocHost, t => t !== jsDocParameterTag)); return createCodeFixAction( deleteUnmatchedParameter, changes, [Diagnostics.Delete_unused_param_tag_0, name.getText(context.sourceFile)], deleteUnmatchedParameter, - Diagnostics.Delete_all_unused_param_tags + Diagnostics.Delete_all_unused_param_tags, ); } @@ -96,8 +95,7 @@ function getRenameAction(context: CodeFixContext, { name, jsDocHost, signature, } // @todo - match to all available names instead to the first parameter name // @see /codeFixRenameUnmatchedParameter3.ts - const parameterName = firstDefined(signature.parameters, p => - isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : undefined); + const parameterName = firstDefined(signature.parameters, p => isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : undefined); if (parameterName === undefined) return undefined; const newJSDocParameterTag = factory.updateJSDocParameterTag( @@ -107,10 +105,9 @@ function getRenameAction(context: CodeFixContext, { name, jsDocHost, signature, jsDocParameterTag.isBracketed, jsDocParameterTag.typeExpression, jsDocParameterTag.isNameFirst, - jsDocParameterTag.comment + jsDocParameterTag.comment, ); - const changes = textChanges.ChangeTracker.with(context, changeTracker => - changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, t => t === jsDocParameterTag ? newJSDocParameterTag : t))); + const changes = textChanges.ChangeTracker.with(context, changeTracker => changeTracker.replaceJSDocComment(sourceFile, jsDocHost, map(tags, t => t === jsDocParameterTag ? newJSDocParameterTag : t))); return createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]); } diff --git a/src/services/codefixes/fixUnreachableCode.ts b/src/services/codefixes/fixUnreachableCode.ts index 17afabda71a93..61c363c3fc868 100644 --- a/src/services/codefixes/fixUnreachableCode.ts +++ b/src/services/codefixes/fixUnreachableCode.ts @@ -43,7 +43,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, st tokenKind: Debug.formatSyntaxKind(token.kind), errorCode, start, - length + length, }); Debug.fail("Token and statement should start at the same point. " + logData); } diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 4da1d6ce22d9c..494721afb5ce5 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -112,23 +112,20 @@ registerCodeFix({ const elements = token.parent.elements; const diagnostic: [DiagnosticMessage, string] = [ elements.length > 1 ? Diagnostics.Remove_unused_declarations_for_Colon_0 : Diagnostics.Remove_unused_declaration_for_Colon_0, - map(elements, e => e.getText(sourceFile)).join(", ") + map(elements, e => e.getText(sourceFile)).join(", "), ]; return [ - createDeleteFix(textChanges.ChangeTracker.with(context, t => - deleteDestructuringElements(t, sourceFile, token.parent as ObjectBindingPattern | ArrayBindingPattern)), diagnostic) + createDeleteFix(textChanges.ChangeTracker.with(context, t => deleteDestructuringElements(t, sourceFile, token.parent as ObjectBindingPattern | ArrayBindingPattern)), diagnostic), ]; } return [ - createDeleteFix(textChanges.ChangeTracker.with(context, t => - deleteDestructuring(context, t, sourceFile, token.parent as ObjectBindingPattern | ArrayBindingPattern)), Diagnostics.Remove_unused_destructuring_declaration), + createDeleteFix(textChanges.ChangeTracker.with(context, t => deleteDestructuring(context, t, sourceFile, token.parent as ObjectBindingPattern | ArrayBindingPattern)), Diagnostics.Remove_unused_destructuring_declaration), ]; } if (canDeleteEntireVariableStatement(sourceFile, token)) { return [ - createDeleteFix(textChanges.ChangeTracker.with(context, t => - deleteEntireVariableStatement(t, sourceFile, token.parent as VariableDeclarationList)), Diagnostics.Remove_variable_statement) + createDeleteFix(textChanges.ChangeTracker.with(context, t => deleteEntireVariableStatement(t, sourceFile, token.parent as VariableDeclarationList)), Diagnostics.Remove_variable_statement), ]; } @@ -139,8 +136,7 @@ registerCodeFix({ result.push(createCodeFixAction(fixName, changes, [Diagnostics.Replace_infer_0_with_unknown, name], fixIdInfer, Diagnostics.Replace_all_unused_infer_with_unknown)); } else { - const deletion = textChanges.ChangeTracker.with(context, t => - tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ false)); + const deletion = textChanges.ChangeTracker.with(context, t => tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ false)); if (deletion.length) { const name = isComputedPropertyName(token.parent) ? token.parent : token; result.push(createDeleteFix(deletion, [Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)])); @@ -280,7 +276,7 @@ function tryPrefixDeclaration(changes: textChanges.ChangeTracker, errorCode: num if (isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, factory.createIdentifier(`_${token.text}`)); if (isParameter(token.parent)) { - getJSDocParameterTags(token.parent).forEach((tag) => { + getJSDocParameterTags(token.parent).forEach(tag => { if (isIdentifier(tag.name)) { changes.replaceNode(sourceFile, tag.name, factory.createIdentifier(`_${tag.name.text}`)); } @@ -338,10 +334,13 @@ function tryDeleteParameter( sourceFiles: readonly SourceFile[], program: Program, cancellationToken: CancellationToken, - isFixAll = false): void { + isFixAll = false, +): void { if (mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program, cancellationToken, isFixAll)) { - if (parameter.modifiers && parameter.modifiers.length > 0 && - (!isIdentifier(parameter.name) || FindAllReferences.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile))) { + if ( + parameter.modifiers && parameter.modifiers.length > 0 && + (!isIdentifier(parameter.name) || FindAllReferences.Core.isSymbolReferencedInFile(parameter.name, checker, sourceFile)) + ) { for (const modifier of parameter.modifiers) { if (isModifier(modifier)) { changes.deleteModifier(sourceFile, modifier); @@ -416,8 +415,7 @@ function mayDeleteParameter(checker: TypeChecker, sourceFile: SourceFile, parame } function isCallbackLike(checker: TypeChecker, sourceFile: SourceFile, name: Identifier): boolean { - return !!FindAllReferences.Core.eachSymbolReferenceInFile(name, checker, sourceFile, reference => - isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0); + return !!FindAllReferences.Core.eachSymbolReferenceInFile(name, checker, sourceFile, reference => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0); } function isLastParameter(func: FunctionLikeDeclaration, parameter: ParameterDeclaration, isFixAll: boolean): boolean { diff --git a/src/services/codefixes/generateAccessors.ts b/src/services/codefixes/generateAccessors.ts index 772abe45614af..fe4af3faca1c1 100644 --- a/src/services/codefixes/generateAccessors.ts +++ b/src/services/codefixes/generateAccessors.ts @@ -177,19 +177,19 @@ export function getAccessorConvertiblePropertyAtPosition(file: SourceFile, progr if (!declaration || (!(nodeOverlapsWithStartEnd(declaration.name, file, start, end) || cursorRequest))) { return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_property_for_which_to_generate_accessor) + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_property_for_which_to_generate_accessor), }; } if (!isConvertibleName(declaration.name)) { return { - error: getLocaleSpecificMessage(Diagnostics.Name_is_not_valid) + error: getLocaleSpecificMessage(Diagnostics.Name_is_not_valid), }; } if (((getEffectiveModifierFlags(declaration) & ModifierFlags.Modifier) | meaning) !== meaning) { return { - error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_property_with_modifier) + error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_property_with_modifier), }; } @@ -206,7 +206,7 @@ export function getAccessorConvertiblePropertyAtPosition(file: SourceFile, progr declaration, fieldName, accessorName, - renameAccessor: startWithUnderscore + renameAccessor: startWithUnderscore, }; } @@ -218,9 +218,9 @@ function generateGetAccessor(fieldName: AcceptedNameType, accessorName: Accepted type, factory.createBlock([ factory.createReturnStatement( - createAccessorAccessExpression(fieldName, isStatic, container) - ) - ], /*multiLine*/ true) + createAccessorAccessExpression(fieldName, isStatic, container), + ), + ], /*multiLine*/ true), ); } @@ -233,16 +233,16 @@ function generateSetAccessor(fieldName: AcceptedNameType, accessorName: Accepted /*dotDotDotToken*/ undefined, factory.createIdentifier("value"), /*questionToken*/ undefined, - type + type, )], factory.createBlock([ factory.createExpressionStatement( factory.createAssignment( createAccessorAccessExpression(fieldName, isStatic, container), - factory.createIdentifier("value") - ) - ) - ], /*multiLine*/ true) + factory.createIdentifier("value"), + ), + ), + ], /*multiLine*/ true), ); } @@ -253,7 +253,7 @@ function updatePropertyDeclaration(changeTracker: textChanges.ChangeTracker, fil fieldName, declaration.questionToken || declaration.exclamationToken, type, - declaration.initializer + declaration.initializer, ); changeTracker.replaceNode(file, declaration, property); } @@ -278,8 +278,7 @@ function updateFieldDeclaration(changeTracker: textChanges.ChangeTracker, file: updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); } else { - changeTracker.replaceNode(file, declaration, - factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, cast(fieldName, isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + changeTracker.replaceNode(file, declaration, factory.updateParameterDeclaration(declaration, modifiers, declaration.dotDotDotToken, cast(fieldName, isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); } } @@ -292,11 +291,13 @@ function insertAccessor(changeTracker: textChanges.ChangeTracker, file: SourceFi function updateReadonlyPropertyInitializerStatementConstructor(changeTracker: textChanges.ChangeTracker, file: SourceFile, constructor: ConstructorDeclaration, fieldName: string, originalName: string) { if (!constructor.body) return; constructor.body.forEachChild(function recur(node) { - if (isElementAccessExpression(node) && + if ( + isElementAccessExpression(node) && node.expression.kind === SyntaxKind.ThisKeyword && isStringLiteral(node.argumentExpression) && node.argumentExpression.text === originalName && - isWriteAccess(node)) { + isWriteAccess(node) + ) { changeTracker.replaceNode(file, node.argumentExpression, factory.createStringLiteral(fieldName)); } if (isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.ThisKeyword && node.name.text === originalName && isWriteAccess(node)) { diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 1116d70c19ccf..804e87040f48b 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -112,7 +112,9 @@ import { visitNode, visitNodes, } from "../_namespaces/ts"; -import { ImportAdder } from "../_namespaces/ts.codefix"; +import { + ImportAdder, +} from "../_namespaces/ts.codefix"; /** * Finds members of the resolved type that are missing in the class pointed to by class decl @@ -130,7 +132,8 @@ export function createMissingMemberNodes( context: TypeConstructionContext, preferences: UserPreferences, importAdder: ImportAdder | undefined, - addClassElement: (node: AddNode) => void): void { + addClassElement: (node: AddNode) => void, +): void { const classMembers = classDeclaration.symbol.members!; for (const symbol of possiblyMissingSymbols) { if (!classMembers.has(symbol.escapedName)) { @@ -158,9 +161,9 @@ export type AddNode = PropertyDeclaration | GetAccessorDeclaration | SetAccessor /** @internal */ export const enum PreserveOptionalFlags { - Method = 1 << 0, + Method = 1 << 0, Property = 1 << 1, - All = Method | Property + All = Method | Property, } /** @@ -204,8 +207,7 @@ export function addNewNodeForMemberSymbol( const declarationName = createDeclarationName(symbol, declaration); const effectiveModifierFlags = declaration ? getEffectiveModifierFlags(declaration) : ModifierFlags.None; let modifierFlags = effectiveModifierFlags & ModifierFlags.Static; - modifierFlags |= - effectiveModifierFlags & ModifierFlags.Public ? ModifierFlags.Public : + modifierFlags |= effectiveModifierFlags & ModifierFlags.Public ? ModifierFlags.Public : effectiveModifierFlags & ModifierFlags.Protected ? ModifierFlags.Protected : ModifierFlags.None; if (declaration && isAutoAccessorPropertyDeclaration(declaration)) { @@ -234,7 +236,8 @@ export function addNewNodeForMemberSymbol( declaration ? createName(declarationName) : symbol.getName(), optional && (preserveOptional & PreserveOptionalFlags.Property) ? factory.createToken(SyntaxKind.QuestionToken) : undefined, typeNode, - /*initializer*/ undefined)); + /*initializer*/ undefined, + )); break; case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: { @@ -258,7 +261,8 @@ export function addNewNodeForMemberSymbol( createName(declarationName), emptyArray, createTypeNode(typeNode), - createBody(body, quotePreference, ambient))); + createBody(body, quotePreference, ambient), + )); } else { Debug.assertNode(accessor, isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); @@ -268,7 +272,8 @@ export function addNewNodeForMemberSymbol( modifiers, createName(declarationName), createDummyParameters(1, [parameterName], [createTypeNode(typeNode)], 1, /*inJs*/ false), - createBody(body, quotePreference, ambient))); + createBody(body, quotePreference, ambient), + )); } } break; @@ -378,14 +383,13 @@ export function createSignatureDeclarationFromSignature( modifiers: NodeArray | undefined, optional: boolean | undefined, enclosingDeclaration: Node | undefined, - importAdder: ImportAdder | undefined + importAdder: ImportAdder | undefined, ) { const program = context.program; const checker = program.getTypeChecker(); const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); const isJs = isInJSFile(enclosingDeclaration); - const flags = - NodeBuilderFlags.NoTruncation + const flags = NodeBuilderFlags.NoTruncation | NodeBuilderFlags.SuppressAnyReturnType | NodeBuilderFlags.AllowEmptyTuple | (quotePreference === QuotePreference.Single ? NodeBuilderFlags.UseSingleQuotesForStringLiteralType : NodeBuilderFlags.None); @@ -421,7 +425,7 @@ export function createSignatureDeclarationFromSignature( typeParameterDecl.modifiers, typeParameterDecl.name, constraint, - defaultType + defaultType, ); }); if (typeParameters !== newTypeParameters) { @@ -444,7 +448,7 @@ export function createSignatureDeclarationFromSignature( parameterDecl.name, isJs ? undefined : parameterDecl.questionToken, type, - parameterDecl.initializer + parameterDecl.initializer, ); }); if (parameters !== newParameters) { @@ -484,7 +488,7 @@ export function createSignatureDeclarationFromCallExpression( call: CallExpression, name: Identifier | PrivateIdentifier | string, modifierFlags: ModifierFlags, - contextNode: Node + contextNode: Node, ): MethodDeclaration | FunctionDeclaration | MethodSignature { const quotePreference = getQuotePreference(context.sourceFile, context.preferences); const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); @@ -494,11 +498,16 @@ export function createSignatureDeclarationFromCallExpression( const { typeArguments, arguments: args, parent } = call; const contextualType = isJs ? undefined : checker.getContextualType(call); - const names = map(args, arg => - isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : undefined); + const names = map(args, arg => isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : undefined); const instanceTypes = isJs ? [] : map(args, arg => checker.getTypeAtLocation(arg)); const { argumentTypeNodes, argumentTypeParameters } = getArgumentTypesAndTypeParameters( - checker, importAdder, instanceTypes, contextNode, scriptTarget, NodeBuilderFlags.NoTruncation, tracker + checker, + importAdder, + instanceTypes, + contextNode, + scriptTarget, + NodeBuilderFlags.NoTruncation, + tracker, ); const modifiers = modifierFlags @@ -523,7 +532,7 @@ export function createSignatureDeclarationFromCallExpression( typeParameters, parameters, type, - createStubbedMethodBody(quotePreference) + createStubbedMethodBody(quotePreference), ); case SyntaxKind.MethodSignature: return factory.createMethodSignature( @@ -532,7 +541,7 @@ export function createSignatureDeclarationFromCallExpression( /*questionToken*/ undefined, typeParameters, parameters, - type === undefined ? factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword) : type + type === undefined ? factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword) : type, ); case SyntaxKind.FunctionDeclaration: Debug.assert(typeof name === "string" || isIdentifier(name), "Unexpected name"); @@ -543,7 +552,7 @@ export function createSignatureDeclarationFromCallExpression( typeParameters, parameters, type, - createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference) + createStubbedBody(Diagnostics.Function_not_implemented.message, quotePreference), ); default: Debug.fail("Unexpected kind"); @@ -709,7 +718,8 @@ function createDummyParameters(argCount: number, names: (string | undefined)[] | /*name*/ parameterName + (parameterNameCount || ""), /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? factory.createToken(SyntaxKind.QuestionToken) : undefined, /*type*/ inJs ? undefined : types?.[i] || factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword), - /*initializer*/ undefined); + /*initializer*/ undefined, + ); parameters.push(newParameter); } return parameters; @@ -753,7 +763,8 @@ function createMethodImplementingSignatures( maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", /*questionToken*/ maxNonRestArgs >= minArgumentCount ? factory.createToken(SyntaxKind.QuestionToken) : undefined, factory.createArrayTypeNode(factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword)), - /*initializer*/ undefined); + /*initializer*/ undefined, + ); parameters.push(restParameter); } @@ -765,7 +776,8 @@ function createMethodImplementingSignatures( parameters, getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration), quotePreference, - body); + body, + ); } function getReturnTypeFromSignatures(signatures: readonly Signature[], checker: TypeChecker, context: TypeConstructionContext, enclosingDeclaration: ClassLikeDeclaration): TypeNode | undefined { @@ -783,7 +795,7 @@ function createStubbedMethod( parameters: readonly ParameterDeclaration[], returnType: TypeNode | undefined, quotePreference: QuotePreference, - body: Block | undefined + body: Block | undefined, ): MethodDeclaration { return factory.createMethodDeclaration( modifiers, @@ -793,7 +805,8 @@ function createStubbedMethod( typeParameters, parameters, returnType, - body || createStubbedMethodBody(quotePreference)); + body || createStubbedMethodBody(quotePreference), + ); } function createStubbedMethodBody(quotePreference: QuotePreference) { @@ -808,24 +821,32 @@ export function createStubbedBody(text: string, quotePreference: QuotePreference factory.createIdentifier("Error"), /*typeArguments*/ undefined, // TODO Handle auto quote preference. - [factory.createStringLiteral(text, /*isSingleQuote*/ quotePreference === QuotePreference.Single)]))], - /*multiLine*/ true); + [factory.createStringLiteral(text, /*isSingleQuote*/ quotePreference === QuotePreference.Single)], + ), + )], + /*multiLine*/ true, + ); } /** @internal */ export function setJsonCompilerOptionValues( changeTracker: textChanges.ChangeTracker, configFile: TsConfigSourceFile, - options: [string, Expression][] + options: [string, Expression][], ) { const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (compilerOptionsProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment( - "compilerOptions", - factory.createObjectLiteralExpression(options.map(([optionName, optionValue]) => createJsonPropertyAssignment(optionName, optionValue)), /*multiLine*/ true))); + changeTracker.insertNodeAtObjectStart( + configFile, + tsconfigObjectLiteral, + createJsonPropertyAssignment( + "compilerOptions", + factory.createObjectLiteralExpression(options.map(([optionName, optionValue]) => createJsonPropertyAssignment(optionName, optionValue)), /*multiLine*/ true), + ), + ); return; } diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index e6f0eb91405e3..1b0bcd9145d65 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -171,14 +171,17 @@ registerCodeFix({ const { errorCode, preferences, sourceFile, span, program } = context; const info = getFixInfos(context, errorCode, span.start, /*useAutoImportProvider*/ true); if (!info) return undefined; - return info.map(({ fix, symbolName, errorIdentifierText }) => codeActionForFix( - context, - sourceFile, - symbolName, - fix, - /*includeSymbolNameInDescription*/ symbolName !== errorIdentifierText, - program.getCompilerOptions(), - preferences)); + return info.map(({ fix, symbolName, errorIdentifierText }) => + codeActionForFix( + context, + sourceFile, + symbolName, + fix, + /*includeSymbolNameInDescription*/ symbolName !== errorIdentifierText, + program.getCompilerOptions(), + preferences, + ) + ); }, fixIds: [importFixId], getAllCodeActions: context => { @@ -222,7 +225,7 @@ function createImportAdderWorker(sourceFile: SourceFile, program: Program, useAu type NewImportsKey = `${0 | 1}|${string}`; /** Use `getNewImportEntry` for access */ - const newImports = new Map>(); + const newImports = new Map>(); return { addImportFromDiagnostic, addImportFromExportedSymbol, writeFixes, hasFixes }; function addImportFromDiagnostic(diagnostic: DiagnosticWithLocation, context: CodeFixContextBase) { @@ -312,7 +315,7 @@ function createImportAdderWorker(sourceFile: SourceFile, program: Program, useAu return Math.max(prevValue ?? 0, newValue); } - function getNewImportEntry(moduleSpecifier: string, importKind: ImportKind, useRequire: boolean, addAsTypeOnly: AddAsTypeOnly): Mutable { + function getNewImportEntry(moduleSpecifier: string, importKind: ImportKind, useRequire: boolean, addAsTypeOnly: AddAsTypeOnly): Mutable { // A default import that requires type-only makes the whole import type-only. // (We could add `default` as a named import, but that style seems undesirable.) // Under `--preserveValueImports` and `--importsNotUsedAsValues=error`, if a @@ -323,11 +326,11 @@ function createImportAdderWorker(sourceFile: SourceFile, program: Program, useAu const nonTypeOnlyKey = newImportsKey(moduleSpecifier, /*topLevelTypeOnly*/ false); const typeOnlyEntry = newImports.get(typeOnlyKey); const nonTypeOnlyEntry = newImports.get(nonTypeOnlyKey); - const newEntry: ImportsCollection & { useRequire: boolean } = { + const newEntry: ImportsCollection & { useRequire: boolean; } = { defaultImport: undefined, namedImports: undefined, namespaceLikeImport: undefined, - useRequire + useRequire, }; if (importKind === ImportKind.Default && addAsTypeOnly === AddAsTypeOnly.Required) { if (typeOnlyEntry) return typeOnlyEntry; @@ -371,7 +374,8 @@ function createImportAdderWorker(sourceFile: SourceFile, program: Program, useAu importClauseOrBindingPattern, defaultImport, arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })), - preferences); + preferences, + ); }); let newDeclarations: AnyImportOrRequireStatement | readonly AnyImportOrRequireStatement[] | undefined; @@ -384,7 +388,8 @@ function createImportAdderWorker(sourceFile: SourceFile, program: Program, useAu defaultImport, namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })), namespaceLikeImport, - compilerOptions); + compilerOptions, + ); newDeclarations = combine(newDeclarations, declarations); }); if (newDeclarations) { @@ -402,13 +407,13 @@ function createImportAdderWorker(sourceFile: SourceFile, program: Program, useAu * * @internal */ - export interface ImportSpecifierResolver { +export interface ImportSpecifierResolver { getModuleSpecifierForBestExportInfo( exportInfo: readonly SymbolExportInfo[], position: number, isValidTypeOnlyUseSite: boolean, - fromCacheOnly?: boolean - ): { exportInfo?: SymbolExportInfo, moduleSpecifier: string, computedWithoutCacheCount: number } | undefined; + fromCacheOnly?: boolean, + ): { exportInfo?: SymbolExportInfo; moduleSpecifier: string; computedWithoutCacheCount: number; } | undefined; } /** @internal */ @@ -422,7 +427,7 @@ export function createImportSpecifierResolver(importingFile: SourceFile, program position: number, isValidTypeOnlyUseSite: boolean, fromCacheOnly?: boolean, - ): { exportInfo?: SymbolExportInfo, moduleSpecifier: string, computedWithoutCacheCount: number } | undefined { + ): { exportInfo?: SymbolExportInfo; moduleSpecifier: string; computedWithoutCacheCount: number; } | undefined { const { fixes, computedWithoutCacheCount } = getImportFixes( exportInfo, position, @@ -433,21 +438,28 @@ export function createImportSpecifierResolver(importingFile: SourceFile, program host, preferences, importMap, - fromCacheOnly); + fromCacheOnly, + ); const result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); return result && { ...result, computedWithoutCacheCount }; } } // Sorted with the preferred fix coming first. -const enum ImportFixKind { UseNamespace, JsdocTypeImport, AddToExisting, AddNew, PromoteTypeOnly } +const enum ImportFixKind { + UseNamespace, + JsdocTypeImport, + AddToExisting, + AddNew, + PromoteTypeOnly, +} // These should not be combined as bitflags, but are given powers of 2 values to // easily detect conflicts between `NotAllowed` and `Required` by giving them a unique sum. // They're also ordered in terms of increasing priority for a fix-all scenario (see // `reduceAddAsTypeOnlyValues`). const enum AddAsTypeOnly { - Allowed = 1 << 0, - Required = 1 << 1, + Allowed = 1 << 0, + Required = 1 << 1, NotAllowed = 1 << 2, } type ImportFix = FixUseNamespaceImport | FixAddJsdocTypeImport | FixAddToExistingImport | FixAddNewImport | FixPromoteTypeOnlyImport; @@ -490,7 +502,6 @@ interface FixPromoteTypeOnlyImport { readonly typeOnlyAliasDeclaration: TypeOnlyAliasDeclaration; } - /** Information needed to augment an existing import declaration. */ interface FixAddToExistingImportInfo { readonly declaration: AnyImportOrRequire; @@ -513,7 +524,7 @@ export function getImportCompletionAction( position: number, preferences: UserPreferences, cancellationToken: CancellationToken, -): { readonly moduleSpecifier: string, readonly codeAction: CodeAction } { +): { readonly moduleSpecifier: string; readonly codeAction: CodeAction; } { const compilerOptions = program.getCompilerOptions(); let exportInfos; @@ -543,7 +554,8 @@ export function getImportCompletionAction( fix, /*includeSymbolNameInDescription*/ false, compilerOptions, - preferences)) + preferences, + )), }; } @@ -607,7 +619,7 @@ function getImportFixes( preferences: UserPreferences, importMap = createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()), fromCacheOnly?: boolean, -): { computedWithoutCacheCount: number, fixes: readonly ImportFixWithModuleSpecifier[] } { +): { computedWithoutCacheCount: number; fixes: readonly ImportFixWithModuleSpecifier[]; } { const checker = program.getTypeChecker(); const existingImports = flatMap(exportInfos, importMap.getImportsForExportInfo); const useNamespace = usagePosition !== undefined && tryUseExistingNamespaceImport(existingImports, usagePosition); @@ -630,7 +642,8 @@ function getImportFixes( useRequire, host, preferences, - fromCacheOnly); + fromCacheOnly, + ); return { computedWithoutCacheCount, fixes: [...(useNamespace ? [useNamespace] : emptyArray), ...fixes], @@ -679,7 +692,7 @@ function getAddAsTypeOnly( symbol: Symbol, targetFlags: SymbolFlags, checker: TypeChecker, - compilerOptions: CompilerOptions + compilerOptions: CompilerOptions, ) { if (!isValidTypeOnlyUseSite) { // Can't use a type-only import if the usage is an emitting position @@ -689,7 +702,8 @@ function getAddAsTypeOnly( // Not writing a (top-level) type-only import here would create an error because the runtime dependency is unnecessary return AddAsTypeOnly.Required; } - if (importNameElisionDisabled(compilerOptions) && + if ( + importNameElisionDisabled(compilerOptions) && (!(targetFlags & SymbolFlags.Value) || !!checker.getTypeOnlyAliasDeclaration(symbol)) ) { // A type-only import is required for this symbol if under these settings if the symbol will @@ -746,13 +760,16 @@ function tryAddToExistingImport(existingImports: readonly FixAddToExistingImport // the import guarantees the symbol came from the main program. const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ false, symbol, targetFlags, checker, compilerOptions); - if (importKind === ImportKind.Default && ( - name || // Cannot add a default import to a declaration that already has one - addAsTypeOnly === AddAsTypeOnly.Required && namedBindings // Cannot add a default import as type-only if the import already has named bindings - )) { + if ( + importKind === ImportKind.Default && ( + name || // Cannot add a default import to a declaration that already has one + addAsTypeOnly === AddAsTypeOnly.Required && namedBindings // Cannot add a default import as type-only if the import already has named bindings + ) + ) { return undefined; } - if (importKind === ImportKind.Named && + if ( + importKind === ImportKind.Named && namedBindings?.kind === SyntaxKind.NamespaceImport // Cannot add a named import to a declaration that has a namespace import ) { return undefined; @@ -794,7 +811,7 @@ function createExistingImportMap(checker: TypeChecker, importingFile: SourceFile if (!matchingDeclarations) return emptyArray; const importKind = getImportKind(importingFile, exportKind, compilerOptions); return matchingDeclarations.map(declaration => ({ declaration, importKind, symbol, targetFlags })); - } + }, }; } @@ -844,7 +861,7 @@ function getNewImportFixes( host: LanguageServiceHost, preferences: UserPreferences, fromCacheOnly?: boolean, -): { computedWithoutCacheCount: number, fixes: readonly (FixAddNewImport | FixAddJsdocTypeImport)[] } { +): { computedWithoutCacheCount: number; fixes: readonly (FixAddNewImport | FixAddJsdocTypeImport)[]; } { const isJs = isSourceFileJS(sourceFile); const compilerOptions = program.getCompilerOptions(); const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host); @@ -887,7 +904,8 @@ function getNewImportFixes( namespacePrefix ||= moduleSymbolToValidIdentifier( exportInfo.moduleSymbol, getEmitScriptTarget(compilerOptions), - /*forceCapitalize*/ false); + /*forceCapitalize*/ false, + ); qualification = { namespacePrefix, usagePosition }; } return { @@ -917,7 +935,7 @@ function getFixesForAddImport( host: LanguageServiceHost, preferences: UserPreferences, fromCacheOnly?: boolean, -): { computedWithoutCacheCount?: number, fixes: readonly (FixAddNewImport | FixAddJsdocTypeImport)[] } { +): { computedWithoutCacheCount?: number; fixes: readonly (FixAddNewImport | FixAddJsdocTypeImport)[]; } { const existingDeclaration = firstDefined(existingImports, info => newImportInfoFromExistingSpecifier(info, isValidTypeOnlyUseSite, useRequire, program.getTypeChecker(), program.getCompilerOptions())); return existingDeclaration ? { fixes: [existingDeclaration] } : getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUseSite, useRequire, exportInfos, host, preferences, fromCacheOnly); } @@ -927,7 +945,7 @@ function newImportInfoFromExistingSpecifier( isValidTypeOnlyUseSite: boolean, useRequire: boolean, checker: TypeChecker, - compilerOptions: CompilerOptions + compilerOptions: CompilerOptions, ): FixAddNewImport | undefined { const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(declaration)?.text; if (moduleSpecifier) { @@ -966,7 +984,7 @@ function getFixInfos(context: CodeFixContextBase, errorCode: number, pos: number return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host); } -function sortFixInfo(fixes: readonly (FixInfo & { fix: ImportFixWithModuleSpecifier })[], sourceFile: SourceFile, program: Program, packageJsonImportFilter: PackageJsonImportFilter, host: LanguageServiceHost): readonly (FixInfo & { fix: ImportFixWithModuleSpecifier })[] { +function sortFixInfo(fixes: readonly (FixInfo & { fix: ImportFixWithModuleSpecifier; })[], sourceFile: SourceFile, program: Program, packageJsonImportFilter: PackageJsonImportFilter, host: LanguageServiceHost): readonly (FixInfo & { fix: ImportFixWithModuleSpecifier; })[] { const _toPath = (fileName: string) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)); return sort(fixes, (a, b) => compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || @@ -984,13 +1002,13 @@ function getBestFix(fixes: readonly ImportFixWithModuleSpecifier[], sourceFile: return fixes.reduce((best, fix) => // Takes true branch of conditional if `fix` is better than `best` compareModuleSpecifiers( - fix, - best, - sourceFile, - program, - packageJsonImportFilter.allowsImportingSpecifier, - fileName => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), - ) === Comparison.LessThan ? fix : best + fix, + best, + sourceFile, + program, + packageJsonImportFilter.allowsImportingSpecifier, + fileName => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), + ) === Comparison.LessThan ? fix : best ); } @@ -1008,7 +1026,8 @@ function compareModuleSpecifiers( || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans( isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath), - isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath)) + isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath), + ) || compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } return Comparison.EqualTo; @@ -1020,13 +1039,14 @@ function compareModuleSpecifiers( // (e.g. `export * from "../whatever"`) or are not named "index" (we don't even try to consider // this if we're in a resolution mode where you can't drop trailing "/index" from paths). function isFixPossiblyReExportingImportingFile(fix: ImportFixWithModuleSpecifier, importingFile: SourceFile, compilerOptions: CompilerOptions, toPath: (fileName: string) => Path): boolean { - if (fix.isReExport && + if ( + fix.isReExport && fix.exportInfo?.moduleFileName && getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node10 && isIndexFileName(fix.exportInfo.moduleFileName) ) { const reExportDir = toPath(getDirectoryPath(fix.exportInfo.moduleFileName)); - return startsWith((importingFile.path), reExportDir); + return startsWith(importingFile.path, reExportDir); } return false; } @@ -1041,7 +1061,7 @@ function compareNodeCoreModuleSpecifiers(a: string, b: string, importingFile: So return Comparison.EqualTo; } -function getFixesInfoForUMDImport({ sourceFile, program, host, preferences }: CodeFixContextBase, token: Node): (FixInfo & { fix: ImportFixWithModuleSpecifier })[] | undefined { +function getFixesInfoForUMDImport({ sourceFile, program, host, preferences }: CodeFixContextBase, token: Node): (FixInfo & { fix: ImportFixWithModuleSpecifier; })[] | undefined { const checker = program.getTypeChecker(); const umdSymbol = getUmdSymbol(token, checker); if (!umdSymbol) return undefined; @@ -1086,11 +1106,16 @@ export function getImportKind(importingFile: SourceFile, exportKind: ExportKind, return ImportKind.CommonJS; } switch (exportKind) { - case ExportKind.Named: return ImportKind.Named; - case ExportKind.Default: return ImportKind.Default; - case ExportKind.ExportEquals: return getExportEqualsImportKind(importingFile, compilerOptions, !!forceImportKeyword); - case ExportKind.UMD: return getUmdImportKind(importingFile, compilerOptions, !!forceImportKeyword); - default: return Debug.assertNever(exportKind); + case ExportKind.Named: + return ImportKind.Named; + case ExportKind.Default: + return ImportKind.Default; + case ExportKind.ExportEquals: + return getExportEqualsImportKind(importingFile, compilerOptions, !!forceImportKeyword); + case ExportKind.UMD: + return getUmdImportKind(importingFile, compilerOptions, !!forceImportKeyword); + default: + return Debug.assertNever(exportKind); } } @@ -1126,7 +1151,7 @@ function getUmdImportKind(importingFile: SourceFile, compilerOptions: CompilerOp } } -function getFixesInfoForNonUMDImport({ sourceFile, program, cancellationToken, host, preferences }: CodeFixContextBase, symbolToken: Identifier, useAutoImportProvider: boolean): readonly (FixInfo & { fix: ImportFixWithModuleSpecifier })[] | undefined { +function getFixesInfoForNonUMDImport({ sourceFile, program, cancellationToken, host, preferences }: CodeFixContextBase, symbolToken: Identifier, useAutoImportProvider: boolean): readonly (FixInfo & { fix: ImportFixWithModuleSpecifier; })[] | undefined { const checker = program.getTypeChecker(); const compilerOptions = program.getCompilerOptions(); return flatMap(getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions), symbolName => { @@ -1138,9 +1163,8 @@ function getFixesInfoForNonUMDImport({ sourceFile, program, cancellationToken, h const useRequire = shouldUseRequire(sourceFile, program); const exportInfo = getExportInfos(symbolName, isJSXTagName(symbolToken), getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); return arrayFrom( - flatMapIterator(exportInfo.values(), exportInfos => - getImportFixes(exportInfos, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes), - fix => ({ fix, symbolName, errorIdentifierText: symbolToken.text, isJsxNamespaceFix: symbolName !== symbolToken.text }) + flatMapIterator(exportInfo.values(), exportInfos => getImportFixes(exportInfos, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes), + fix => ({ fix, symbolName, errorIdentifierText: symbolToken.text, isJsxNamespaceFix: symbolName !== symbolToken.text }), ); }); } @@ -1196,7 +1220,8 @@ function getExportInfos( }); function addSymbol(moduleSymbol: Symbol, toFile: SourceFile | undefined, exportedSymbol: Symbol, exportKind: ExportKind, program: Program, isFromPackageJson: boolean): void { const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); - if (toFile && isImportableFile(program, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || + if ( + toFile && isImportableFile(program, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) ) { const checker = program.getTypeChecker(); @@ -1275,7 +1300,8 @@ function codeActionForFixWorker(changes: textChanges.ChangeTracker, sourceFile: importClauseOrBindingPattern, importKind === ImportKind.Default ? { name: symbolName, addAsTypeOnly } : undefined, importKind === ImportKind.Named ? [{ name: symbolName, addAsTypeOnly }] : emptyArray, - preferences); + preferences, + ); const moduleSpecifierWithoutQuotes = stripQuotes(moduleSpecifier); return includeSymbolNameInDescription ? [Diagnostics.Import_0_from_1, symbolName, moduleSpecifierWithoutQuotes] @@ -1289,13 +1315,20 @@ function codeActionForFixWorker(changes: textChanges.ChangeTracker, sourceFile: const namespaceLikeImport = importKind === ImportKind.Namespace || importKind === ImportKind.CommonJS ? { importKind, name: qualification?.namespacePrefix || symbolName, addAsTypeOnly } : undefined; - insertImports(changes, sourceFile, getDeclarations( - moduleSpecifier, - quotePreference, - defaultImport, - namedImports, - namespaceLikeImport, - compilerOptions), /*blankLineBetween*/ true, preferences); + insertImports( + changes, + sourceFile, + getDeclarations( + moduleSpecifier, + quotePreference, + defaultImport, + namedImports, + namespaceLikeImport, + compilerOptions, + ), + /*blankLineBetween*/ true, + preferences, + ); if (qualification) { addNamespaceQualifier(changes, sourceFile, qualification); } @@ -1372,7 +1405,8 @@ function promoteFromTypeOnly(changes: textChanges.ChangeTracker, aliasDeclaratio if (convertExistingToTypeOnly) { const namedImports = tryCast(importClause.namedBindings, isNamedImports); if (namedImports && namedImports.elements.length > 1) { - if (OrganizeImports.detectImportSpecifierSorting(namedImports.elements, preferences) && + if ( + OrganizeImports.detectImportSpecifierSorting(namedImports.elements, preferences) && aliasDeclaration.kind === SyntaxKind.ImportSpecifier && namedImports.elements.indexOf(aliasDeclaration) !== 0 ) { @@ -1438,11 +1472,15 @@ function doAddExistingFix( const comparer = OrganizeImports.getOrganizeImportsComparer(preferences, ignoreCaseForSorting); const newSpecifiers = stableSort( - namedImports.map(namedImport => factory.createImportSpecifier( - (!clause.isTypeOnly || promoteFromTypeOnly) && needsTypeOnly(namedImport), - /*propertyName*/ undefined, - factory.createIdentifier(namedImport.name))), - (s1, s2) => OrganizeImports.compareImportOrExportSpecifiers(s1, s2, comparer)); + namedImports.map(namedImport => + factory.createImportSpecifier( + (!clause.isTypeOnly || promoteFromTypeOnly) && needsTypeOnly(namedImport), + /*propertyName*/ undefined, + factory.createIdentifier(namedImport.name), + ) + ), + (s1, s2) => OrganizeImports.compareImportOrExportSpecifiers(s1, s2, comparer), + ); // The sorting preference computed earlier may or may not have validated that these particular // import specifiers are sorted. If they aren't, `getImportSpecifierInsertionIndex` will return @@ -1531,7 +1569,7 @@ interface ImportsCollection { }; } -function needsTypeOnly({ addAsTypeOnly }: { addAsTypeOnly: AddAsTypeOnly }): boolean { +function needsTypeOnly({ addAsTypeOnly }: { addAsTypeOnly: AddAsTypeOnly; }): boolean { return addAsTypeOnly === AddAsTypeOnly.Required; } @@ -1540,7 +1578,7 @@ function getNewImports( quotePreference: QuotePreference, defaultImport: Import | undefined, namedImports: readonly Import[] | undefined, - namespaceLikeImport: Import & { importKind: ImportKind.CommonJS | ImportKind.Namespace } | undefined, + namespaceLikeImport: Import & { importKind: ImportKind.CommonJS | ImportKind.Namespace; } | undefined, compilerOptions: CompilerOptions, ): AnyImportSyntax | readonly AnyImportSyntax[] { const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); @@ -1550,17 +1588,24 @@ function getNewImports( // even though it's not an error, it would add unnecessary runtime emit. const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) || compilerOptions.verbatimModuleSyntax && - defaultImport?.addAsTypeOnly !== AddAsTypeOnly.NotAllowed && - !some(namedImports, i => i.addAsTypeOnly === AddAsTypeOnly.NotAllowed); - statements = combine(statements, makeImport( - defaultImport && factory.createIdentifier(defaultImport.name), - namedImports?.map(({ addAsTypeOnly, name }) => factory.createImportSpecifier( - !topLevelTypeOnly && addAsTypeOnly === AddAsTypeOnly.Required, - /*propertyName*/ undefined, - factory.createIdentifier(name))), - moduleSpecifier, - quotePreference, - topLevelTypeOnly)); + defaultImport?.addAsTypeOnly !== AddAsTypeOnly.NotAllowed && + !some(namedImports, i => i.addAsTypeOnly === AddAsTypeOnly.NotAllowed); + statements = combine( + statements, + makeImport( + defaultImport && factory.createIdentifier(defaultImport.name), + namedImports?.map(({ addAsTypeOnly, name }) => + factory.createImportSpecifier( + !topLevelTypeOnly && addAsTypeOnly === AddAsTypeOnly.Required, + /*propertyName*/ undefined, + factory.createIdentifier(name), + ) + ), + moduleSpecifier, + quotePreference, + topLevelTypeOnly, + ), + ); } if (namespaceLikeImport) { @@ -1569,15 +1614,18 @@ function getNewImports( /*modifiers*/ undefined, needsTypeOnly(namespaceLikeImport), factory.createIdentifier(namespaceLikeImport.name), - factory.createExternalModuleReference(quotedModuleSpecifier)) + factory.createExternalModuleReference(quotedModuleSpecifier), + ) : factory.createImportDeclaration( /*modifiers*/ undefined, factory.createImportClause( needsTypeOnly(namespaceLikeImport), /*name*/ undefined, - factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name))), + factory.createNamespaceImport(factory.createIdentifier(namespaceLikeImport.name)), + ), quotedModuleSpecifier, - /*assertClause*/ undefined); + /*assertClause*/ undefined, + ); statements = combine(statements, declaration); } return Debug.checkDefined(statements); @@ -1611,8 +1659,10 @@ function createConstEqualsRequireDeclaration(name: string | ObjectBindingPattern typeof name === "string" ? factory.createIdentifier(name) : name, /*exclamationToken*/ undefined, /*type*/ undefined, - factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier]))], - NodeFlags.Const)) as RequireVariableStatement; + factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier]), + ), + ], NodeFlags.Const), + ) as RequireVariableStatement; } function symbolHasMeaning({ declarations }: Symbol, meaning: SemanticMeaning): boolean { diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index af21562a22a27..95a19e1d39638 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -395,7 +395,6 @@ function annotateSetAccessor( program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken, - ): void { const param = firstOrUndefined(setAccessorDeclaration.parameters); if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { @@ -436,7 +435,7 @@ function tryReplaceImportTypeNodeWithAutoImport( sourceFile: SourceFile, changes: textChanges.ChangeTracker, importAdder: ImportAdder, - scriptTarget: ScriptTarget + scriptTarget: ScriptTarget, ): boolean { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeNode)) { @@ -487,16 +486,14 @@ function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: } } else { - const paramTags = map(inferences, ({ name, typeNode, isOptional }) => - factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /*isNameFirst*/ false, /*comment*/ undefined)); + const paramTags = map(inferences, ({ name, typeNode, isOptional }) => factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, factory.createJSDocTypeExpression(typeNode), /*isNameFirst*/ false, /*comment*/ undefined)); changes.addJSDocTags(sourceFile, signature, paramTags); } } function getReferences(token: PropertyName | Token, program: Program, cancellationToken: CancellationToken): readonly Identifier[] { // Position shouldn't matter since token is not a SourceFile. - return mapDefined(FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry => - entry.kind !== FindAllReferences.EntryKind.Span ? tryCast(entry.node, isIdentifier) : undefined); + return mapDefined(FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry => entry.kind !== FindAllReferences.EntryKind.Span ? tryCast(entry.node, isIdentifier) : undefined); } function inferTypeForVariableFromUsage(token: Identifier | PrivateIdentifier, program: Program, cancellationToken: CancellationToken): Type { @@ -509,7 +506,7 @@ function inferTypeForParametersFromUsage(func: SignatureDeclaration, sourceFile: return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || func.parameters.map(p => ({ declaration: p, - type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType(), })); } @@ -548,7 +545,7 @@ interface ParameterInference { function inferTypeFromReferences(program: Program, references: readonly Identifier[], cancellationToken: CancellationToken) { const checker = program.getTypeChecker(); - const builtinConstructors: { [s: string]: (t: Type) => Type } = { + const builtinConstructors: { [s: string]: (t: Type) => Type; } = { string: () => checker.getStringType(), number: () => checker.getNumberType(), Array: t => checker.createArrayType(t), @@ -676,7 +673,7 @@ function inferTypeFromReferences(program: Program, references: readonly Identifi return { type: isRest ? checker.createArrayType(type) : type, isOptional: isOptional && !isRest, - declaration: parameter + declaration: parameter, }; }); } @@ -782,8 +779,8 @@ function inferTypeFromReferences(program: Program, references: readonly Identifi usage.isNumberOrString = true; break; - // case SyntaxKind.ExclamationToken: - // no inferences here; + // case SyntaxKind.ExclamationToken: + // no inferences here; } } @@ -884,8 +881,10 @@ function inferTypeFromReferences(program: Program, references: readonly Identifi // LogicalOperator Or NullishCoalescing case SyntaxKind.BarBarToken: case SyntaxKind.QuestionQuestionToken: - if (node === parent.left && - (node.parent.parent.kind === SyntaxKind.VariableDeclaration || isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + if ( + node === parent.left && + (node.parent.parent.kind === SyntaxKind.VariableDeclaration || isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true)) + ) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usage, checker.getTypeAtLocation(parent.right)); @@ -907,7 +906,7 @@ function inferTypeFromReferences(program: Program, references: readonly Identifi function inferTypeFromCallExpression(parent: CallExpression | NewExpression, usage: Usage): void { const call: CallUsage = { argumentTypes: [], - return_: createEmptyUsage() + return_: createEmptyUsage(), }; if (parent.arguments) { @@ -996,16 +995,17 @@ function inferTypeFromReferences(program: Program, references: readonly Identifi const priorities: Priority[] = [ { high: t => t === checker.getStringType() || t === checker.getNumberType(), - low: t => t === stringNumber + low: t => t === stringNumber, }, { high: t => !(t.flags & (TypeFlags.Any | TypeFlags.Void)), - low: t => !!(t.flags & (TypeFlags.Any | TypeFlags.Void)) + low: t => !!(t.flags & (TypeFlags.Any | TypeFlags.Void)), }, { high: t => !(t.flags & (TypeFlags.Nullable | TypeFlags.Any | TypeFlags.Void)) && !(getObjectFlags(t) & ObjectFlags.Anonymous), - low: t => !!(getObjectFlags(t) & ObjectFlags.Anonymous) - }]; + low: t => !!(getObjectFlags(t) & ObjectFlags.Anonymous), + }, + ]; let good = removeLowPriorityInferences(inferences, priorities); const anons = good.filter(i => getObjectFlags(i) & ObjectFlags.Anonymous) as AnonymousType[]; if (anons.length) { @@ -1057,7 +1057,8 @@ function inferTypeFromReferences(program: Program, references: readonly Identifi members, calls, constructs, - indexInfos); + indexInfos, + ); } function inferTypes(usage: Usage): Type[] { diff --git a/src/services/codefixes/requireInTs.ts b/src/services/codefixes/requireInTs.ts index 940cc8b690f92..cc22d5e9f0078 100644 --- a/src/services/codefixes/requireInTs.ts +++ b/src/services/codefixes/requireInTs.ts @@ -41,19 +41,24 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Convert_require_to_import, fixId, Diagnostics.Convert_all_require_to_import)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(diag.file, context.program, diag.start); - if (info) { - doChange(changes, context.sourceFile, info); - } - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file, context.program, diag.start); + if (info) { + doChange(changes, context.sourceFile, info); + } + }), }); function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, info: Info) { const { allowSyntheticDefaults, defaultImportName, namedImports, statement, required } = info; - changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults - ? factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, factory.createExternalModuleReference(required)) - : factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined)); + changes.replaceNode( + sourceFile, + statement, + defaultImportName && !allowSyntheticDefaults + ? factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, defaultImportName, factory.createExternalModuleReference(required)) + : factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, namedImports), required, /*assertClause*/ undefined), + ); } interface Info { @@ -79,7 +84,7 @@ function getInfo(sourceFile: SourceFile, program: Program, pos: number): Info | defaultImportName, namedImports, statement: cast(decl.parent.parent, isVariableStatement), - required: first(parent.arguments) + required: first(parent.arguments), }; } } diff --git a/src/services/codefixes/returnValueCorrect.ts b/src/services/codefixes/returnValueCorrect.ts index 5bca2c5788b91..3aba6c183d29a 100644 --- a/src/services/codefixes/returnValueCorrect.ts +++ b/src/services/codefixes/returnValueCorrect.ts @@ -53,12 +53,12 @@ const fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; const errorCodes = [ Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code, Diagnostics.Type_0_is_not_assignable_to_type_1.code, - Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code + Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, ]; enum ProblemKind { MissingReturnStatement, - MissingParentheses + MissingParentheses, } interface MissingReturnInfo { @@ -90,32 +90,34 @@ registerCodeFix({ if (info.kind === ProblemKind.MissingReturnStatement) { return append( [getActionForfixAddReturnStatement(context, info.expression, info.statement)], - isArrowFunction(info.declaration) ? getActionForFixRemoveBracesFromArrowFunctionBody(context, info.declaration, info.expression, info.commentSource): undefined); + isArrowFunction(info.declaration) ? getActionForFixRemoveBracesFromArrowFunctionBody(context, info.declaration, info.expression, info.commentSource) : undefined, + ); } else { return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)]; } }, - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code); - if (!info) return undefined; + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code); + if (!info) return undefined; - switch (context.fixId) { - case fixIdAddReturnStatement: - addReturnStatement(changes, diag.file, info.expression, info.statement); - break; - case fixRemoveBracesFromArrowFunctionBody: - if (!isArrowFunction(info.declaration)) return undefined; - removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /*withParen*/ false); - break; - case fixIdWrapTheBlockWithParen: - if (!isArrowFunction(info.declaration)) return undefined; - wrapBlockWithParen(changes, diag.file, info.declaration, info.expression); - break; - default: - Debug.fail(JSON.stringify(context.fixId)); - } - }), + switch (context.fixId) { + case fixIdAddReturnStatement: + addReturnStatement(changes, diag.file, info.expression, info.statement); + break; + case fixRemoveBracesFromArrowFunctionBody: + if (!isArrowFunction(info.declaration)) return undefined; + removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /*withParen*/ false); + break; + case fixIdWrapTheBlockWithParen: + if (!isArrowFunction(info.declaration)) return undefined; + wrapBlockWithParen(changes, diag.file, info.declaration, info.expression); + break; + default: + Debug.fail(JSON.stringify(context.fixId)); + } + }), }); function createObjectTypeFromLabeledExpression(checker: TypeChecker, label: Identifier, expression: Expression) { @@ -135,7 +137,7 @@ function getFixInfo(checker: TypeChecker, declaration: FunctionLikeDeclaration, kind: ProblemKind.MissingReturnStatement, expression: firstStatement.expression, statement: firstStatement, - commentSource: firstStatement.expression + commentSource: firstStatement.expression, }; } else if (isLabeledStatement(firstStatement) && isExpressionStatement(firstStatement.statement)) { @@ -147,14 +149,14 @@ function getFixInfo(checker: TypeChecker, declaration: FunctionLikeDeclaration, kind: ProblemKind.MissingParentheses, expression: node, statement: firstStatement, - commentSource: firstStatement.statement.expression + commentSource: firstStatement.statement.expression, } : { - declaration, - kind: ProblemKind.MissingReturnStatement, - expression: node, - statement: firstStatement, - commentSource: firstStatement.statement.expression - }; + declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression, + }; } } else if (isBlock(firstStatement) && length(firstStatement.statements) === 1) { @@ -168,7 +170,7 @@ function getFixInfo(checker: TypeChecker, declaration: FunctionLikeDeclaration, kind: ProblemKind.MissingReturnStatement, expression: node, statement: firstStatement, - commentSource: firstBlockStatement + commentSource: firstBlockStatement, }; } } @@ -192,13 +194,15 @@ function checkFixedAssignableTo(checker: TypeChecker, declaration: FunctionLikeD exprType, /*typePredicate*/ undefined, sig.minArgumentCount, - sig.flags); + sig.flags, + ); exprType = checker.createAnonymousType( /*symbol*/ undefined, createSymbolTable(), [newSig], [], - []); + [], + ); } else { exprType = checker.getAnyType(); @@ -257,7 +261,7 @@ function addReturnStatement(changes: textChanges.ChangeTracker, sourceFile: Sour changes.replaceNode(sourceFile, statement, factory.createReturnStatement(expression), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude, - suffix: probablyNeedSemi ? ";" : undefined + suffix: probablyNeedSemi ? ";" : undefined, }); } diff --git a/src/services/codefixes/splitTypeOnlyImport.ts b/src/services/codefixes/splitTypeOnlyImport.ts index 6af08a70ebff6..0b1e2e48e577e 100644 --- a/src/services/codefixes/splitTypeOnlyImport.ts +++ b/src/services/codefixes/splitTypeOnlyImport.ts @@ -30,9 +30,10 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId, Diagnostics.Split_all_invalid_type_only_imports)]; } }, - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, error) => { - splitTypeOnlyImport(changes, getImportDeclaration(context.sourceFile, error), context); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, error) => { + splitTypeOnlyImport(changes, getImportDeclaration(context.sourceFile, error), context); + }), }); function getImportDeclaration(sourceFile: SourceFile, span: TextSpan) { @@ -44,16 +45,26 @@ function splitTypeOnlyImport(changes: textChanges.ChangeTracker, importDeclarati return; } const importClause = Debug.checkDefined(importDeclaration.importClause); - changes.replaceNode(context.sourceFile, importDeclaration, factory.updateImportDeclaration( + changes.replaceNode( + context.sourceFile, importDeclaration, - importDeclaration.modifiers, - factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), - importDeclaration.moduleSpecifier, - importDeclaration.assertClause)); + factory.updateImportDeclaration( + importDeclaration, + importDeclaration.modifiers, + factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined), + importDeclaration.moduleSpecifier, + importDeclaration.assertClause, + ), + ); - changes.insertNodeAfter(context.sourceFile, importDeclaration, factory.createImportDeclaration( - /*modifiers*/ undefined, - factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings), - importDeclaration.moduleSpecifier, - importDeclaration.assertClause)); + changes.insertNodeAfter( + context.sourceFile, + importDeclaration, + factory.createImportDeclaration( + /*modifiers*/ undefined, + factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings), + importDeclaration.moduleSpecifier, + importDeclaration.assertClause, + ), + ); } diff --git a/src/services/codefixes/useDefaultImport.ts b/src/services/codefixes/useDefaultImport.ts index 75f72964530b6..92ef84495a7bb 100644 --- a/src/services/codefixes/useDefaultImport.ts +++ b/src/services/codefixes/useDefaultImport.ts @@ -32,10 +32,11 @@ registerCodeFix({ return [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_default_import, fixId, Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const info = getInfo(diag.file, diag.start); - if (info) doChange(changes, diag.file, info, context.preferences); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const info = getInfo(diag.file, diag.start); + if (info) doChange(changes, diag.file, info, context.preferences); + }), }); interface Info { diff --git a/src/services/codefixes/wrapJsxInFragment.ts b/src/services/codefixes/wrapJsxInFragment.ts index 78122a0840c62..11693d88a4c43 100644 --- a/src/services/codefixes/wrapJsxInFragment.ts +++ b/src/services/codefixes/wrapJsxInFragment.ts @@ -30,11 +30,12 @@ registerCodeFix({ return [createCodeFixAction(fixID, changes, Diagnostics.Wrap_in_JSX_fragment, fixID, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)]; }, fixIds: [fixID], - getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { - const node = findNodeToFix(context.sourceFile, diag.start); - if (!node) return undefined; - doChange(changes, context.sourceFile, node); - }), + getAllCodeActions: context => + codeFixAll(context, errorCodes, (changes, diag) => { + const node = findNodeToFix(context.sourceFile, diag.start); + if (!node) return undefined; + doChange(changes, context.sourceFile, node); + }), }); function findNodeToFix(sourceFile: SourceFile, pos: number): BinaryExpression | undefined { diff --git a/src/services/completions.ts b/src/services/completions.ts index 33ed264c3b620..bf808d66b29ed 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -384,7 +384,9 @@ import { VariableDeclaration, walkUpParenthesizedExpressions, } from "./_namespaces/ts"; -import { StringCompletions } from "./_namespaces/ts.Completions"; +import { + StringCompletions, +} from "./_namespaces/ts.Completions"; // Exported only for tests /** @internal */ @@ -396,7 +398,7 @@ export const moduleSpecifierResolutionCacheAttemptLimit = 1000; export type Log = (message: string) => void; /** @internal */ -export type SortText = string & { __sortText: any }; +export type SortText = string & { __sortText: any; }; /** @internal */ export const SortText = { // Presets @@ -452,6 +454,7 @@ export enum CompletionSource { ObjectLiteralMemberWithComma = "ObjectLiteralMemberWithComma/", } +// dprint-ignore /** @internal */ export const enum SymbolOriginInfoKind { ThisType = 1 << 0, @@ -498,9 +501,9 @@ interface SymbolOriginInfoTypeOnlyImport extends SymbolOriginInfo { } interface SymbolOriginInfoObjectLiteralMethod extends SymbolOriginInfo { - insertText: string, - labelDetails: CompletionEntryLabelDetails, - isSnippet?: true, + insertText: string; + labelDetails: CompletionEntryLabelDetails; + isSnippet?: true; } interface SymbolOriginInfoComputedPropertyName extends SymbolOriginInfo { @@ -575,6 +578,7 @@ export type SymbolOriginInfoMap = Record; */ export type SymbolSortTextMap = (SortText | undefined)[]; +// dprint-ignore const enum KeywordCompletionFilters { None, // No keywords All, // Every possible keyword (TODO: This is never appropriate) @@ -585,10 +589,14 @@ const enum KeywordCompletionFilters { TypeAssertionKeywords, TypeKeywords, TypeKeyword, // Literally just `type` - Last = TypeKeyword + Last = TypeKeyword, } -const enum GlobalsSearch { Continue, Success, Fail } +const enum GlobalsSearch { + Continue, + Success, + Fail, +} interface ModuleSpecifierResolutionContext { tryResolve: (exportInfo: readonly SymbolExportInfo[], isFromAmbientModule: boolean) => ModuleSpecifierResolutionResult; @@ -679,7 +687,7 @@ export function getCompletionsAtPosition( completionKind: CompletionTriggerKind | undefined, cancellationToken: CancellationToken, formatContext?: formatting.FormatContext, - includeSymbol = false + includeSymbol = false, ): CompletionInfo | undefined { const { previousToken } = getRelevantTokens(position, sourceFile); if (triggerCharacter && !isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) { @@ -692,7 +700,6 @@ export function getCompletionsAtPosition( return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] }; } return undefined; - } const compilerOptions = program.getCompilerOptions(); @@ -715,8 +722,10 @@ export function getCompletionsAtPosition( return stringCompletions; } - if (previousToken && isBreakOrContinueStatement(previousToken.parent) - && (previousToken.kind === SyntaxKind.BreakKeyword || previousToken.kind === SyntaxKind.ContinueKeyword || previousToken.kind === SyntaxKind.Identifier)) { + if ( + previousToken && isBreakOrContinueStatement(previousToken.parent) + && (previousToken.kind === SyntaxKind.BreakKeyword || previousToken.kind === SyntaxKind.ContinueKeyword || previousToken.kind === SyntaxKind.Identifier) + ) { return getLabelCompletionAtPosition(previousToken.parent); } @@ -742,7 +751,9 @@ export function getCompletionsAtPosition( checker, compilerOptions, preferences, - /*tagNameOnly*/ true)]); + /*tagNameOnly*/ true, + ), + ]); case CompletionDataKind.JsDocTag: // If the current position is a jsDoc tag, only tags should be provided for completion return jsdocCompletionInfo([ @@ -753,7 +764,9 @@ export function getCompletionsAtPosition( checker, compilerOptions, preferences, - /*tagNameOnly*/ false)]); + /*tagNameOnly*/ false, + ), + ]); case CompletionDataKind.JsDocParameterName: return jsdocCompletionInfo(JsDoc.getJSDocParameterNameCompletions(completionData.tag)); case CompletionDataKind.Keywords: @@ -876,7 +889,8 @@ function getJSDocParameterCompletions( checker: TypeChecker, options: CompilerOptions, preferences: UserPreferences, - tagNameOnly: boolean): CompletionEntry[] { + tagNameOnly: boolean, +): CompletionEntry[] { const currentToken = getTokenAtPosition(sourceFile, position); if (!isJSDocTag(currentToken) && !isJSDoc(currentToken)) { return []; @@ -900,17 +914,17 @@ function getJSDocParameterCompletions( if (isIdentifier(param.name)) { // Named parameter const tabstopCounter = { tabstop: 1 }; const paramName = param.name.text; - let displayText = - getJSDocParamAnnotation( - paramName, - param.initializer, - param.dotDotDotToken, - isJs, - /*isObject*/ false, - /*isSnippet*/ false, - checker, - options, - preferences); + let displayText = getJSDocParamAnnotation( + paramName, + param.initializer, + param.dotDotDotToken, + isJs, + /*isObject*/ false, + /*isSnippet*/ false, + checker, + options, + preferences, + ); let snippetText = isSnippet ? getJSDocParamAnnotation( paramName, @@ -922,7 +936,8 @@ function getJSDocParameterCompletions( checker, options, preferences, - tabstopCounter) + tabstopCounter, + ) : undefined; if (tagNameOnly) { // Remove `@` displayText = displayText.slice(1); @@ -938,17 +953,17 @@ function getJSDocParameterCompletions( } else if (param.parent.parameters.indexOf(param) === paramTagCount) { // Destructuring parameter; do it positionally const paramPath = `param${paramTagCount}`; - const displayTextResult = - generateJSDocParamTagsForDestructuring( - paramPath, - param.name, - param.initializer, - param.dotDotDotToken, - isJs, - /*isSnippet*/ false, - checker, - options, - preferences,); + const displayTextResult = generateJSDocParamTagsForDestructuring( + paramPath, + param.name, + param.initializer, + param.dotDotDotToken, + isJs, + /*isSnippet*/ false, + checker, + options, + preferences, + ); const snippetTextResult = isSnippet ? generateJSDocParamTagsForDestructuring( paramPath, @@ -959,7 +974,8 @@ function getJSDocParameterCompletions( /*isSnippet*/ true, checker, options, - preferences,) + preferences, + ) : undefined; let displayText = displayTextResult.join(getNewLineCharacter(options) + "* "); let snippetText = snippetTextResult?.join(getNewLineCharacter(options) + "* "); @@ -987,7 +1003,8 @@ function generateJSDocParamTagsForDestructuring( isSnippet: boolean, checker: TypeChecker, options: CompilerOptions, - preferences: UserPreferences): string[] { + preferences: UserPreferences, +): string[] { if (!isJs) { return [ getJSDocParamAnnotation( @@ -1000,7 +1017,8 @@ function generateJSDocParamTagsForDestructuring( checker, options, preferences, - { tabstop: 1 }) + { tabstop: 1 }, + ), ]; } return patternWorker(path, pattern, initializer, dotDotDotToken, { tabstop: 1 }); @@ -1010,22 +1028,23 @@ function generateJSDocParamTagsForDestructuring( pattern: BindingPattern, initializer: Expression | undefined, dotDotDotToken: DotDotDotToken | undefined, - counter: TabStopCounter): string[] { + counter: TabStopCounter, + ): string[] { if (isObjectBindingPattern(pattern) && !dotDotDotToken) { const oldTabstop = counter.tabstop; const childCounter = { tabstop: oldTabstop }; - const rootParam = - getJSDocParamAnnotation( - path, - initializer, - dotDotDotToken, - isJs, - /*isObject*/ true, - isSnippet, - checker, - options, - preferences, - childCounter); + const rootParam = getJSDocParamAnnotation( + path, + initializer, + dotDotDotToken, + isJs, + /*isObject*/ true, + isSnippet, + checker, + options, + preferences, + childCounter, + ); let childTags: string[] | undefined = []; for (const element of pattern.elements) { const elementTags = elementWorker(path, element, childCounter); @@ -1053,8 +1072,9 @@ function generateJSDocParamTagsForDestructuring( checker, options, preferences, - counter) - ]; + counter, + ), + ]; } // Assumes binding element is inside object binding pattern. @@ -1077,7 +1097,9 @@ function generateJSDocParamTagsForDestructuring( checker, options, preferences, - counter)]; + counter, + ), + ]; } else if (element.propertyName) { // `{ b: {...} }` or `{ b: [...] }` const propertyName = tryGetTextOfPropertyName(element.propertyName); @@ -1102,7 +1124,8 @@ function getJSDocParamAnnotation( checker: TypeChecker, options: CompilerOptions, preferences: UserPreferences, - tabstopCounter?: TabStopCounter) { + tabstopCounter?: TabStopCounter, +) { if (isSnippet) { Debug.assertIsDefined(tabstopCounter); } @@ -1124,7 +1147,7 @@ function getJSDocParamAnnotation( if (!(inferredType.flags & (TypeFlags.Any | TypeFlags.Void))) { const sourceFile = initializer.getSourceFile(); const quotePreference = getQuotePreference(sourceFile, preferences); - const builderFlags = (quotePreference === QuotePreference.Single ? NodeBuilderFlags.UseSingleQuotesForStringLiteralType : NodeBuilderFlags.None); + const builderFlags = quotePreference === QuotePreference.Single ? NodeBuilderFlags.UseSingleQuotesForStringLiteralType : NodeBuilderFlags.None; const typeNode = checker.typeToTypeNode(inferredType, findAncestor(initializer, isFunctionLike), builderFlags); if (typeNode) { const printer = isSnippet @@ -1136,7 +1159,7 @@ function getJSDocParamAnnotation( : createPrinter({ removeComments: true, module: options.module, - target: options.target + target: options.target, }); setEmitFlags(typeNode, EmitFlags.SingleLine); type = printer.printNode(EmitHint.Unspecified, typeNode, sourceFile); @@ -1193,8 +1216,10 @@ function keywordCompletionData(keywordFilters: KeywordCompletionFilters, filterO function keywordFiltersFromSyntaxKind(keywordCompletion: TokenSyntaxKind): KeywordCompletionFilters { switch (keywordCompletion) { - case SyntaxKind.TypeKeyword: return KeywordCompletionFilters.TypeKeyword; - default: Debug.fail("Unknown mapping from SyntaxKind to KeywordCompletionFilters"); + case SyntaxKind.TypeKeyword: + return KeywordCompletionFilters.TypeKeyword; + default: + Debug.fail("Unknown mapping from SyntaxKind to KeywordCompletionFilters"); } } @@ -1298,7 +1323,7 @@ function completionInfoFromData( symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, - includeSymbol + includeSymbol, ); if (keywordFilters !== KeywordCompletionFilters.None) { @@ -1328,11 +1353,13 @@ function completionInfoFromData( } let caseBlock: CaseBlock | undefined; - if (preferences.includeCompletionsWithInsertText + if ( + preferences.includeCompletionsWithInsertText && contextToken && !isRightOfOpenTag && !isRightOfDotOrQuestionDot - && (caseBlock = findAncestor(contextToken, isCaseBlock))) { + && (caseBlock = findAncestor(contextToken, isCaseBlock)) + ) { const cases = getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, compilerOptions, host, program, formatContext); if (cases) { entries.push(cases.entry); @@ -1361,8 +1388,8 @@ function getExhaustiveCaseSnippets( options: CompilerOptions, host: LanguageServiceHost, program: Program, - formatContext: formatting.FormatContext | undefined): { entry: CompletionEntry, importAdder: codefix.ImportAdder } | undefined { - + formatContext: formatting.FormatContext | undefined, +): { entry: CompletionEntry; importAdder: codefix.ImportAdder; } | undefined { const clauses = caseBlock.clauses; const checker = program.getTypeChecker(); const switchType = checker.getTypeAtLocation(caseBlock.parent.expression); @@ -1422,14 +1449,14 @@ function getExhaustiveCaseSnippets( removeComments: true, module: options.module, target: options.target, - newLine: getNewLineKind(newLineChar) + newLine: getNewLineKind(newLineChar), }); const printNode = formatContext ? (node: Node) => printer.printAndFormatNode(EmitHint.Unspecified, node, sourceFile, formatContext) : (node: Node) => printer.printNode(EmitHint.Unspecified, node, sourceFile); const insertText = map(newClauses, (clause, i) => { if (preferences.includeCompletionsWithSnippetText) { - return `${printNode(clause)}$${i+1}`; + return `${printNode(clause)}$${i + 1}`; } return `${printNode(clause)}`; }).join(newLineChar); @@ -1458,10 +1485,8 @@ function typeNodeToExpression(typeNode: TypeNode, languageVersion: ScriptTarget, const typeName = (typeNode as TypeReferenceNode).typeName; return entityNameToExpression(typeName, languageVersion, quotePreference); case SyntaxKind.IndexedAccessType: - const objectExpression = - typeNodeToExpression((typeNode as IndexedAccessTypeNode).objectType, languageVersion, quotePreference); - const indexExpression = - typeNodeToExpression((typeNode as IndexedAccessTypeNode).indexType, languageVersion, quotePreference); + const objectExpression = typeNodeToExpression((typeNode as IndexedAccessTypeNode).objectType, languageVersion, quotePreference); + const indexExpression = typeNodeToExpression((typeNode as IndexedAccessTypeNode).indexType, languageVersion, quotePreference); return objectExpression && indexExpression && factory.createElementAccessExpression(objectExpression, indexExpression); @@ -1494,12 +1519,14 @@ function entityNameToExpression(entityName: EntityName, languageVersion: ScriptT if (canUsePropertyAccess(unescapedName, languageVersion)) { return factory.createPropertyAccessExpression( entityNameToExpression(entityName.left, languageVersion, quotePreference), - unescapedName); + unescapedName, + ); } else { return factory.createElementAccessExpression( entityNameToExpression(entityName.left, languageVersion, quotePreference), - factory.createStringLiteral(unescapedName, quotePreference === QuotePreference.Single)); + factory.createStringLiteral(unescapedName, quotePreference === QuotePreference.Single), + ); } } @@ -1565,7 +1592,8 @@ function getJSCompletionEntries( position: number, uniqueNames: UniqueNameSet, target: ScriptTarget, - entries: SortedArray): void { + entries: SortedArray, +): void { getNameTable(sourceFile).forEach((pos, name) => { // Skip identifiers produced only from the current location if (pos === position) { @@ -1579,7 +1607,7 @@ function getJSCompletionEntries( kind: ScriptElementKind.warning, kindModifiers: "", sortText: SortText.JavascriptIdentifiers, - isFromUncheckedFile: true + isFromUncheckedFile: true, }, compareCompletionEntries); } }); @@ -1618,7 +1646,7 @@ function createCompletionEntry( formatContext: formatting.FormatContext | undefined, isJsxIdentifierExpected: boolean | undefined, isRightOfOpenTag: boolean | undefined, - includeSymbol: boolean + includeSymbol: boolean, ): CompletionEntry | undefined { let insertText: string | undefined; let filterText: string | undefined; @@ -1702,22 +1730,25 @@ function createCompletionEntry( // // Completion should add a comma after "red" and provide completions for b if (completionKind === CompletionKind.ObjectPropertyDeclaration && contextToken && findPrecedingToken(contextToken.pos, sourceFile, contextToken)?.kind !== SyntaxKind.CommaToken) { - if (isMethodDeclaration(contextToken.parent.parent) || + if ( + isMethodDeclaration(contextToken.parent.parent) || isGetAccessorDeclaration(contextToken.parent.parent) || isSetAccessorDeclaration(contextToken.parent.parent) || isSpreadAssignment(contextToken.parent) || findAncestor(contextToken.parent, isPropertyAssignment)?.getLastToken(sourceFile) === contextToken || - isShorthandPropertyAssignment(contextToken.parent) && getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line) { - + isShorthandPropertyAssignment(contextToken.parent) && getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line + ) { source = CompletionSource.ObjectLiteralMemberWithComma; hasAction = true; } } - if (preferences.includeCompletionsWithClassMemberSnippets && + if ( + preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === CompletionKind.MemberLike && - isClassLikeMemberCompletion(symbol, location, sourceFile)) { + isClassLikeMemberCompletion(symbol, location, sourceFile) + ) { let importAdder; const memberCompletionEntry = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, position, contextToken, formatContext); if (memberCompletionEntry) { @@ -1742,14 +1773,17 @@ function createCompletionEntry( sortText = SortText.SortBelow(sortText); } - if (isJsxIdentifierExpected && !isRightOfOpenTag + if ( + isJsxIdentifierExpected && !isRightOfOpenTag && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle - && preferences.jsxAttributeCompletionStyle !== "none" && !(isJsxAttribute(location.parent) && location.parent.initializer)) { + && preferences.jsxAttributeCompletionStyle !== "none" && !(isJsxAttribute(location.parent) && location.parent.initializer) + ) { let useBraces = preferences.jsxAttributeCompletionStyle === "braces"; const type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); // If is boolean like or undefined, don't return a snippet we want just to return the completion. - if (preferences.jsxAttributeCompletionStyle === "auto" + if ( + preferences.jsxAttributeCompletionStyle === "auto" && !(type.flags & TypeFlags.BooleanLike) && !(type.flags & TypeFlags.Union && find((type as UnionType).types, type => !!(type.flags & TypeFlags.BooleanLike))) ) { @@ -1812,7 +1846,7 @@ function createCompletionEntry( isPackageJsonImport: originIsPackageJsonImport(origin) || undefined, isImportStatementCompletion: !!importStatementCompletion || undefined, data, - ...includeSymbol ? { symbol } : undefined + ...includeSymbol ? { symbol } : undefined, }; } @@ -1823,8 +1857,7 @@ function isClassLikeMemberCompletion(symbol: Symbol, location: Node, sourceFile: } // Completion symbol must be for a class member. - const memberFlags = - SymbolFlags.ClassMember + const memberFlags = SymbolFlags.ClassMember & SymbolFlags.EnumMemberExcludes; /* In `class C { @@ -1876,7 +1909,7 @@ function getEntryForMemberCompletion( position: number, contextToken: Node | undefined, formatContext: formatting.FormatContext | undefined, -): { insertText: string, filterText?: string, isSnippet?: true, importAdder?: codefix.ImportAdder, eraseRange?: TextRange } | undefined { +): { insertText: string; filterText?: string; isSnippet?: true; importAdder?: codefix.ImportAdder; eraseRange?: TextRange; } | undefined { const classLikeDeclaration = findAncestor(location, isClassLike); if (!classLikeDeclaration) { return undefined; // This should never happen. @@ -1937,8 +1970,10 @@ function getEntryForMemberCompletion( if (isAbstract) { requiredModifiers |= ModifierFlags.Abstract; } - if (isClassElement(node) - && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === MemberOverrideStatus.NeedsOverride) { + if ( + isClassElement(node) + && checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === MemberOverrideStatus.NeedsOverride + ) { requiredModifiers |= ModifierFlags.Override; } if (!completionNodes.length) { @@ -1953,7 +1988,8 @@ function getEntryForMemberCompletion( }, body, codefix.PreserveOptionalFlags.Property, - !!isAbstract); + !!isAbstract, + ); if (completionNodes.length) { const isMethod = symbol.flags & SymbolFlags.Method; @@ -1994,13 +2030,15 @@ function getEntryForMemberCompletion( format, factory.createNodeArray(completionNodes), sourceFile, - formatContext); + formatContext, + ); } else { // Otherwise, just use emitter to print the new nodes. insertText = printer.printSnippetList( format, factory.createNodeArray(completionNodes), - sourceFile); + sourceFile, + ); } } @@ -2010,10 +2048,13 @@ function getEntryForMemberCompletion( function getPresentModifiers( contextToken: Node | undefined, sourceFile: SourceFile, - position: number): { modifiers: ModifierFlags, decorators?: Decorator[], range?: TextRange } { - if (!contextToken || + position: number, +): { modifiers: ModifierFlags; decorators?: Decorator[]; range?: TextRange; } { + if ( + !contextToken || getLineAndCharacterOfPosition(sourceFile, position).line - > getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line) { + > getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line + ) { return { modifiers: ModifierFlags.None }; } let modifiers = ModifierFlags.None; @@ -2076,7 +2117,7 @@ function getEntryForObjectLiteralMethodCompletion( options: CompilerOptions, preferences: UserPreferences, formatContext: formatting.FormatContext | undefined, -): { insertText: string, isSnippet?: true, labelDetails: CompletionEntryLabelDetails } | undefined { +): { insertText: string; isSnippet?: true; labelDetails: CompletionEntryLabelDetails; } | undefined { const isSnippet = preferences.includeCompletionsWithSnippetText || undefined; let insertText: string = name; @@ -2115,11 +2156,11 @@ function getEntryForObjectLiteralMethodCompletion( method.questionToken, method.typeParameters, method.parameters, - method.type); + method.type, + ); const labelDetails = { detail: signaturePrinter.printNode(EmitHint.Unspecified, methodSignature, sourceFile) }; return { isSnippet, insertText, labelDetails }; - } function createObjectLiteralMethod( @@ -2187,7 +2228,8 @@ function createObjectLiteralMethod( /*questionToken*/ undefined, /*type*/ undefined, typedParam.initializer, - )); + ) + ); return factory.createMethodDeclaration( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -2196,8 +2238,9 @@ function createObjectLiteralMethod( /*typeParameters*/ undefined, parameters, /*type*/ undefined, - body); - } + body, + ); + } default: return undefined; } @@ -2276,7 +2319,8 @@ function createSnippetPrinter( text: printUnescapedSnippetList( format, list, - sourceFile), + sourceFile, + ), getLineAndCharacterOfPosition(pos: number) { return getLineAndCharacterOfPosition(this, pos); }, @@ -2291,7 +2335,8 @@ function createSnippetPrinter( sourceFile.languageVariant, /* indentation */ 0, /* delta */ 0, - { ...formatContext, options: formatOptions }); + { ...formatContext, options: formatOptions }, + ); }); const allChanges = escapes @@ -2317,12 +2362,14 @@ function createSnippetPrinter( hint: EmitHint, node: Node, sourceFile: SourceFile, - formatContext: formatting.FormatContext): string { + formatContext: formatting.FormatContext, + ): string { const syntheticFile = { text: printUnescapedNode( hint, node, - sourceFile), + sourceFile, + ), getLineAndCharacterOfPosition(pos: number) { return getLineAndCharacterOfPosition(this, pos); }, @@ -2336,7 +2383,8 @@ function createSnippetPrinter( sourceFile.languageVariant, /* indentation */ 0, /* delta */ 0, - { ...formatContext, options: formatOptions }); + { ...formatContext, options: formatOptions }, + ); const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) @@ -2402,8 +2450,7 @@ function completionEntryDataToSymbolOriginInfo(data: CompletionEntryData, comple function getInsertTextAndReplacementSpanForImportCompletion(name: string, importStatementCompletion: ImportStatementCompletionInfo, origin: SymbolOriginInfoResolvedExport, useSemicolons: boolean, sourceFile: SourceFile, options: CompilerOptions, preferences: UserPreferences) { const replacementSpan = importStatementCompletion.replacementSpan; const quotedModuleSpecifier = escapeSnippetText(quote(sourceFile, preferences, origin.moduleSpecifier)); - const exportKind = - origin.isDefaultExport ? ExportKind.Default : + const exportKind = origin.isDefaultExport ? ExportKind.Default : origin.exportName === InternalSymbolName.ExportEquals ? ExportKind.ExportEquals : ExportKind.Named; const tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : ""; @@ -2413,14 +2460,18 @@ function getInsertTextAndReplacementSpanForImportCompletion(name: string, import const importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? `${tokenToString(SyntaxKind.TypeKeyword)} ` : ""; const suffix = useSemicolons ? ";" : ""; switch (importKind) { - case ImportKind.CommonJS: return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` }; - case ImportKind.Default: return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` }; - case ImportKind.Namespace: return { replacementSpan, insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` }; - case ImportKind.Named: return { replacementSpan, insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` }; + case ImportKind.CommonJS: + return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` }; + case ImportKind.Default: + return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` }; + case ImportKind.Namespace: + return { replacementSpan, insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` }; + case ImportKind.Named: + return { replacementSpan, insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` }; } } -function quotePropertyName(sourceFile: SourceFile, preferences: UserPreferences, name: string,): string { +function quotePropertyName(sourceFile: SourceFile, preferences: UserPreferences, name: string): string { if (/^\d+$/.test(name)) { return name; } @@ -2475,7 +2526,7 @@ export function getCompletionEntriesFromSymbols( symbolToSortTextMap?: SymbolSortTextMap, isJsxIdentifierExpected?: boolean, isRightOfOpenTag?: boolean, - includeSymbol = false + includeSymbol = false, ): UniqueNameSet { const start = timestamp(); const variableOrParameterDeclaration = getVariableOrParameterDeclaration(contextToken, location); @@ -2496,7 +2547,7 @@ export function getCompletionEntriesFromSymbols( const { name, needsConvertPropertyAccess } = info; const originalSortText = symbolToSortTextMap?.[getSymbolId(symbol)] ?? SortText.LocationPriority; - const sortText = (isDeprecated(symbol, typeChecker) ? SortText.Deprecated(originalSortText) : originalSortText); + const sortText = isDeprecated(symbol, typeChecker) ? SortText.Deprecated(originalSortText) : originalSortText; const entry = createCompletionEntry( symbol, sortText, @@ -2521,7 +2572,7 @@ export function getCompletionEntriesFromSymbols( formatContext, isJsxIdentifierExpected, isRightOfOpenTag, - includeSymbol + includeSymbol, ); if (!entry) { continue; @@ -2560,10 +2611,12 @@ export function getCompletionEntriesFromSymbols( // `function f(a = /* no 'a' and 'b' here */, b) { }` or // `function f(a: T) { }` const symbolDeclaration = symbol.valueDeclaration ?? symbol.declarations?.[0]; - if (variableOrParameterDeclaration && symbolDeclaration && ( - (isTypeParameterDeclaration(variableOrParameterDeclaration) && isTypeParameterDeclaration(symbolDeclaration)) || - (isParameter(variableOrParameterDeclaration) && isParameter(symbolDeclaration)) - )) { + if ( + variableOrParameterDeclaration && symbolDeclaration && ( + (isTypeParameterDeclaration(variableOrParameterDeclaration) && isTypeParameterDeclaration(symbolDeclaration)) || + (isParameter(variableOrParameterDeclaration) && isParameter(symbolDeclaration)) + ) + ) { const symbolDeclarationPos = symbolDeclaration.pos; const parameters = isParameter(variableOrParameterDeclaration) ? variableOrParameterDeclaration.parent.parameters : isInferTypeNode(variableOrParameterDeclaration.parent) ? undefined : @@ -2581,11 +2634,13 @@ export function getCompletionEntriesFromSymbols( const symbolOrigin = skipAlias(symbol, typeChecker); // We only want to filter out the global keywords // Auto Imports are not available for scripts so this conditional is always false - if (!!sourceFile.externalModuleIndicator + if ( + !!sourceFile.externalModuleIndicator && !compilerOptions.allowUmdGlobalAccess && symbolToSortTextMap[getSymbolId(symbol)] === SortText.GlobalsOrKeywords && (symbolToSortTextMap[getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions - || symbolToSortTextMap[getSymbolId(symbolOrigin)] === SortText.LocationPriority)) { + || symbolToSortTextMap[getSymbolId(symbolOrigin)] === SortText.LocationPriority) + ) { return false; } @@ -2631,7 +2686,7 @@ function getLabelStatementCompletions(node: Node): CompletionEntry[] { name, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.label, - sortText: SortText.LocationPriority + sortText: SortText.LocationPriority, }); } } @@ -2658,7 +2713,7 @@ function getSymbolCompletionFromEntryId( entryId: CompletionEntryIdentifier, host: LanguageServiceHost, preferences: UserPreferences, -): SymbolCompletion | { type: "request", request: Request } | { type: "literal", literal: string | number | PseudoBigInt } | { type: "cases" } | { type: "none" } { +): SymbolCompletion | { type: "request"; request: Request; } | { type: "literal"; literal: string | number | PseudoBigInt; } | { type: "cases"; } | { type: "none"; } { if (entryId.source === CompletionSource.SwitchCases) { return { type: "cases" }; } @@ -2701,10 +2756,11 @@ function getSymbolCompletionFromEntryId( const origin = symbolToOriginInfoMap[index]; const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); return info && info.name === entryId.name && ( - entryId.source === CompletionSource.ClassMemberSnippet && symbol.flags & SymbolFlags.ClassMember - || entryId.source === CompletionSource.ObjectLiteralMethodSnippet && symbol.flags & (SymbolFlags.Property | SymbolFlags.Method) - || getSourceFromOrigin(origin) === entryId.source - || entryId.source === CompletionSource.ObjectLiteralMemberWithComma) + entryId.source === CompletionSource.ClassMemberSnippet && symbol.flags & SymbolFlags.ClassMember + || entryId.source === CompletionSource.ObjectLiteralMethodSnippet && symbol.flags & (SymbolFlags.Property | SymbolFlags.Method) + || getSourceFromOrigin(origin) === entryId.source + || entryId.source === CompletionSource.ObjectLiteralMemberWithComma + ) ? { type: "symbol" as const, symbol, location, origin, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation } : undefined; }) || { type: "none" }; @@ -2774,11 +2830,13 @@ export function getCompletionEntryDetails( program.getCompilerOptions(), host, program, - /*formatContext*/ undefined)!; + /*formatContext*/ undefined, + )!; if (importAdder.hasFixes()) { const changes = textChanges.ChangeTracker.with( { host, formatContext, preferences }, - importAdder.writeFixes); + importAdder.writeFixes, + ); return { name: entry.name, kind: ScriptElementKind.unknown, @@ -2813,10 +2871,7 @@ function createSimpleDetails(name: string, kind: ScriptElementKind, kind2: Symbo /** @internal */ export function createCompletionDetailsForSymbol(symbol: Symbol, name: string, checker: TypeChecker, sourceFile: SourceFile, location: Node, cancellationToken: CancellationToken, codeActions?: CodeAction[], sourceDisplay?: SymbolDisplayPart[]): CompletionEntryDetails { - const { displayParts, documentation, symbolKind, tags } = - checker.runWithCancellationToken(cancellationToken, checker => - SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, SemanticMeaning.All) - ); + const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken(cancellationToken, checker => SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, SemanticMeaning.All)); return createCompletionDetails(name, SymbolDisplay.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } @@ -2865,7 +2920,8 @@ function getCompletionEntryCodeActionsAndSourceDisplay( location, position, contextToken, - formatContext)!; + formatContext, + )!; if (importAdder || eraseRange) { const changes = textChanges.ChangeTracker.with( { host, formatContext, preferences }, @@ -2876,7 +2932,8 @@ function getCompletionEntryCodeActionsAndSourceDisplay( if (eraseRange) { tracker.deleteRange(sourceFile, eraseRange); } - }); + }, + ); return { sourceDisplay: undefined, codeActions: [{ @@ -2894,7 +2951,8 @@ function getCompletionEntryCodeActionsAndSourceDisplay( program, host, formatContext, - preferences); + preferences, + ); Debug.assertIsDefined(codeAction, "Expected to have a code action for promoting type-only alias"); return { codeActions: [codeAction], sourceDisplay: undefined }; @@ -2903,7 +2961,7 @@ function getCompletionEntryCodeActionsAndSourceDisplay( if (source === CompletionSource.ObjectLiteralMemberWithComma && contextToken) { const changes = textChanges.ChangeTracker.with( { host, formatContext, preferences }, - tracker => tracker.insertText(sourceFile, contextToken.end, ",") + tracker => tracker.insertText(sourceFile, contextToken.end, ","), ); if (changes) { @@ -2937,7 +2995,8 @@ function getCompletionEntryCodeActionsAndSourceDisplay( formatContext, previousToken && isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences, - cancellationToken); + cancellationToken, + ); Debug.assert(!data?.moduleSpecifier || moduleSpecifier === data.moduleSpecifier); return { sourceDisplay: [textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -2956,7 +3015,13 @@ export function getCompletionEntrySymbol( return completion.type === "symbol" ? completion.symbol : undefined; } -const enum CompletionDataKind { Data, JsDocTagName, JsDocTag, JsDocParameterName, Keywords } +const enum CompletionDataKind { + Data, + JsDocTagName, + JsDocTag, + JsDocParameterName, + Keywords, +} /** * true: after the `=` sign but no identifier has been typed yet. Else is the Identifier after the initializer. * @@ -2991,9 +3056,9 @@ interface CompletionData { readonly flags: CompletionInfoFlags; } type Request = - | { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } - | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag } - | { readonly kind: CompletionDataKind.Keywords, keywordCompletions: readonly CompletionEntry[], isNewIdentifierLocation: boolean }; + | { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag; } + | { readonly kind: CompletionDataKind.JsDocParameterName; tag: JSDocParameterTag; } + | { readonly kind: CompletionDataKind.Keywords; keywordCompletions: readonly CompletionEntry[]; isNewIdentifierLocation: boolean; }; /** @internal */ export const enum CompletionKind { @@ -3045,9 +3110,9 @@ function getContextualType(previousToken: Node, position: number, sourceFile: So // 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, ContextFlags.Completions) || checker.getContextualType(previousToken as Expression); + // completion at `x ===/**/` should be for the right side + checker.getTypeAtLocation(parent.left) : + checker.getContextualType(previousToken as Expression, ContextFlags.Completions) || checker.getContextualType(previousToken as Expression); } } @@ -3129,10 +3194,12 @@ function getCompletionData( const typeExpression = tryGetTypeExpressionFromTag(tag); if (typeExpression) { currentToken = getTokenAtPosition(sourceFile, position); - if (!currentToken || + if ( + !currentToken || (!isDeclarationName(currentToken) && (currentToken.parent.kind !== SyntaxKind.JSDocPropertyTag || - (currentToken.parent as JSDocPropertyTag).name !== currentToken))) { + (currentToken.parent as JSDocPropertyTag).name !== currentToken)) + ) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(typeExpression); } @@ -3214,11 +3281,13 @@ function getCompletionData( propertyAccessToConvert = parent as PropertyAccessExpression; node = propertyAccessToConvert.expression; const leftmostAccessExpression = getLeftmostAccessExpression(propertyAccessToConvert); - if (nodeIsMissing(leftmostAccessExpression) || + if ( + nodeIsMissing(leftmostAccessExpression) || ((isCallExpression(node) || isFunctionLike(node)) && node.end === contextToken.pos && node.getChildCount(sourceFile) && - last(node.getChildren(sourceFile)).kind !== SyntaxKind.CloseParenToken)) { + last(node.getChildren(sourceFile)).kind !== SyntaxKind.CloseParenToken) + ) { // This is likely dot from incorrectly parsed expression and user is starting to write spread // eg: Math.min(./**/) // const x = function (./**/) {} @@ -3308,8 +3377,10 @@ function getCompletionData( case SyntaxKind.JsxAttribute: // For `
`, `parent` will be JsxAttribute and `previousToken` will be its initializer - if ((parent as JsxAttribute).initializer === previousToken && - previousToken.end < position) { + if ( + (parent as JsxAttribute).initializer === previousToken && + previousToken.end < position + ) { isJsxIdentifierExpected = true; break; } @@ -3321,9 +3392,11 @@ function getCompletionData( isJsxIdentifierExpected = true; // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. - if (parent !== previousToken.parent && + if ( + parent !== previousToken.parent && !(parent as JsxAttribute).initializer && - findChildOfKind(parent, SyntaxKind.EqualsToken, sourceFile)) { + findChildOfKind(parent, SyntaxKind.EqualsToken, sourceFile) + ) { isJsxInitializer = previousToken as Identifier; } } @@ -3385,7 +3458,8 @@ function getCompletionData( const isLiteralExpected = !tryCast(previousToken, isStringLiteralLike) && !isJsxIdentifierExpected; const literals = !isLiteralExpected ? [] : mapDefined( contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), - t => t.isLiteral() && !(t.flags & TypeFlags.EnumLiteral) ? t.value : undefined); + t => t.isLiteral() && !(t.flags & TypeFlags.EnumLiteral) ? t.value : undefined, + ); const recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); return { @@ -3474,14 +3548,13 @@ function getCompletionData( Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); const isValidValueAccess = (symbol: Symbol) => typeChecker.isValidPropertyAccess(isImportType ? node as ImportTypeNode : (node.parent as PropertyAccessExpression), symbol.name); const isValidTypeAccess = (symbol: Symbol) => symbolCanBeReferencedAtTypeLocation(symbol, typeChecker); - const isValidAccess: (symbol: Symbol) => boolean = - isNamespaceName - // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. - ? symbol => !!(symbol.flags & SymbolFlags.Namespace) && !symbol.declarations?.every(d => d.parent === node.parent) - : isRhsOfImportDeclaration ? - // Any kind is allowed when dotting off namespace in internal import equals declaration - symbol => isValidTypeAccess(symbol) || isValidValueAccess(symbol) : - isTypeLocation || insideJsDocTagTypeExpression ? isValidTypeAccess : isValidValueAccess; + const isValidAccess: (symbol: Symbol) => boolean = isNamespaceName + // At `namespace N.M/**/`, if this is the only declaration of `M`, don't include `M` as a completion. + ? symbol => !!(symbol.flags & SymbolFlags.Namespace) && !symbol.declarations?.every(d => d.parent === node.parent) + : isRhsOfImportDeclaration ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + symbol => isValidTypeAccess(symbol) || isValidValueAccess(symbol) : + isTypeLocation || insideJsDocTagTypeExpression ? isValidTypeAccess : isValidValueAccess; for (const exportedSymbol of exportedSymbols) { if (isValidAccess(exportedSymbol)) { symbols.push(exportedSymbol); @@ -3489,15 +3562,16 @@ function getCompletionData( } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && + if ( + !isTypeLocation && !insideJsDocTagTypeExpression && symbol.declarations && - symbol.declarations.some(d => d.kind !== SyntaxKind.SourceFile && d.kind !== SyntaxKind.ModuleDeclaration && d.kind !== SyntaxKind.EnumDeclaration)) { + symbol.declarations.some(d => d.kind !== SyntaxKind.SourceFile && d.kind !== SyntaxKind.ModuleDeclaration && d.kind !== SyntaxKind.EnumDeclaration) + ) { let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); let insertQuestionDot = false; if (type.isNullableType()) { - const canCorrectToQuestionDot = - isRightOfDot && + const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; @@ -3526,8 +3600,7 @@ function getCompletionData( if (!isTypeLocation) { let insertQuestionDot = false; if (type.isNullableType()) { - const canCorrectToQuestionDot = - isRightOfDot && + const canCorrectToQuestionDot = isRightOfDot && !isRightOfQuestionDot && preferences.includeAutomaticOptionalChainCompletions !== false; @@ -3596,7 +3669,8 @@ function getCompletionData( const index = symbols.length; symbols.push(firstAccessibleSymbol); const moduleSymbol = firstAccessibleSymbol.parent; - if (!moduleSymbol || + if ( + !moduleSymbol || !isExternalModuleSymbol(moduleSymbol) || typeChecker.tryGetMemberInModuleExportsAndProperties(firstAccessibleSymbol.name, moduleSymbol) !== firstAccessibleSymbol ) { @@ -3604,14 +3678,18 @@ function getCompletionData( } else { const fileName = isExternalModuleNameRelative(stripQuotes(moduleSymbol.name)) ? getSourceFileOfModule(moduleSymbol)?.fileName : undefined; - const { moduleSpecifier } = (importSpecifierResolver ||= codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)).getModuleSpecifierForBestExportInfo([{ - exportKind: ExportKind.Named, - moduleFileName: fileName, - isFromPackageJson: false, - moduleSymbol, - symbol: firstAccessibleSymbol, - targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags, - }], position, isValidTypeOnlyAliasUseSite(location)) || {}; + const { moduleSpecifier } = (importSpecifierResolver ||= codefix.createImportSpecifierResolver(sourceFile, program, host, preferences)).getModuleSpecifierForBestExportInfo( + [{ + exportKind: ExportKind.Named, + moduleFileName: fileName, + isFromPackageJson: false, + moduleSymbol, + symbol: firstAccessibleSymbol, + targetFlags: skipAlias(firstAccessibleSymbol, typeChecker).flags, + }], + position, + isValidTypeOnlyAliasUseSite(location), + ) || {}; if (moduleSpecifier) { const origin: SymbolOriginInfoResolvedExport = { @@ -3762,8 +3840,10 @@ function getCompletionData( Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); for (let i = 0; i < symbols.length; i++) { const symbol = symbols[i]; - if (!typeChecker.isArgumentsSymbol(symbol) && - !some(symbol.declarations, d => d.getSourceFile() === sourceFile)) { + if ( + !typeChecker.isArgumentsSymbol(symbol) && + !some(symbol.declarations, d => d.getSourceFile() === sourceFile) + ) { symbolToSortTextMap[getSymbolId(symbol)] = SortText.GlobalsOrKeywords; } if (typeOnlyAliasNeedsPromotion && !(symbol.flags & SymbolFlags.Value)) { @@ -3825,16 +3905,16 @@ function getCompletionData( return insideJsDocTagTypeExpression || !!importStatementCompletion && isTypeOnlyImportOrExportDeclaration(location.parent) || !isContextTokenValueLocation(contextToken) && - (isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker) - || isPartOfTypeNode(location) - || isContextTokenTypeLocation(contextToken)); + (isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker) + || isPartOfTypeNode(location) + || isContextTokenTypeLocation(contextToken)); } function isContextTokenValueLocation(contextToken: Node) { return contextToken && ((contextToken.kind === SyntaxKind.TypeOfKeyword && (contextToken.parent.kind === SyntaxKind.TypeQuery || isTypeOfExpression(contextToken.parent))) || - (contextToken.kind === SyntaxKind.AssertsKeyword && contextToken.parent.kind === SyntaxKind.TypePredicate)); + (contextToken.kind === SyntaxKind.AssertsKeyword && contextToken.parent.kind === SyntaxKind.TypePredicate)); } function isContextTokenTypeLocation(contextToken: Node): boolean { @@ -3882,8 +3962,7 @@ function getCompletionData( const isAfterTypeOnlyImportSpecifierModifier = previousToken === contextToken && importStatementCompletion; - const lowerCaseTokenText = - isAfterTypeOnlyImportSpecifierModifier ? "" : + const lowerCaseTokenText = isAfterTypeOnlyImportSpecifierModifier ? "" : previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() : ""; @@ -3963,13 +4042,13 @@ function getCompletionData( moduleSymbol: exportInfo.moduleSymbol, isFromPackageJson: exportInfo.isFromPackageJson, }); - } + }, ); hasUnresolvedAutoImports = context.skippedAny(); flags |= context.resolvedAny() ? CompletionInfoFlags.ResolvedModuleSpecifiers : 0; flags |= context.resolvedBeyondLimit() ? CompletionInfoFlags.ResolvedModuleSpecifiersBeyondLimit : 0; - } + }, ); function isImportableExportInfo(info: SymbolExportInfo) { @@ -3990,7 +4069,8 @@ function getCompletionData( preferences, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), - moduleSpecifierCache); + moduleSpecifierCache, + ); } } @@ -4020,7 +4100,8 @@ function getCompletionData( getEmitScriptTarget(compilerOptions), /*origin*/ undefined, CompletionKind.ObjectPropertyDeclaration, - /*jsxIdentifierExpected*/ false); + /*jsxIdentifierExpected*/ false, + ); if (!displayName) { return; } @@ -4033,7 +4114,8 @@ function getCompletionData( host, compilerOptions, preferences, - formatContext); + formatContext, + ); if (!entryProps) { return; } @@ -4118,6 +4200,7 @@ function getCompletionData( const containingNodeKind = contextToken.parent.kind; const tokenKind = keywordForNode(contextToken); // Previous token may have been a keyword that was converted to an identifier. + // dprint-ignore switch (tokenKind) { case SyntaxKind.CommaToken: return containingNodeKind === SyntaxKind.CallExpression // func( a, | @@ -4185,7 +4268,8 @@ function getCompletionData( // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). return (isRegularExpressionLiteral(contextToken) || isStringTextContainingNode(contextToken)) && ( rangeContainsPositionExclusive(contextToken, position) || - position === contextToken.end && (!!contextToken.isUnterminated || isRegularExpressionLiteral(contextToken))); + position === contextToken.end && (!!contextToken.isUnterminated || isRegularExpressionLiteral(contextToken)) + ); } function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols(): GlobalsSearch | undefined { @@ -4294,9 +4378,11 @@ function getCompletionData( const filteredMembers = filterObjectMembersList(typeMembers, Debug.checkDefined(existingMembers)); symbols = concatenate(symbols, filteredMembers); setSortTextToOptionalMember(); - if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression + if ( + objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression && preferences.includeCompletionsWithObjectLiteralMethodSnippets - && preferences.includeCompletionsWithInsertText) { + && preferences.includeCompletionsWithInsertText + ) { transformObjectLiteralMembersSortText(symbolsStartIndex); collectObjectLiteralMethodSymbols(filteredMembers, objectLikeContainer); } @@ -4322,8 +4408,7 @@ function getCompletionData( if (!contextToken) return GlobalsSearch.Continue; // `import { |` or `import { a as 0, | }` or `import { type | }` - const namedImportsOrExports = - contextToken.kind === SyntaxKind.OpenBraceToken || contextToken.kind === SyntaxKind.CommaToken ? tryCast(contextToken.parent, isNamedImportsOrExports) : + const namedImportsOrExports = contextToken.kind === SyntaxKind.OpenBraceToken || contextToken.kind === SyntaxKind.CommaToken ? tryCast(contextToken.parent, isNamedImportsOrExports) : isTypeKeywordTokenOrIdentifier(contextToken) ? tryCast(contextToken.parent.parent, isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return GlobalsSearch.Continue; @@ -4537,9 +4622,11 @@ function getCompletionData( break; case SyntaxKind.CloseBraceToken: - if (parent && + if ( + parent && parent.kind === SyntaxKind.JsxExpression && - parent.parent && parent.parent.kind === SyntaxKind.JsxAttribute) { + parent.parent && parent.parent.kind === SyntaxKind.JsxAttribute + ) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -4568,6 +4655,7 @@ function getCompletionData( function isSolelyIdentifierDefinitionLocation(contextToken: Node): boolean { const parent = contextToken.parent; const containingNodeKind = parent.kind; + // dprint-ignore switch (contextToken.kind) { case SyntaxKind.CommaToken: return containingNodeKind === SyntaxKind.VariableDeclaration || @@ -4668,9 +4756,11 @@ function getCompletionData( // - its modifier of the constructor parameter or // - its name of the parameter and not being edited // eg. constructor(a |<- this shouldnt show completion - if (!isIdentifier(contextToken) || + if ( + !isIdentifier(contextToken) || isParameterPropertyModifier(keywordForNode(contextToken)) || - isCurrentlyEditingNode(contextToken)) { + isCurrentlyEditingNode(contextToken) + ) { return false; } } @@ -4704,20 +4794,24 @@ function getCompletionData( const ancestorPropertyDeclaraion = getAncestor(contextToken.parent, SyntaxKind.PropertyDeclaration); // If we are inside a class declaration and typing `constructor` after property declaration... - if (ancestorPropertyDeclaraion + if ( + ancestorPropertyDeclaraion && contextToken !== previousToken && isClassLike(previousToken.parent.parent) // And the cursor is at the token... - && position <= previousToken.end) { + && position <= previousToken.end + ) { // If we are sure that the previous property declaration is terminated according to newline or semicolon... if (isPreviousPropertyDeclarationTerminated(contextToken, previousToken.end)) { return false; // Don't block completions. } - else if (contextToken.kind !== SyntaxKind.EqualsToken + else if ( + contextToken.kind !== SyntaxKind.EqualsToken // Should not block: `class C { blah = c/**/ }` // But should block: `class C { blah = somewhat c/**/ }` and `class C { blah: SomeType c/**/ }` && (isInitializedProperty(ancestorPropertyDeclaraion as PropertyDeclaration) - || hasType(ancestorPropertyDeclaraion))) { + || hasType(ancestorPropertyDeclaraion)) + ) { return true; } } @@ -4733,7 +4827,7 @@ function getCompletionData( function isPreviousPropertyDeclarationTerminated(contextToken: Node, position: number) { return contextToken.kind !== SyntaxKind.EqualsToken && (contextToken.kind === SyntaxKind.SemicolonToken - || !positionsAreOnSameLine(contextToken.end, position, sourceFile)); + || !positionsAreOnSameLine(contextToken.end, position, sourceFile)); } function isFunctionLikeButNotConstructor(kind: SyntaxKind) { @@ -4769,13 +4863,15 @@ function getCompletionData( const existingMemberNames = new Set<__String>(); for (const m of existingMembers) { // Ignore omitted expressions for missing members - if (m.kind !== SyntaxKind.PropertyAssignment && + if ( + m.kind !== SyntaxKind.PropertyAssignment && m.kind !== SyntaxKind.ShorthandPropertyAssignment && m.kind !== SyntaxKind.BindingElement && m.kind !== SyntaxKind.MethodDeclaration && m.kind !== SyntaxKind.GetAccessor && m.kind !== SyntaxKind.SetAccessor && - m.kind !== SyntaxKind.SpreadAssignment) { + m.kind !== SyntaxKind.SpreadAssignment + ) { continue; } @@ -4859,7 +4955,8 @@ function getCompletionData( target, origin, CompletionKind.ObjectPropertyDeclaration, - /*jsxIdentifierExpected*/ false); + /*jsxIdentifierExpected*/ false, + ); if (displayName) { const originalSortText = symbolToSortTextMap[symbolId] ?? SortText.LocationPriority; const { name } = displayName; @@ -4877,10 +4974,12 @@ function getCompletionData( const existingMemberNames = new Set<__String>(); for (const m of existingMembers) { // Ignore omitted expressions for missing members - if (m.kind !== SyntaxKind.PropertyDeclaration && + if ( + m.kind !== SyntaxKind.PropertyDeclaration && m.kind !== SyntaxKind.MethodDeclaration && m.kind !== SyntaxKind.GetAccessor && - m.kind !== SyntaxKind.SetAccessor) { + m.kind !== SyntaxKind.SetAccessor + ) { continue; } @@ -4909,7 +5008,8 @@ function getCompletionData( !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & ModifierFlags.Private) && - !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration))); + !(propertySymbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(propertySymbol.valueDeclaration)) + ); } /** @@ -4954,8 +5054,8 @@ function tryGetObjectLikeCompletionContainer(contextToken: Node | undefined, pos if (contextToken) { const { parent } = contextToken; switch (contextToken.kind) { - case SyntaxKind.OpenBraceToken: // const x = { | - case SyntaxKind.CommaToken: // const x = { a: 0, | + case SyntaxKind.OpenBraceToken: // const x = { | + case SyntaxKind.CommaToken: // const x = { a: 0, | if (isObjectLiteralExpression(parent) || isObjectBindingPattern(parent)) { return parent; } @@ -4969,9 +5069,11 @@ function tryGetObjectLikeCompletionContainer(contextToken: Node | undefined, pos return contextToken.parent.parent; } else { - if (isObjectLiteralExpression(contextToken.parent.parent) && + if ( + isObjectLiteralExpression(contextToken.parent.parent) && (isSpreadAssignment(contextToken.parent) || isShorthandPropertyAssignment(contextToken.parent) && - (getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line))) { + (getLineAndCharacterOfPosition(sourceFile, contextToken.getEnd()).line !== getLineAndCharacterOfPosition(sourceFile, position).line)) + ) { return contextToken.parent.parent; } const ancestorNode = findAncestor(parent, isPropertyAssignment); @@ -4988,8 +5090,10 @@ function tryGetObjectLikeCompletionContainer(contextToken: Node | undefined, pos return parent.parent; } const ancestorNode = findAncestor(parent, isPropertyAssignment); - if (contextToken.kind !== SyntaxKind.ColonToken && ancestorNode?.getLastToken(sourceFile) === contextToken && - isObjectLiteralExpression(ancestorNode.parent)) { + if ( + contextToken.kind !== SyntaxKind.ColonToken && ancestorNode?.getLastToken(sourceFile) === contextToken && + isObjectLiteralExpression(ancestorNode.parent) + ) { return ancestorNode.parent; } } @@ -4998,7 +5102,7 @@ function tryGetObjectLikeCompletionContainer(contextToken: Node | undefined, pos return undefined; } -function getRelevantTokens(position: number, sourceFile: SourceFile): { contextToken: Node, previousToken: Node } | { contextToken: undefined, previousToken: undefined } { +function getRelevantTokens(position: number, sourceFile: SourceFile): { contextToken: Node; previousToken: Node; } | { contextToken: undefined; previousToken: undefined; } { const previousToken = findPrecedingToken(position, sourceFile); if (previousToken && position <= previousToken.end && (isMemberName(previousToken) || isKeyword(previousToken.kind))) { const contextToken = findPrecedingToken(previousToken.getFullStart(), sourceFile, /*startNode*/ undefined)!; // TODO: GH#18217 @@ -5007,11 +5111,10 @@ function getRelevantTokens(position: number, sourceFile: SourceFile): { contextT return { contextToken: previousToken as Node, previousToken: previousToken as Node }; } -function getAutoImportSymbolFromCompletionEntryData(name: string, data: CompletionEntryData, program: Program, host: LanguageServiceHost): { symbol: Symbol, origin: SymbolOriginInfoExport | SymbolOriginInfoResolvedExport } | undefined { +function getAutoImportSymbolFromCompletionEntryData(name: string, data: CompletionEntryData, program: Program, host: LanguageServiceHost): { symbol: Symbol; origin: SymbolOriginInfoExport | SymbolOriginInfoResolvedExport; } | undefined { const containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider!()! : program; const checker = containingProgram.getTypeChecker(); - const moduleSymbol = - data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : + const moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : data.fileName ? checker.getMergedSymbol(Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : undefined; @@ -5040,12 +5143,14 @@ function getCompletionEntryDisplayNameForSymbol( return undefined; } const name = originIncludesSymbolName(origin) ? origin.symbolName : symbol.name; - if (name === undefined + if ( + name === undefined // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) || symbol.flags & SymbolFlags.Module && isSingleOrDoubleQuote(name.charCodeAt(0)) // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" - || isKnownSymbol(symbol)) { + || isKnownSymbol(symbol) + ) { return undefined; } @@ -5080,7 +5185,7 @@ const allKeywordsCompletions: () => readonly CompletionEntry[] = memoize(() => { name: tokenToString(i)!, kind: ScriptElementKind.keyword, kindModifiers: ScriptElementKindModifier.none, - sortText: SortText.GlobalsOrKeywords + sortText: SortText.GlobalsOrKeywords, }); } return res; @@ -5092,8 +5197,7 @@ function getKeywordCompletions(keywordFilter: KeywordCompletionFilters, filterOu const index = keywordFilter + KeywordCompletionFilters.Last + 1; return _keywordCompletions[index] || (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter) - .filter(entry => !isTypeScriptOnlyKeyword(stringToToken(entry.name)!)) - ); + .filter(entry => !isTypeScriptOnlyKeyword(stringToToken(entry.name)!))); } function getTypescriptKeywordCompletions(keywordFilter: KeywordCompletionFilters): readonly CompletionEntry[] { @@ -5216,9 +5320,11 @@ function getContextualKeywords( const parent = contextToken.parent; const tokenLine = file.getLineAndCharacterOfPosition(contextToken.end).line; const currentLine = file.getLineAndCharacterOfPosition(position).line; - if ((isImportDeclaration(parent) || isExportDeclaration(parent) && parent.moduleSpecifier) + if ( + (isImportDeclaration(parent) || isExportDeclaration(parent) && parent.moduleSpecifier) && contextToken === parent.moduleSpecifier - && tokenLine === currentLine) { + && tokenLine === currentLine + ) { entries.push({ name: tokenToString(SyntaxKind.AssertKeyword)!, kind: ScriptElementKind.keyword, @@ -5322,9 +5428,11 @@ function tryGetObjectTypeDeclarationCompletionContainer(sourceFile: SourceFile, if (!contextToken) return undefined; // class C { blah; constructor/**/ } and so on - if (location.kind === SyntaxKind.ConstructorKeyword + if ( + location.kind === SyntaxKind.ConstructorKeyword // class C { blah \n constructor/**/ } - || (isIdentifier(contextToken) && isPropertyDeclaration(contextToken.parent) && isClassLike(location))) { + || (isIdentifier(contextToken) && isPropertyDeclaration(contextToken.parent) && isClassLike(location)) + ) { return findAncestor(contextToken, isClassLike) as ObjectTypeDeclaration; } @@ -5516,11 +5624,13 @@ function getImportStatementCompletionInfo(contextToken: Node, sourceFile: Source return parent; } if (isNamedImports(parent) || isNamespaceImport(parent)) { - if (!parent.parent.isTypeOnly && ( - contextToken.kind === SyntaxKind.OpenBraceToken || - contextToken.kind === SyntaxKind.ImportKeyword || - contextToken.kind === SyntaxKind.CommaToken - )) { + if ( + !parent.parent.isTypeOnly && ( + contextToken.kind === SyntaxKind.OpenBraceToken || + contextToken.kind === SyntaxKind.ImportKeyword || + contextToken.kind === SyntaxKind.CommaToken + ) + ) { keywordCompletion = SyntaxKind.TypeKeyword; } @@ -5593,7 +5703,8 @@ function getPotentiallyInvalidImportSpecifier(namedBindings: NamedImportBindings tryCast(namedBindings, isNamedImports)?.elements, e => !e.propertyName && isStringANonContextualKeyword(e.name.text) && - findPrecedingToken(e.name.pos, namedBindings!.getSourceFile(), namedBindings)?.kind !== SyntaxKind.CommaToken); + findPrecedingToken(e.name.pos, namedBindings!.getSourceFile(), namedBindings)?.kind !== SyntaxKind.CommaToken, + ); } function couldBeTypeOnlyImportSpecifier(importSpecifier: Node, contextToken: Node | undefined): importSpecifier is ImportSpecifier { @@ -5640,9 +5751,8 @@ function getVariableOrParameterDeclaration(contextToken: Node | undefined, locat function isArrowFunctionBody(node: Node) { return node.parent && isArrowFunction(node.parent) && (node.parent.body === node || - // const a = () => /**/; - node.kind === SyntaxKind.EqualsGreaterThanToken - ); + // const a = () => /**/; + node.kind === SyntaxKind.EqualsGreaterThanToken); } /** True if symbol is a type or a module containing at least one type. */ @@ -5654,7 +5764,7 @@ function symbolCanBeReferencedAtTypeLocation(symbol: Symbol, checker: TypeChecke function nonAliasCanBeReferencedAtTypeLocation(symbol: Symbol): boolean { return !!(symbol.flags & SymbolFlags.Type) || checker.isUnknownSymbol(symbol) || !!(symbol.flags & SymbolFlags.Module) && addToSeen(seenModules, getSymbolId(symbol)) && - checker.getExportsOfModule(symbol).some(e => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); + checker.getExportsOfModule(symbol).some(e => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); } } @@ -5679,7 +5789,7 @@ function isDeprecated(symbol: Symbol, checker: TypeChecker) { * 'tate' in 'useState' * 'ment' in 'ENVIRONMENT_VARIABLE' */ - function charactersFuzzyMatchInString(identifierString: string, lowercaseCharacters: string): boolean { +function charactersFuzzyMatchInString(identifierString: string, lowercaseCharacters: string): boolean { if (lowercaseCharacters.length === 0) { return true; } @@ -5692,8 +5802,7 @@ function isDeprecated(symbol: Symbol, checker: TypeChecker) { const strChar = identifierString.charCodeAt(strIndex); const testChar = lowercaseCharacters.charCodeAt(characterIndex); if (strChar === testChar || strChar === toUpperCharCode(testChar)) { - matchedFirstCharacter ||= - prevChar === undefined || // Beginning of word + matchedFirstCharacter ||= prevChar === undefined || // Beginning of word CharacterCodes.a <= prevChar && prevChar <= CharacterCodes.z && CharacterCodes.A <= strChar && strChar <= CharacterCodes.Z || // camelCase transition prevChar === CharacterCodes._ && strChar !== CharacterCodes._; // snake_case transition if (matchedFirstCharacter) { diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index 1d4848c641851..b5c92cc1b3f17 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -107,7 +107,7 @@ export namespace DocumentHighlights { return { fileName: sourceFile.fileName, textSpan: createTextSpanFromNode(node, sourceFile), - kind: HighlightSpanKind.none + kind: HighlightSpanKind.none, }; } @@ -186,8 +186,7 @@ export namespace DocumentHighlights { } function getFromAllDeclarations(nodeTest: (node: Node) => node is T, keywords: readonly SyntaxKind[]): HighlightSpan[] | undefined { - return useParent(node.parent, nodeTest, decl => mapDefined(tryCast(decl, canHaveSymbol)?.symbol.declarations, d => - nodeTest(d) ? find(d.getChildren(sourceFile), c => contains(keywords, c.kind)) : undefined)); + return useParent(node.parent, nodeTest, decl => mapDefined(tryCast(decl, canHaveSymbol)?.symbol.declarations, d => nodeTest(d) ? find(d.getChildren(sourceFile), c => contains(keywords, c.kind)) : undefined)); } function useParent(node: Node, nodeTest: (node: Node) => node is T, getNodes: (node: T, sourceFile: SourceFile) => readonly Node[] | undefined): HighlightSpan[] | undefined { @@ -211,7 +210,8 @@ export namespace DocumentHighlights { // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. return concatenate( node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), - node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); + node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock), + ); } // Do not cross function boundaries. return isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); @@ -386,7 +386,6 @@ export namespace DocumentHighlights { return getLoopBreakContinueOccurrences(owner as IterationStatement); case SyntaxKind.SwitchStatement: return getSwitchCaseDefaultOccurrences(owner as SwitchStatement); - } } @@ -494,7 +493,6 @@ export namespace DocumentHighlights { }); }); - return keywords; } @@ -550,7 +548,7 @@ export namespace DocumentHighlights { result.push({ fileName: sourceFile.fileName, textSpan: createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: HighlightSpanKind.reference + kind: HighlightSpanKind.reference, }); i++; // skip the next keyword continue; diff --git a/src/services/documentRegistry.ts b/src/services/documentRegistry.ts index b8ef0757b7700..9fc06295100cd 100644 --- a/src/services/documentRegistry.ts +++ b/src/services/documentRegistry.ts @@ -159,7 +159,7 @@ export interface ExternalDocumentCache { getDocument(key: DocumentRegistryBucketKeyWithMode, path: Path): SourceFile | undefined; } -export type DocumentRegistryBucketKey = string & { __bucketKey: any }; +export type DocumentRegistryBucketKey = string & { __bucketKey: any; }; /** @internal */ export interface DocumentRegistryEntry { @@ -194,13 +194,13 @@ export function createDocumentRegistryInternal(useCaseSensitiveFileNames?: boole function reportStats() { const bucketInfoArray = arrayFrom(buckets.keys()).filter(name => name && name.charAt(0) === "_").map(name => { const entries = buckets.get(name)!; - const sourceFiles: { name: string; scriptKind: ScriptKind, refCount: number; }[] = []; + const sourceFiles: { name: string; scriptKind: ScriptKind; refCount: number; }[] = []; entries.forEach((entry, name) => { if (isDocumentRegistryEntry(entry)) { sourceFiles.push({ name, scriptKind: entry.sourceFile.scriptKind, - refCount: entry.languageServiceRefCount + refCount: entry.languageServiceRefCount, }); } else { @@ -210,7 +210,7 @@ export function createDocumentRegistryInternal(useCaseSensitiveFileNames?: boole sourceFiles.sort((x, y) => y.refCount - x.refCount); return { bucket: name, - sourceFiles + sourceFiles, }; }); return JSON.stringify(bucketInfoArray, undefined, 2); @@ -269,7 +269,7 @@ export function createDocumentRegistryInternal(useCaseSensitiveFileNames?: boole { languageVersion: scriptTarget, impliedNodeFormat: host && getImpliedNodeFormatForFile(path, host.getCompilerHost?.()?.getModuleResolutionCache?.()?.getPackageJsonInfoCache(), host, compilationSettings), - setExternalModuleIndicator: getSetExternalModuleIndicator(compilationSettings) + setExternalModuleIndicator: getSetExternalModuleIndicator(compilationSettings), }; sourceFileOptions.languageVersion = scriptTarget; const oldBucketCount = buckets.size; @@ -301,7 +301,7 @@ export function createDocumentRegistryInternal(useCaseSensitiveFileNames?: boole Debug.assert(acquiring); entry = { sourceFile, - languageServiceRefCount: 0 + languageServiceRefCount: 0, }; setBucketEntry(); } @@ -324,8 +324,7 @@ export function createDocumentRegistryInternal(useCaseSensitiveFileNames?: boole // the script snapshot. If so, update it appropriately. Otherwise, we can just // return it as is. if (entry.sourceFile.version !== version) { - entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, - scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot!)); // TODO: GH#18217 + entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot!)); // TODO: GH#18217 if (externalCache) { externalCache.setDocument(keyWithMode, path, entry.sourceFile); } diff --git a/src/services/exportInfoMap.ts b/src/services/exportInfoMap.ts index 4651c1dac1c36..9a4d9cf1d2b7c 100644 --- a/src/services/exportInfoMap.ts +++ b/src/services/exportInfoMap.ts @@ -288,13 +288,17 @@ export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost): const checker = (isFromPackageJson ? host.getPackageJsonAutoImportProvider()! : host.getCurrentProgram()!).getTypeChecker(); - const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined(info.moduleFile - ? checker.getMergedSymbol(info.moduleFile.symbol) - : checker.tryFindAmbientModule(info.moduleName)); - const symbol = info.symbol || cachedSymbol || Debug.checkDefined(exportKind === ExportKind.ExportEquals - ? checker.resolveExternalModuleSymbol(moduleSymbol) - : checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol), - `Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}`); + const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined( + info.moduleFile + ? checker.getMergedSymbol(info.moduleFile.symbol) + : checker.tryFindAmbientModule(info.moduleName), + ); + const symbol = info.symbol || cachedSymbol || Debug.checkDefined( + exportKind === ExportKind.ExportEquals + ? checker.resolveExternalModuleSymbol(moduleSymbol) + : checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol), + `Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}`, + ); symbols.set(id, [symbol, moduleSymbol]); return { symbol, @@ -377,7 +381,7 @@ export function isImportableFile( // or there doesnt exist the file in the program by the symlink return (toFile === to || !toFile) && isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); - } + }, ); if (packageJsonFilter) { @@ -488,7 +492,8 @@ export function getExportInfoMap(importingFile: SourceFile, host: LanguageServic moduleFile, defaultInfo.exportKind, isFromPackageJson, - checker); + checker, + ); } checker.forEachExportAndPropertyOfModule(moduleSymbol, (exported, key) => { if (exported !== defaultInfo?.symbol && isImportableSymbol(exported, checker) && addToSeen(seenExports, key)) { @@ -500,7 +505,8 @@ export function getExportInfoMap(importingFile: SourceFile, host: LanguageServic moduleFile, ExportKind.Named, isFromPackageJson, - checker); + checker, + ); } }); }); @@ -528,7 +534,7 @@ function isImportableSymbol(symbol: Symbol, checker: TypeChecker) { return !checker.isUndefinedSymbol(symbol) && !checker.isUnknownSymbol(symbol) && !isKnownSymbol(symbol) && !isPrivateIdentifierSymbol(symbol); } -function getDefaultLikeExportWorker(moduleSymbol: Symbol, checker: TypeChecker): { readonly symbol: Symbol, readonly exportKind: ExportKind } | undefined { +function getDefaultLikeExportWorker(moduleSymbol: Symbol, checker: TypeChecker): { readonly symbol: Symbol; readonly exportKind: ExportKind; } | undefined { const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) return { symbol: exportEquals, exportKind: ExportKind.ExportEquals }; const defaultExport = checker.tryGetMemberInModuleExports(InternalSymbolName.Default, moduleSymbol); @@ -536,7 +542,7 @@ function getDefaultLikeExportWorker(moduleSymbol: Symbol, checker: TypeChecker): } /** @internal */ -export function getDefaultExportInfoWorker(defaultExport: Symbol, checker: TypeChecker, compilerOptions: CompilerOptions): { readonly resolvedSymbol: Symbol, readonly name: string } | undefined { +export function getDefaultExportInfoWorker(defaultExport: Symbol, checker: TypeChecker, compilerOptions: CompilerOptions): { readonly resolvedSymbol: Symbol; readonly name: string; } | undefined { const localSymbol = getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { resolvedSymbol: localSymbol, name: localSymbol.name }; @@ -554,8 +560,10 @@ export function getDefaultExportInfoWorker(defaultExport: Symbol, checker: TypeC } } - if (defaultExport.escapedName !== InternalSymbolName.Default && - defaultExport.escapedName !== InternalSymbolName.ExportEquals) { + if ( + defaultExport.escapedName !== InternalSymbolName.Default && + defaultExport.escapedName !== InternalSymbolName.ExportEquals + ) { return { resolvedSymbol: defaultExport, name: defaultExport.getName() }; } return { resolvedSymbol: defaultExport, name: getNameForExportedSymbol(defaultExport, compilerOptions.target) }; diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 1aa55a6cbc2cf..11a00e51954da 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -268,18 +268,31 @@ export interface SymbolAndEntries { } /** @internal */ -export const enum DefinitionKind { Symbol, Label, Keyword, This, String, TripleSlashReference } +export const enum DefinitionKind { + Symbol, + Label, + Keyword, + This, + String, + TripleSlashReference, +} /** @internal */ export type Definition = - | { readonly type: DefinitionKind.Symbol; readonly symbol: Symbol } - | { readonly type: DefinitionKind.Label; readonly node: Identifier } - | { readonly type: DefinitionKind.Keyword; readonly node: Node } - | { readonly type: DefinitionKind.This; readonly node: Node } - | { readonly type: DefinitionKind.String; readonly node: StringLiteralLike } - | { readonly type: DefinitionKind.TripleSlashReference; readonly reference: FileReference, readonly file: SourceFile }; + | { readonly type: DefinitionKind.Symbol; readonly symbol: Symbol; } + | { readonly type: DefinitionKind.Label; readonly node: Identifier; } + | { readonly type: DefinitionKind.Keyword; readonly node: Node; } + | { readonly type: DefinitionKind.This; readonly node: Node; } + | { readonly type: DefinitionKind.String; readonly node: StringLiteralLike; } + | { readonly type: DefinitionKind.TripleSlashReference; readonly reference: FileReference; readonly file: SourceFile; }; /** @internal */ -export const enum EntryKind { Span, Node, StringLiteral, SearchedLocalFoundProperty, SearchedPropertyFoundLocal } +export const enum EntryKind { + Span, + Node, + StringLiteral, + SearchedLocalFoundProperty, + SearchedPropertyFoundLocal, +} /** @internal */ export type NodeEntryKind = EntryKind.Node | EntryKind.StringLiteral | EntryKind.SearchedLocalFoundProperty | EntryKind.SearchedPropertyFoundLocal; /** @internal */ @@ -308,7 +321,7 @@ export function nodeEntry(node: Node, kind: NodeEntryKind = EntryKind.Node): Nod return { kind, node: (node as NamedDeclaration).name || node, - context: getContextNodeForNodeEntry(node) + context: getContextNodeForNodeEntry(node), }; } @@ -332,8 +345,8 @@ function getContextNodeForNodeEntry(node: Node): ContextNode | undefined { isAccessExpression(node.parent) && isBinaryExpression(node.parent.parent) && node.parent.parent.left === node.parent ? - node.parent.parent : - undefined; + node.parent.parent : + undefined; if (binaryExpression && getAssignmentDeclarationKind(binaryExpression) !== AssignmentDeclarationKind.None) { return getContextNode(binaryExpression); } @@ -343,9 +356,11 @@ function getContextNodeForNodeEntry(node: Node): ContextNode | undefined { if (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) { return node.parent.parent; } - else if (isJsxSelfClosingElement(node.parent) || + else if ( + isJsxSelfClosingElement(node.parent) || isLabeledStatement(node.parent) || - isBreakOrContinueStatement(node.parent)) { + isBreakOrContinueStatement(node.parent) + ) { return node.parent; } else if (isStringLiteralLike(node)) { @@ -354,8 +369,7 @@ function getContextNodeForNodeEntry(node: Node): ContextNode | undefined { const declOrStatement = findAncestor(validImport, node => isDeclaration(node) || isStatement(node) || - isJSDocTag(node) - )! as NamedDeclaration | Statement | JSDocTag; + isJSDocTag(node))! as NamedDeclaration | Statement | JSDocTag; return isDeclaration(declOrStatement) ? getContextNode(declOrStatement) : declOrStatement; @@ -369,14 +383,16 @@ function getContextNodeForNodeEntry(node: Node): ContextNode | undefined { undefined; } - if (node.parent.name === node || // node is name of declaration, use parent + if ( + node.parent.name === node || // node is name of declaration, use parent isConstructorDeclaration(node.parent) || isExportAssignment(node.parent) || // Property name of the import export specifier or binding pattern, use parent ((isImportOrExportSpecifier(node.parent) || isBindingElement(node.parent)) && node.parent.propertyName === node) || // Is default export - (node.kind === SyntaxKind.DefaultKeyword && hasSyntacticModifier(node.parent, ModifierFlags.ExportDefault))) { + (node.kind === SyntaxKind.DefaultKeyword && hasSyntacticModifier(node.parent, ModifierFlags.ExportDefault)) + ) { return getContextNode(node.parent); } @@ -391,10 +407,10 @@ export function getContextNode(node: NamedDeclaration | BinaryExpression | ForIn return !isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : isVariableStatement(node.parent.parent) ? - node.parent.parent : - isForInOrOfStatement(node.parent.parent) ? - getContextNode(node.parent.parent) : - node.parent; + node.parent.parent : + isForInOrOfStatement(node.parent.parent) ? + getContextNode(node.parent.parent) : + node.parent; case SyntaxKind.BindingElement: return getContextNode(node.parent.parent as NamedDeclaration); @@ -419,16 +435,14 @@ export function getContextNode(node: NamedDeclaration | BinaryExpression | ForIn case SyntaxKind.ForInStatement: return { start: (node as ForInOrOfStatement).initializer, - end: (node as ForInOrOfStatement).expression + end: (node as ForInOrOfStatement).expression, }; case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: return isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent) ? getContextNode( - findAncestor(node.parent, node => - isBinaryExpression(node) || isForInOrOfStatement(node) - ) as BinaryExpression | ForInOrOfStatement + findAncestor(node.parent, node => isBinaryExpression(node) || isForInOrOfStatement(node)) as BinaryExpression | ForInOrOfStatement, ) : node; @@ -438,7 +452,7 @@ export function getContextNode(node: NamedDeclaration | BinaryExpression | ForIn } /** @internal */ -export function toContextSpan(textSpan: TextSpan, sourceFile: SourceFile, context?: ContextNode): { contextSpan: TextSpan } | undefined { +export function toContextSpan(textSpan: TextSpan, sourceFile: SourceFile, context?: ContextNode): { contextSpan: TextSpan; } | undefined { if (!context) return undefined; const contextSpan = isContextWithStartAndEndNode(context) ? getTextSpan(context.start, sourceFile, context.end) : @@ -494,7 +508,7 @@ export function findReferencedSymbols(program: Program, cancellationToken: Cance // Only include referenced symbols that have a valid definition. definition && { definition: checker.runWithCancellationToken(cancellationToken, checker => definitionToReferencedSymbolDefinitionInfo(definition, checker, node)), - references: references.map(r => toReferencedSymbolEntry(r, symbol)) + references: references.map(r => toReferencedSymbolEntry(r, symbol)), }); } @@ -565,7 +579,12 @@ function getImplementationReferenceEntries(program: Program, cancellationToken: /** @internal */ export function findReferenceOrRenameEntries( - program: Program, cancellationToken: CancellationToken, sourceFiles: readonly SourceFile[], node: Node, position: number, options: Options | undefined, + program: Program, + cancellationToken: CancellationToken, + sourceFiles: readonly SourceFile[], + node: Node, + position: number, + options: Options | undefined, convertEntry: ToReferenceOrRenameEntry, ): T[] | undefined { return map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), entry => convertEntry(entry, node, program.getTypeChecker())); @@ -592,7 +611,7 @@ function flattenEntries(referenceSymbols: readonly SymbolAndEntries[] | undefine } function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: TypeChecker, originalNode: Node): ReferencedSymbolDefinitionInfo { - const info = ((): { sourceFile: SourceFile, textSpan: TextSpan, name: string, kind: ScriptElementKind, displayParts: SymbolDisplayPart[], context?: Node | ContextWithStartAndEndNode } => { + const info = ((): { sourceFile: SourceFile; textSpan: TextSpan; name: string; kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; context?: Node | ContextWithStartAndEndNode; } => { switch (def.type) { case DefinitionKind.Symbol: { const { symbol } = def; @@ -605,7 +624,7 @@ function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: Ty name, kind, displayParts, - context: getContextNode(declaration) + context: getContextNode(declaration), }; } case DefinitionKind.Label: { @@ -621,7 +640,12 @@ function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: Ty const { node } = def; const symbol = checker.getSymbolAtLocation(node); const displayParts = symbol && SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind( - checker, symbol, node.getSourceFile(), getContainerNode(node), node).displayParts || [textPart("this")]; + checker, + symbol, + node.getSourceFile(), + getContainerNode(node), + node, + ).displayParts || [textPart("this")]; return { ...getFileAndTextSpanFromNode(node), name: "this", kind: ScriptElementKind.variableElement, displayParts }; } case DefinitionKind.String: { @@ -630,7 +654,7 @@ function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: Ty ...getFileAndTextSpanFromNode(node), name: node.text, kind: ScriptElementKind.variableElement, - displayParts: [displayPart(getTextOfNode(node), SymbolDisplayPartKind.stringLiteral)] + displayParts: [displayPart(getTextOfNode(node), SymbolDisplayPartKind.stringLiteral)], }; } case DefinitionKind.TripleSlashReference: { @@ -639,7 +663,7 @@ function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: Ty sourceFile: def.file, name: def.reference.fileName, kind: ScriptElementKind.string, - displayParts: [displayPart(`"${def.reference.fileName}"`, SymbolDisplayPartKind.stringLiteral)] + displayParts: [displayPart(`"${def.reference.fileName}"`, SymbolDisplayPartKind.stringLiteral)], }; } default: @@ -656,7 +680,7 @@ function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: Ty name, textSpan, displayParts, - ...toContextSpan(textSpan, sourceFile, context) + ...toContextSpan(textSpan, sourceFile, context), }; } @@ -664,15 +688,14 @@ function getFileAndTextSpanFromNode(node: Node) { const sourceFile = node.getSourceFile(); return { sourceFile, - textSpan: getTextSpan(isComputedPropertyName(node) ? node.expression : node, sourceFile) + textSpan: getTextSpan(isComputedPropertyName(node) ? node.expression : node, sourceFile), }; } -function getDefinitionKindAndDisplayParts(symbol: Symbol, checker: TypeChecker, node: Node): { displayParts: SymbolDisplayPart[], kind: ScriptElementKind } { +function getDefinitionKindAndDisplayParts(symbol: Symbol, checker: TypeChecker, node: Node): { displayParts: SymbolDisplayPart[]; kind: ScriptElementKind; } { const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol); const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node; - const { displayParts, symbolKind } = - SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); + const { displayParts, symbolKind } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); return { displayParts, kind: symbolKind }; } @@ -686,7 +709,7 @@ function toReferencedSymbolEntry(entry: Entry, symbol: Symbol | undefined): Refe if (!symbol) return referenceEntry; return { ...referenceEntry, - isDefinition: entry.kind !== EntryKind.Span && isDeclarationOfSymbol(entry.node, symbol) + isDefinition: entry.kind !== EntryKind.Span && isDeclarationOfSymbol(entry.node, symbol), }; } @@ -714,12 +737,15 @@ function entryToDocumentSpan(entry: Entry): DocumentSpan { return { textSpan, fileName: sourceFile.fileName, - ...toContextSpan(textSpan, sourceFile, entry.context) + ...toContextSpan(textSpan, sourceFile, entry.context), }; } } -interface PrefixAndSuffix { readonly prefixText?: string; readonly suffixText?: string; } +interface PrefixAndSuffix { + readonly prefixText?: string; + readonly suffixText?: string; +} function getPrefixAndSuffixText(entry: Entry, originalNode: Node, checker: TypeChecker, quotePreference: QuotePreference): PrefixAndSuffix { if (entry.kind !== EntryKind.Span && isIdentifier(originalNode)) { const { node, kind } = entry; @@ -740,9 +766,11 @@ function getPrefixAndSuffixText(entry: Entry, originalNode: Node, checker: TypeC // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. if (isShorthandAssignment) { const grandParent = parent.parent; - if (isObjectLiteralExpression(grandParent) && + if ( + isObjectLiteralExpression(grandParent) && isBinaryExpression(grandParent.parent) && - isModuleExportsAccessExpression(grandParent.parent.left)) { + isModuleExportsAccessExpression(grandParent.parent.left) + ) { return prefixColon; } return suffixColon; @@ -779,7 +807,7 @@ function toImplementationLocation(entry: Entry, checker: TypeChecker): Implement const { node } = entry; return { ...documentSpan, - ...implementationKindDisplayParts(node, checker) + ...implementationKindDisplayParts(node, checker), }; } else { @@ -787,7 +815,7 @@ function toImplementationLocation(entry: Entry, checker: TypeChecker): Implement } } -function implementationKindDisplayParts(node: Node, checker: TypeChecker): { kind: ScriptElementKind, displayParts: SymbolDisplayPart[] } { +function implementationKindDisplayParts(node: Node, checker: TypeChecker): { kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; } { const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node); if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); @@ -795,13 +823,13 @@ function implementationKindDisplayParts(node: Node, checker: TypeChecker): { kin else if (node.kind === SyntaxKind.ObjectLiteralExpression) { return { kind: ScriptElementKind.interfaceElement, - displayParts: [punctuationPart(SyntaxKind.OpenParenToken), textPart("object literal"), punctuationPart(SyntaxKind.CloseParenToken)] + displayParts: [punctuationPart(SyntaxKind.OpenParenToken), textPart("object literal"), punctuationPart(SyntaxKind.CloseParenToken)], }; } else if (node.kind === SyntaxKind.ClassExpression) { return { kind: ScriptElementKind.localClassElement, - displayParts: [punctuationPart(SyntaxKind.OpenParenToken), textPart("anonymous local class"), punctuationPart(SyntaxKind.CloseParenToken)] + displayParts: [punctuationPart(SyntaxKind.OpenParenToken), textPart("anonymous local class"), punctuationPart(SyntaxKind.CloseParenToken)], }; } else { @@ -810,15 +838,15 @@ function implementationKindDisplayParts(node: Node, checker: TypeChecker): { kin } /** @internal */ -export function toHighlightSpan(entry: Entry): { fileName: string, span: HighlightSpan } { +export function toHighlightSpan(entry: Entry): { fileName: string; span: HighlightSpan; } { const documentSpan = entryToDocumentSpan(entry); if (entry.kind === EntryKind.Span) { return { fileName: documentSpan.fileName, span: { textSpan: documentSpan.textSpan, - kind: HighlightSpanKind.reference - } + kind: HighlightSpanKind.reference, + }, }; } @@ -827,7 +855,7 @@ export function toHighlightSpan(entry: Entry): { fileName: string, span: Highlig textSpan: documentSpan.textSpan, kind: writeAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference, isInString: entry.kind === EntryKind.StringLiteral ? true : undefined, - ...documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan } + ...documentSpan.contextSpan && { contextSpan: documentSpan.contextSpan }, }; return { fileName: documentSpan.fileName, span }; } @@ -868,9 +896,9 @@ export function isDeclarationOfSymbol(node: Node, target: Symbol | undefined): b if (!target) return false; const source = getDeclarationFromName(node) || (node.kind === SyntaxKind.DefaultKeyword ? node.parent - : isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent - : node.kind === SyntaxKind.ConstructorKeyword && isConstructorDeclaration(node.parent) ? node.parent.parent - : undefined); + : isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent + : node.kind === SyntaxKind.ConstructorKeyword && isConstructorDeclaration(node.parent) ? node.parent.parent + : undefined); const commonjsSource = source && isBinaryExpression(source) ? source.left as unknown as Declaration : undefined; return !!(source && target.declarations?.some(d => d === source || d === commonjsSource)); } @@ -960,7 +988,7 @@ export namespace Core { } return [{ definition: { type: DefinitionKind.TripleSlashReference, reference: resolvedRef.reference, file: node }, - references: getReferencesForNonModule(resolvedRef.file, fileIncludeReasons, program) || emptyArray + references: getReferencesForNonModule(resolvedRef.file, fileIncludeReasons, program) || emptyArray, }]; } @@ -1043,7 +1071,7 @@ export namespace Core { entries = append(entries, { kind: EntryKind.Span, fileName: referencingFile.fileName, - textSpan: createTextSpanFromRange(location) + textSpan: createTextSpanFromRange(location), }); } } @@ -1092,7 +1120,8 @@ export namespace Core { continue; } const symbol = entry.definition.symbol; - const refIndex = findIndex(result, ref => !!ref.definition && + const refIndex = findIndex(result, ref => + !!ref.definition && ref.definition.type === DefinitionKind.Symbol && ref.definition.symbol === symbol); if (refIndex === -1) { @@ -1115,7 +1144,7 @@ export namespace Core { return entry1Span.start !== entry2Span.start ? compareValues(entry1Span.start, entry2Span.start) : compareValues(entry1Span.length, entry2Span.length); - }) + }), }; } } @@ -1147,9 +1176,9 @@ export namespace Core { else if (reference.kind === "implicit") { // Return either: The first JSX node in the (if not a tslib import), the first statement of the file, or the whole file if neither of those exist const range = reference.literal.text !== externalHelpersModuleNameText && forEachChildRecursively( - reference.referencingFile, - n => !(n.transformFlags & TransformFlags.ContainsJsx) ? "skip" : isJsxElement(n) || isJsxSelfClosingElement(n) || isJsxFragment(n) ? n : undefined - ) || reference.referencingFile.statements[0] || reference.referencingFile; + reference.referencingFile, + n => !(n.transformFlags & TransformFlags.ContainsJsx) ? "skip" : isJsxElement(n) || isJsxSelfClosingElement(n) || isJsxFragment(n) ? n : undefined, + ) || reference.referencingFile.statements[0] || reference.referencingFile; return nodeEntry(range); } else { @@ -1222,7 +1251,8 @@ export namespace Core { sourceFiles, node.kind, cancellationToken, - node.kind === SyntaxKind.ReadonlyKeyword ? isReadonlyTypeOperator : undefined); + node.kind === SyntaxKind.ReadonlyKeyword ? isReadonlyTypeOperator : undefined, + ); } if (isImportMeta(node.parent) && node.parent.name === node) { @@ -1406,7 +1436,8 @@ export namespace Core { readonly cancellationToken: CancellationToken, readonly searchMeaning: SemanticMeaning, readonly options: Options, - private readonly result: SymbolAndEntries[]) { + private readonly result: SymbolAndEntries[], + ) { } includesSourceFile(sourceFile: SourceFile): boolean { @@ -1421,7 +1452,7 @@ export namespace Core { } /** @param allSearchSymbols set of additional symbols for use by `includes`. */ - createSearch(location: Node | undefined, symbol: Symbol, comingFrom: ImportExport | undefined, searchOptions: { text?: string, allSearchSymbols?: Symbol[] } = {}): Search { + createSearch(location: Node | undefined, symbol: Symbol, comingFrom: ImportExport | undefined, searchOptions: { text?: string; allSearchSymbols?: Symbol[]; } = {}): Search { // Note: if this is an external module symbol, the name doesn't include quotes. // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form @@ -1454,7 +1485,7 @@ export namespace Core { addStringOrCommentReference(fileName: string, textSpan: TextSpan): void { this.result.push({ definition: undefined, - references: [{ kind: EntryKind.Span, fileName, textSpan }] + references: [{ kind: EntryKind.Span, fileName, textSpan }], }); } @@ -1668,9 +1699,11 @@ export namespace Core { for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer)) { if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; const referenceSymbol = checker.getSymbolAtLocation(token)!; - if (referenceSymbol === symbol + if ( + referenceSymbol === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol - || isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + || isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol + ) { const res = cb(token); if (res) return res; } @@ -1706,7 +1739,7 @@ export namespace Core { signature: SignatureDeclaration, sourceFiles: readonly SourceFile[], checker: TypeChecker, - cb: (name: Identifier, call?: CallExpression) => boolean + cb: (name: Identifier, call?: CallExpression) => boolean, ): boolean { if (!signature.name || !isIdentifier(signature.name)) return false; @@ -1759,8 +1792,10 @@ export namespace Core { // before and after it have to be a non-identifier char). const endPosition = position + symbolNameLength; - if ((position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), ScriptTarget.Latest)) && - (endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), ScriptTarget.Latest))) { + if ( + (position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), ScriptTarget.Latest)) && + (endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), ScriptTarget.Latest)) + ) { // Found a real match. Keep searching. positions.push(position); } @@ -1914,9 +1949,11 @@ export namespace Core { } // Use the parent symbol if the location is commonjs require syntax on javascript files only. - if (isInJSFile(referenceLocation) + if ( + isInJSFile(referenceLocation) && isBindingElement(referenceLocation.parent) - && isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { + && isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent) + ) { referenceSymbol = referenceLocation.parent.symbol; // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In // this case, just skip it, since the bound identifiers are not an alias of the import. @@ -2028,12 +2065,12 @@ export namespace Core { const shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration)!; const name = valueDeclaration && getNameOfDeclaration(valueDeclaration); /* - * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment - * has two meanings: property name and property value. Therefore when we do findAllReference at the position where - * an identifier is declared, the language service should return the position of the variable declaration as well as - * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the - * position of property accessing, the referenceEntry of such position will be handled in the first case. - */ + * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment + * has two meanings: property name and property value. Therefore when we do findAllReference at the position where + * an identifier is declared, the language service should return the position of the variable declaration as well as + * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the + * position of property accessing, the referenceEntry of such position will be handled in the first case. + */ if (!(flags & SymbolFlags.Transient) && name && search.includes(shorthandValueSymbol)) { addReference(name, shorthandValueSymbol, state); } @@ -2280,7 +2317,8 @@ export namespace Core { getAllSuperTypeNodes(declaration).some(typeReference => { const type = checker.getTypeAtLocation(typeReference); return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); - })); + }) + ); cachedResults.set(key, inherits); return inherits; } @@ -2396,7 +2434,7 @@ export namespace Core { const thisParameter = firstDefined(references, r => isParameter(r.node.parent) ? r.node : undefined); return [{ definition: { type: DefinitionKind.This, node: thisParameter || thisOrSuperKeyword }, - references + references, }]; } @@ -2422,7 +2460,7 @@ export namespace Core { return [{ definition: { type: DefinitionKind.String, node }, - references + references, }]; } @@ -2430,7 +2468,12 @@ export namespace Core { // This is not needed when searching for re-exports. function populateSearchSymbolSet(symbol: Symbol, location: Node, checker: TypeChecker, isForRename: boolean, providePrefixAndSuffixText: boolean, implementations: boolean): Symbol[] { const result: Symbol[] = []; - forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), + forEachRelatedSymbol( + symbol, + location, + checker, + isForRename, + !(isForRename && providePrefixAndSuffixText), (sym, root, base) => { // static method/property and instance method/property might have the same name. Only include static or only include instance. if (base) { @@ -2439,9 +2482,9 @@ export namespace Core { } } result.push(base || root || sym); - }, - // when try to find implementation, implementations is true, and not allowed to find base class - /*allowBaseTypes*/() => !implementations); + }, // when try to find implementation, implementations is true, and not allowed to find base class + /*allowBaseTypes*/ () => !implementations, + ); return result; } @@ -2449,7 +2492,11 @@ export namespace Core { * @param allowBaseTypes return true means it would try to find in base class or interface. */ function forEachRelatedSymbol( - symbol: Symbol, location: Node, checker: TypeChecker, isForRenamePopulateSearchSymbolSet: boolean, onlyIncludeBindingElementAtReferenceLocation: boolean, + symbol: Symbol, + location: Node, + checker: TypeChecker, + isForRenamePopulateSearchSymbolSet: boolean, + onlyIncludeBindingElementAtReferenceLocation: boolean, /** * @param baseSymbol This symbol means one property/mehtod from base class or interface when it is not null or undefined, */ @@ -2481,7 +2528,8 @@ export namespace Core { const contextualType = checker.getContextualType(containingObjectLiteralElement.parent); const res = contextualType && firstDefined( getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), - sym => fromRoot(sym, EntryKind.SearchedPropertyFoundLocal)); + sym => fromRoot(sym, EntryKind.SearchedPropertyFoundLocal), + ); if (res) return res; // If the location is name of property symbol from object literal destructuring pattern @@ -2586,12 +2634,13 @@ export namespace Core { // } if (!(symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) || !addToSeen(seen, getSymbolId(symbol))) return; - return firstDefined(symbol.declarations, declaration => firstDefined(getAllSuperTypeNodes(declaration), typeReference => { - const type = checker.getTypeAtLocation(typeReference); - const propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); - // Visit the typeReference as well to see if it directly or indirectly uses that property - return type && propertySymbol && (firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); - })); + return firstDefined(symbol.declarations, declaration => + firstDefined(getAllSuperTypeNodes(declaration), typeReference => { + const type = checker.getTypeAtLocation(typeReference); + const propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); + // Visit the typeReference as well to see if it directly or indirectly uses that property + return type && propertySymbol && (firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); + })); } } @@ -2608,24 +2657,19 @@ export namespace Core { function getRelatedSymbol(search: Search, referenceSymbol: Symbol, referenceLocation: Node, state: State): RelatedSymbol | undefined { const { checker } = state; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, - /*onlyIncludeBindingElementAtReferenceLocation*/ state.options.use !== FindReferencesUse.Rename || !!state.options.providePrefixAndSuffixTextForRename, - (sym, rootSymbol, baseSymbol, kind): RelatedSymbol | undefined => { - // check whether the symbol used to search itself is just the searched one. - if (baseSymbol) { - // static method/property and instance method/property might have the same name. Only check static or only check instance. - if (isStaticSymbol(referenceSymbol) !== isStaticSymbol(baseSymbol)) { - baseSymbol = undefined; - } + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, /*onlyIncludeBindingElementAtReferenceLocation*/ state.options.use !== FindReferencesUse.Rename || !!state.options.providePrefixAndSuffixTextForRename, (sym, rootSymbol, baseSymbol, kind): RelatedSymbol | undefined => { + // check whether the symbol used to search itself is just the searched one. + if (baseSymbol) { + // static method/property and instance method/property might have the same name. Only check static or only check instance. + if (isStaticSymbol(referenceSymbol) !== isStaticSymbol(baseSymbol)) { + baseSymbol = undefined; } - return search.includes(baseSymbol || rootSymbol || sym) - // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? { symbol: rootSymbol && !(getCheckFlags(sym) & CheckFlags.Synthetic) ? rootSymbol : sym, kind } - : undefined; - }, - /*allowBaseTypes*/ rootSymbol => - !(search.parents && !search.parents.some(parent => explicitlyInheritsFrom(rootSymbol.parent!, parent, state.inheritsFromCache, checker))) - ); + } + return search.includes(baseSymbol || rootSymbol || sym) + // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. + ? { symbol: rootSymbol && !(getCheckFlags(sym) & CheckFlags.Synthetic) ? rootSymbol : sym, kind } + : undefined; + }, /*allowBaseTypes*/ rootSymbol => !(search.parents && !search.parents.some(parent => explicitlyInheritsFrom(rootSymbol.parent!, parent, state.inheritsFromCache, checker)))); } /** @@ -2666,8 +2710,8 @@ export namespace 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)); + isFunctionLikeDeclaration(node) ? !!node.body : + isClassLike(node) || isModuleOrEnumDeclaration(node)); } export function getReferenceEntriesForShorthandPropertyAssignment(node: Node, checker: TypeChecker, addReference: (node: Node) => void): void { @@ -2706,8 +2750,7 @@ export namespace Core { function getParentSymbolsOfPropertyAccess(location: Node, symbol: Symbol, checker: TypeChecker): readonly Symbol[] | undefined { const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? location.parent as PropertyAccessExpression : undefined; const lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); - const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), t => - t.symbol && t.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? t.symbol : undefined); + const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), t => t.symbol && t.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? t.symbol : undefined); return res.length === 0 ? undefined : res; } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 0f066e4807ebe..474af54946f32 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -112,7 +112,7 @@ export function createTextRangeWithKind(pos: number, end: } const enum Constants { - Unknown = -1 + Unknown = -1, } /* @@ -147,7 +147,6 @@ interface DynamicIndentation { * foo: { indentation: 0, delta: 4 } * bar: { indentation: foo.indentation + foo.delta = 4, delta: 4} however 'foo' and 'bar' are on the same line * so bar inherits indentation from foo and bar.delta will be 4 - * */ getDelta(child: TextRangeWithKind): number; /** @@ -182,7 +181,7 @@ export function formatOnEnter(position: number, sourceFile: SourceFile, formatCo // get start position for the previous line pos: getStartPositionOfLine(line - 1, sourceFile), // end value is exclusive so add 1 to the result - end: endOfFormatSpan + 1 + end: endOfFormatSpan + 1, }; return formatSpan(span, sourceFile, formatContext, FormattingRequestKind.FormatOnEnter); } @@ -216,7 +215,7 @@ export function formatOnOpeningCurly(position: number, sourceFile: SourceFile, f */ const textRange: TextRange = { pos: getLineStartPositionForPosition(outermostNode!.getStart(sourceFile), sourceFile), // TODO: GH#18217 - end: position + end: position, }; return formatSpan(textRange, sourceFile, formatContext, FormattingRequestKind.FormatOnOpeningCurlyBrace); @@ -232,7 +231,7 @@ export function formatOnClosingCurly(position: number, sourceFile: SourceFile, f export function formatDocument(sourceFile: SourceFile, formatContext: FormatContext): TextChange[] { const span = { pos: 0, - end: sourceFile.text.length + end: sourceFile.text.length, }; return formatSpan(span, sourceFile, formatContext, FormattingRequestKind.FormatDocument); } @@ -274,10 +273,12 @@ function findImmediatelyPrecedingTokenOfKind(end: number, expectedTokenKind: Syn */ function findOutermostNodeWithinListLevel(node: Node | undefined) { let current = node; - while (current && + while ( + current && current.parent && current.parent.end === node!.end && - !isListElement(current.parent, current)) { + !isListElement(current.parent, current) + ) { current = current.parent; } @@ -435,16 +436,18 @@ function getOwnOrInheritedDelta(n: Node, options: FormatCodeSettings, sourceFile /** @internal */ export function formatNodeGivenIndentation(node: Node, sourceFileLike: SourceFileLike, languageVariant: LanguageVariant, initialIndentation: number, delta: number, formatContext: FormatContext): TextChange[] { const range = { pos: node.pos, end: node.end }; - return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, scanner => formatSpanWorker( - range, - node, - initialIndentation, - delta, - scanner, - formatContext, - FormattingRequestKind.FormatSelection, - _ => false, // assume that node does not have any errors - sourceFileLike)); + return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, scanner => + formatSpanWorker( + range, + node, + initialIndentation, + delta, + scanner, + formatContext, + FormattingRequestKind.FormatSelection, + _ => false, // assume that node does not have any errors + sourceFileLike, + )); } function formatNodeLines(node: Node | undefined, sourceFile: SourceFile, formatContext: FormatContext, requestKind: FormattingRequestKind): TextChange[] { @@ -454,7 +457,7 @@ function formatNodeLines(node: Node | undefined, sourceFile: SourceFile, formatC const span = { pos: getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), - end: node.end + end: node.end, }; return formatSpan(span, sourceFile, formatContext, requestKind); @@ -468,16 +471,19 @@ function formatSpan(originalRange: TextRange, sourceFile: SourceFile, formatCont sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, - scanner => formatSpanWorker( - originalRange, - enclosingNode, - SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), - getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), - scanner, - formatContext, - requestKind, - prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), - sourceFile)); + scanner => + formatSpanWorker( + originalRange, + enclosingNode, + SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), + getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), + scanner, + formatContext, + requestKind, + prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), + sourceFile, + ), + ); } function formatSpanWorker( @@ -489,8 +495,8 @@ function formatSpanWorker( { options, getRules, host }: FormatContext, requestKind: FormattingRequestKind, rangeContainsError: (r: TextRange) => boolean, - sourceFile: SourceFileLike): TextChange[] { - + sourceFile: SourceFileLike, +): TextChange[] { // formatting context is used by rules provider const formattingContext = new FormattingContext(sourceFile, requestKind, options); let previousRangeTriviaEnd: number; @@ -523,12 +529,10 @@ function formatSpanWorker( const indentation = SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false) ? initialIndentation + options.indentSize! : initialIndentation; - indentTriviaItems(remainingTrivia, indentation, /*indentNextTokenOrTrivia*/ true, - item => { - processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!); - insertIndentation(item.pos, indentation, /*lineAdded*/ false); - } - ); + indentTriviaItems(remainingTrivia, indentation, /*indentNextTokenOrTrivia*/ true, item => { + processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!); + insertIndentation(item.pos, indentation, /*lineAdded*/ false); + }); if (options.trimTrailingWhitespace !== false) { trimTrailingWhitespacesForRemainingRange(remainingTrivia); } @@ -545,8 +549,7 @@ function formatSpanWorker( // inclusive. We would expect a format-selection would delete the space (if rules apply), // but in order to do that, we need to process the pair ["{", "}"], but we stopped processing // just before getting there. This block handles this trailing edit. - const tokenInfo = - formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : + const tokenInfo = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : undefined; @@ -570,7 +573,8 @@ function formatSpanWorker( previousRangeStartLine!, previousParent!, parent, - /*dynamicIndentation*/ undefined); + /*dynamicIndentation*/ undefined, + ); } } @@ -585,15 +589,11 @@ function formatSpanWorker( * If list element is in the range - its indentation will be equal * to inherited indentation from its predecessors. */ - function tryComputeIndentationForListItem(startPos: number, - endPos: number, - parentStartLine: number, - range: TextRange, - inheritedIndentation: number): number { - - if (rangeOverlapsWithStartEnd(range, startPos, endPos) || - rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { - + function tryComputeIndentationForListItem(startPos: number, endPos: number, parentStartLine: number, range: TextRange, inheritedIndentation: number): number { + if ( + rangeOverlapsWithStartEnd(range, startPos, endPos) || + rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */ + ) { if (inheritedIndentation !== Constants.Unknown) { return inheritedIndentation; } @@ -619,8 +619,8 @@ function formatSpanWorker( inheritedIndentation: number, parent: Node, parentDynamicIndentation: DynamicIndentation, - effectiveParentStartLine: number - ): { indentation: number, delta: number; } { + effectiveParentStartLine: number, + ): { indentation: number; delta: number; } { const delta = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize! : 0; if (effectiveParentStartLine === startLine) { @@ -629,7 +629,7 @@ function formatSpanWorker( // - push children if either parent of node itself has non-zero delta return { indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), - delta: Math.min(options.indentSize!, parentDynamicIndentation.getDelta(node) + delta) + delta: Math.min(options.indentSize!, parentDynamicIndentation.getDelta(node) + delta), }; } else if (inheritedIndentation === Constants.Unknown) { @@ -661,12 +661,18 @@ function formatSpanWorker( } switch (node.kind) { - case SyntaxKind.ClassDeclaration: return SyntaxKind.ClassKeyword; - case SyntaxKind.InterfaceDeclaration: return SyntaxKind.InterfaceKeyword; - case SyntaxKind.FunctionDeclaration: return SyntaxKind.FunctionKeyword; - case SyntaxKind.EnumDeclaration: return SyntaxKind.EnumDeclaration; - case SyntaxKind.GetAccessor: return SyntaxKind.GetKeyword; - case SyntaxKind.SetAccessor: return SyntaxKind.SetKeyword; + case SyntaxKind.ClassDeclaration: + return SyntaxKind.ClassKeyword; + case SyntaxKind.InterfaceDeclaration: + return SyntaxKind.InterfaceKeyword; + case SyntaxKind.FunctionDeclaration: + return SyntaxKind.FunctionKeyword; + case SyntaxKind.EnumDeclaration: + return SyntaxKind.EnumDeclaration; + case SyntaxKind.GetAccessor: + return SyntaxKind.GetKeyword; + case SyntaxKind.SetAccessor: + return SyntaxKind.SetKeyword; case SyntaxKind.MethodDeclaration: if ((node as MethodDeclaration).asteriskToken) { return SyntaxKind.AsteriskToken; @@ -707,8 +713,7 @@ function formatSpanWorker( // vs // var a = xValue // > yValue; - getIndentationForToken: (line, kind, container, suppressDelta) => - !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation, + getIndentationForToken: (line, kind, container, suppressDelta) => !suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation, getIndentation: () => indentation, getDelta, recomputeIndentation: (lineAdded, parent) => { @@ -716,7 +721,7 @@ function formatSpanWorker( indentation += lineAdded ? options.indentSize! : -options.indentSize!; delta = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize! : 0; } - } + }, }; function shouldAddDelta(line: number, kind: SyntaxKind, container: Node): boolean { @@ -787,7 +792,8 @@ function formatSpanWorker( }, nodes => { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); - }); + }, + ); // proceed any tokens in the node that are located after child nodes while (formattingScanner.isOnToken() && formattingScanner.getTokenFullStart() < originalRange.end) { @@ -806,7 +812,8 @@ function formatSpanWorker( parentStartLine: number, undecoratedParentStartLine: number, isListItem: boolean, - isFirstListItem?: boolean): number { + isFirstListItem?: boolean, + ): number { Debug.assert(!nodeIsSynthesized(child)); if (nodeIsMissing(child) || isGrammarError(parent, child)) { @@ -890,10 +897,7 @@ function formatSpanWorker( return inheritedIndentation; } - function processChildNodes(nodes: NodeArray, - parent: Node, - parentStartLine: number, - parentDynamicIndentation: DynamicIndentation): void { + function processChildNodes(nodes: NodeArray, parent: Node, parentStartLine: number, parentDynamicIndentation: DynamicIndentation): void { Debug.assert(isNodeArray(nodes)); Debug.assert(!nodeIsSynthesized(nodes)); @@ -1016,8 +1020,7 @@ function formatSpanWorker( let indentNextTokenOrTrivia = true; 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)); + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia, 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 @@ -1039,7 +1042,8 @@ function formatSpanWorker( trivia: TextRangeWithKind[], commentIndentation: number, indentNextTokenOrTrivia: boolean, - indentSingleLine: (item: TextRangeWithKind) => void) { + indentSingleLine: (item: TextRangeWithKind) => void, + ) { for (const triviaItem of trivia) { const triviaInRange = rangeContainsRange(originalRange, triviaItem); switch (triviaItem.kind) { @@ -1072,12 +1076,7 @@ function formatSpanWorker( } } - function processRange(range: TextRangeWithKind, - rangeStart: LineAndCharacter, - parent: Node, - contextNode: Node, - dynamicIndentation: DynamicIndentation): LineAction { - + function processRange(range: TextRangeWithKind, rangeStart: LineAndCharacter, parent: Node, contextNode: Node, dynamicIndentation: DynamicIndentation): LineAction { const rangeHasError = rangeContainsError(range); let lineAction = LineAction.None; if (!rangeHasError) { @@ -1087,8 +1086,7 @@ function formatSpanWorker( trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); } else { - lineAction = - processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); + lineAction = processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); } } @@ -1100,15 +1098,7 @@ function formatSpanWorker( return lineAction; } - function processPair(currentItem: TextRangeWithKind, - currentStartLine: number, - currentParent: Node, - previousItem: TextRangeWithKind, - previousStartLine: number, - previousParent: Node, - contextNode: Node, - dynamicIndentation: DynamicIndentation | undefined): LineAction { - + function processPair(currentItem: TextRangeWithKind, currentStartLine: number, currentParent: Node, previousItem: TextRangeWithKind, previousStartLine: number, previousParent: Node, contextNode: Node, dynamicIndentation: DynamicIndentation | undefined): LineAction { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); const rules = getRules(formattingContext); @@ -1219,8 +1209,7 @@ function formatSpanWorker( const startLinePos = getStartPositionOfLine(startLine, sourceFile); - const nonWhitespaceColumnInFirstPart = - SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); + const nonWhitespaceColumnInFirstPart = SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); let startIndex = 0; if (firstLineIsIndented) { @@ -1230,12 +1219,11 @@ function formatSpanWorker( // shift all parts on the delta size const delta = indentation - nonWhitespaceColumnInFirstPart.column; - for (let i = startIndex; i < parts.length; i++ , startLine++) { + for (let i = startIndex; i < parts.length; i++, startLine++) { const startLinePos = getStartPositionOfLine(startLine, sourceFile); - const nonWhitespaceCharacterAndColumn = - i === 0 - ? nonWhitespaceColumnInFirstPart - : SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); + const nonWhitespaceCharacterAndColumn = i === 0 + ? nonWhitespaceColumnInFirstPart + : SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); const newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { const indentationString = getIndentationString(newIndentation, options); @@ -1326,12 +1314,7 @@ function formatSpanWorker( } } - function applyRuleEdits(rule: Rule, - previousRange: TextRangeWithKind, - previousStartLine: number, - currentRange: TextRangeWithKind, - currentStartLine: number - ): LineAction { + function applyRuleEdits(rule: Rule, previousRange: TextRangeWithKind, previousStartLine: number, currentRange: TextRangeWithKind, currentStartLine: number): LineAction { const onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case RuleAction.StopProcessingSpaceActions: @@ -1381,10 +1364,13 @@ function formatSpanWorker( } } -const enum LineAction { None, LineAdded, LineRemoved } +const enum LineAction { + None, + LineAdded, + LineRemoved, +} /** - * * @internal */ export function getRangeOfEnclosingComment( @@ -1408,7 +1394,8 @@ export function getRangeOfEnclosingComment( const trailingRangesOfPreviousToken = precedingToken && getTrailingCommentRanges(sourceFile.text, precedingToken.end); const leadingCommentRangesOfNextToken = getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile); const commentRanges = concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); - return commentRanges && find(commentRanges, range => rangeContainsPositionExclusive(range, position) || + return commentRanges && find(commentRanges, range => + rangeContainsPositionExclusive(range, position) || // The end marker of a single-line comment does not include the newline character. // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position): // @@ -1499,8 +1486,7 @@ let internedSpacesIndentation: string[] | undefined; /** @internal */ export function getIndentationString(indentation: number, options: EditorSettings): string { // reset interned strings if FormatCodeOptions were changed - const resetInternedStrings = - !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); + const resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { internedSizes = { tabSize: options.tabSize!, indentSize: options.indentSize! }; diff --git a/src/services/formatting/formattingContext.ts b/src/services/formatting/formattingContext.ts index 435b2dec686e1..660f7199ba9eb 100644 --- a/src/services/formatting/formattingContext.ts +++ b/src/services/formatting/formattingContext.ts @@ -6,7 +6,9 @@ import { SourceFileLike, SyntaxKind, } from "../_namespaces/ts"; -import { TextRangeWithKind } from "../_namespaces/ts.formatting"; +import { + TextRangeWithKind, +} from "../_namespaces/ts.formatting"; /** @internal */ export const enum FormattingRequestKind { @@ -15,7 +17,7 @@ export const enum FormattingRequestKind { FormatOnEnter, FormatOnSemicolon, FormatOnOpeningCurlyBrace, - FormatOnClosingCurlyBrace + FormatOnClosingCurlyBrace, } /** @internal */ @@ -70,7 +72,7 @@ export class FormattingContext { if (this.tokensAreOnSameLine === undefined) { const startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; const endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; - this.tokensAreOnSameLine = (startLine === endLine); + this.tokensAreOnSameLine = startLine === endLine; } return this.tokensAreOnSameLine; diff --git a/src/services/formatting/formattingScanner.ts b/src/services/formatting/formattingScanner.ts index 6a8087390461d..78890ad3a29b3 100644 --- a/src/services/formatting/formattingScanner.ts +++ b/src/services/formatting/formattingScanner.ts @@ -113,7 +113,7 @@ export function getFormattingScanner(text: string, languageVariant: LanguageV const item: TextRangeWithTriviaKind = { pos, end: scanner.getTokenFullStart(), - kind: t + kind: t, }; pos = scanner.getTokenFullStart(); diff --git a/src/services/formatting/rule.ts b/src/services/formatting/rule.ts index 99c7c08e1d904..176c0774c2cd4 100644 --- a/src/services/formatting/rule.ts +++ b/src/services/formatting/rule.ts @@ -2,7 +2,9 @@ import { emptyArray, SyntaxKind, } from "../_namespaces/ts"; -import { FormattingContext } from "../_namespaces/ts.formatting"; +import { + FormattingContext, +} from "../_namespaces/ts.formatting"; /** @internal */ export interface Rule { @@ -18,6 +20,7 @@ export type ContextPredicate = (context: FormattingContext) => boolean; /** @internal */ export const anyContext: readonly ContextPredicate[] = emptyArray; +// dprint-ignore /** @internal */ export const enum RuleAction { None = 0, diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 3d9c201a5050b..f57de9336d92e 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -58,14 +58,24 @@ export function getAllRules(): RuleSpec[] { const keywords = tokenRangeFromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword); const binaryOperators = tokenRangeFromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator); const binaryKeywordOperators = [ - SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, - SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, - SyntaxKind.IsKeyword, SyntaxKind.SatisfiesKeyword, + SyntaxKind.InKeyword, + SyntaxKind.InstanceOfKeyword, + SyntaxKind.OfKeyword, + SyntaxKind.AsKeyword, + SyntaxKind.IsKeyword, + SyntaxKind.SatisfiesKeyword, ]; const unaryPrefixOperators = [SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]; const unaryPrefixExpressions = [ - SyntaxKind.NumericLiteral, SyntaxKind.BigIntLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, - SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; + SyntaxKind.NumericLiteral, + SyntaxKind.BigIntLiteral, + SyntaxKind.Identifier, + SyntaxKind.OpenParenToken, + SyntaxKind.OpenBracketToken, + SyntaxKind.OpenBraceToken, + SyntaxKind.ThisKeyword, + SyntaxKind.NewKeyword, + ]; const unaryPreincrementExpressions = [SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; const unaryPostincrementExpressions = [SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]; const unaryPredecrementExpressions = [SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; @@ -216,13 +226,15 @@ export function getAllRules(): RuleSpec[] { ], anyToken, [isNonJsxSameLineTokenContext], - RuleAction.InsertSpace), + RuleAction.InsertSpace, + ), rule( "SpaceBeforeCertainTypeScriptKeywords", anyToken, [SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.FromKeyword], [isNonJsxSameLineTokenContext], - RuleAction.InsertSpace), + RuleAction.InsertSpace, + ), // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { rule("SpaceAfterModuleName", SyntaxKind.StringLiteral, SyntaxKind.OpenBraceToken, [isModuleDeclContext], RuleAction.InsertSpace), @@ -245,15 +257,16 @@ export function getAllRules(): RuleSpec[] { rule("NoSpaceAfterCloseAngularBracket", SyntaxKind.GreaterThanToken, [SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.GreaterThanToken, SyntaxKind.CommaToken], [ isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, - isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/, - isNonTypeAssertionContext + isNotFunctionDeclContext, /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/ + isNonTypeAssertionContext, ], RuleAction.DeleteSpace), // decorators rule("SpaceBeforeAt", [SyntaxKind.CloseParenToken, SyntaxKind.Identifier], SyntaxKind.AtToken, [isNonJsxSameLineTokenContext], RuleAction.InsertSpace), rule("NoSpaceAfterAt", SyntaxKind.AtToken, anyToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), // Insert space after @ in decorator - rule("SpaceAfterDecorator", + rule( + "SpaceAfterDecorator", anyToken, [ SyntaxKind.AbstractKeyword, @@ -271,7 +284,8 @@ export function getAllRules(): RuleSpec[] { SyntaxKind.AsteriskToken, ], [isEndOfDecoratorContextOnSameLine], - RuleAction.InsertSpace), + RuleAction.InsertSpace, + ), rule("NoSpaceBeforeNonNullAssertionOperator", anyToken, SyntaxKind.ExclamationToken, [isNonJsxSameLineTokenContext, isNonNullAssertionContext], RuleAction.DeleteSpace), rule("NoSpaceAfterNewKeywordOnConstructorSignature", SyntaxKind.NewKeyword, SyntaxKind.OpenParenToken, [isNonJsxSameLineTokenContext, isConstructorSignatureContext], RuleAction.DeleteSpace), @@ -391,7 +405,8 @@ export function getAllRules(): RuleSpec[] { [SyntaxKind.CloseParenToken, SyntaxKind.DoKeyword, SyntaxKind.ElseKeyword, SyntaxKind.CaseKeyword], anyToken, [isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNotForContext], - RuleAction.InsertSpace), + RuleAction.InsertSpace, + ), // This low-pri rule takes care of "try {", "catch {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. rule("SpaceAfterTryCatchFinally", [SyntaxKind.TryKeyword, SyntaxKind.CatchKeyword, SyntaxKind.FinallyKeyword], SyntaxKind.OpenBraceToken, [isNonJsxSameLineTokenContext], RuleAction.InsertSpace), ]; @@ -449,27 +464,27 @@ function tokenRangeFromRange(from: SyntaxKind, to: SyntaxKind, except: readonly /// function optionEquals(optionName: K, optionValue: FormatCodeSettings[K]): (context: FormattingContext) => boolean { - return (context) => context.options && context.options[optionName] === optionValue; + return context => context.options && context.options[optionName] === optionValue; } function isOptionEnabled(optionName: keyof FormatCodeSettings): (context: FormattingContext) => boolean { - return (context) => context.options && hasProperty(context.options, optionName) && !!context.options[optionName]; + return context => context.options && hasProperty(context.options, optionName) && !!context.options[optionName]; } function isOptionDisabled(optionName: keyof FormatCodeSettings): (context: FormattingContext) => boolean { - return (context) => context.options && hasProperty(context.options, optionName) && !context.options[optionName]; + return context => context.options && hasProperty(context.options, optionName) && !context.options[optionName]; } function isOptionDisabledOrUndefined(optionName: keyof FormatCodeSettings): (context: FormattingContext) => boolean { - return (context) => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName]; + return context => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName]; } function isOptionDisabledOrUndefinedOrTokensOnSameLine(optionName: keyof FormatCodeSettings): (context: FormattingContext) => boolean { - return (context) => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); + return context => !context.options || !hasProperty(context.options, optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); } function isOptionEnabledOrUndefined(optionName: keyof FormatCodeSettings): (context: FormattingContext) => boolean { - return (context) => !context.options || !hasProperty(context.options, optionName) || !!context.options[optionName]; + return context => !context.options || !hasProperty(context.options, optionName) || !!context.options[optionName]; } function isForContext(context: FormattingContext): boolean { @@ -548,7 +563,7 @@ function isTypeAnnotationContext(context: FormattingContext): boolean { function isConditionalOperatorContext(context: FormattingContext): boolean { return context.contextNode.kind === SyntaxKind.ConditionalExpression || - context.contextNode.kind === SyntaxKind.ConditionalType; + context.contextNode.kind === SyntaxKind.ConditionalType; } function isSameLineTokenOrBeforeBlockContext(context: FormattingContext): boolean { @@ -835,7 +850,6 @@ function isTypeArgumentOrParameterOrAssertion(token: TextRangeWithKind, parent: return true; default: return false; - } } @@ -891,7 +905,8 @@ function isSemicolonDeletionContext(context: FormattingContext): boolean { ? findNextToken( context.currentTokenParent, findAncestor(context.currentTokenParent, a => !a.parent)!, - context.sourceFile) + context.sourceFile, + ) : context.nextTokenParent.getFirstToken(context.sourceFile); if (!nextRealToken) { return true; @@ -907,13 +922,15 @@ function isSemicolonDeletionContext(context: FormattingContext): boolean { || nextTokenKind === SyntaxKind.EndOfFileToken; } - if (nextTokenKind === SyntaxKind.SemicolonClassElement || + if ( + nextTokenKind === SyntaxKind.SemicolonClassElement || nextTokenKind === SyntaxKind.SemicolonToken ) { return false; } - if (context.contextNode.kind === SyntaxKind.InterfaceDeclaration || + if ( + context.contextNode.kind === SyntaxKind.InterfaceDeclaration || context.contextNode.kind === SyntaxKind.TypeAliasDeclaration ) { // Can't remove semicolon after `foo`; it would parse as a method declaration: diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index 8970be77c18a5..15ee6fa629043 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -110,7 +110,7 @@ enum RulesPosition { ContextRulesSpecific = maskBitSize * 2, ContextRulesAny = maskBitSize * 3, NoContextRulesSpecific = maskBitSize * 4, - NoContextRulesAny = maskBitSize * 5 + NoContextRulesAny = maskBitSize * 5, } // The Rules list contains all the inserted rules into a rulebucket in the following order: @@ -132,8 +132,8 @@ function addRule(rules: Rule[], rule: Rule, specificTokens: boolean, constructio const position = rule.action & RuleAction.StopAction ? specificTokens ? RulesPosition.StopRulesSpecific : RulesPosition.StopRulesAny : rule.context !== anyContext ? - specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny : - specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny : + specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; const state = constructionState[rulesBucketIndex] || 0; rules.splice(getInsertionIndex(state, position), 0, rule); diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 1ab72e8c99bb2..d2468b1b2e10b 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -60,9 +60,8 @@ import { /** @internal */ export namespace SmartIndenter { - const enum Value { - Unknown = -1 + Unknown = -1, } /** @@ -245,7 +244,8 @@ export namespace SmartIndenter { indentationDelta: number, sourceFile: SourceFile, isNextChild: boolean, - options: EditorSettings): number { + options: EditorSettings, + ): number { let parent = current.parent; // Walk up the tree and collect indentation for parent-child node pairs. Indentation is not added if @@ -259,8 +259,7 @@ export namespace SmartIndenter { } const containingListOrParentStart = getContainingListOrParentStart(parent, current, sourceFile); - const parentAndChildShareLine = - containingListOrParentStart.line === currentStart.line || + const parentAndChildShareLine = containingListOrParentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); if (useActualIndentation) { @@ -309,8 +308,7 @@ export namespace SmartIndenter { // Instead, when at an argument, we unspoof the starting position of the enclosing call expression // *after* applying indentation for the argument. - const useTrueStart = - isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); + const useTrueStart = isArgumentAndStartLineOverlapsExpressionBeingCalled(parent, current, currentStart.line, sourceFile); current = parent; parent = current.parent; @@ -344,18 +342,11 @@ export namespace SmartIndenter { /* * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression) */ - function getActualIndentationForNode(current: Node, - parent: Node, - currentLineAndChar: LineAndCharacter, - parentAndChildShareLine: boolean, - sourceFile: SourceFile, - options: EditorSettings): number { - + function getActualIndentationForNode(current: Node, parent: Node, currentLineAndChar: LineAndCharacter, parentAndChildShareLine: boolean, sourceFile: SourceFile, options: EditorSettings): number { // actual indentation is used for statements\declarations if one of cases below is true: // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line - const useActualIndentation = - (isDeclaration(current) || isStatementButNotDeclaration(current)) && + const useActualIndentation = (isDeclaration(current) || isStatementButNotDeclaration(current)) && (parent.kind === SyntaxKind.SourceFile || !parentAndChildShareLine); if (!useActualIndentation) { @@ -368,7 +359,7 @@ export namespace SmartIndenter { const enum NextTokenKind { Unknown, OpenBrace, - CloseBrace + CloseBrace, } function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken: Node, current: Node, lineAtPosition: number, sourceFile: SourceFile): NextTokenKind { diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index ef3a1107fca0b..fdc4c1e412534 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -120,10 +120,12 @@ function updateTsconfigFiles(program: Program, changeTracker: textChanges.Change if (foundExactMatch || propertyName !== "include" || !isArrayLiteralExpression(property.initializer)) return; const includes = mapDefined(property.initializer.elements, e => isStringLiteral(e) ? e.text : undefined); if (includes.length === 0) return; - const matchers = getFileMatcherPatterns(configDir, /*excludes*/[], includes, useCaseSensitiveFileNames, currentDirectory); + const matchers = getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); // If there isn't some include for this, add a new one. - if (getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && - !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if ( + getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !getRegexFromPattern(Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath) + ) { changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), factory.createStringLiteral(relativePath(newFileOrDirPath))); } return; @@ -136,7 +138,7 @@ function updateTsconfigFiles(program: Program, changeTracker: textChanges.Change updatePaths(property); } else if (propertyName === "paths") { - forEachProperty(property.initializer, (pathsProperty) => { + forEachProperty(property.initializer, pathsProperty => { if (!isArrayLiteralExpression(pathsProperty.initializer)) return; for (const e of pathsProperty.initializer.elements) { tryUpdateString(e); @@ -194,30 +196,27 @@ function updateImports( const importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined; - updateImportsWorker(sourceFile, changeTracker, - referenceText => { - if (!pathIsRelative(referenceText)) return undefined; - const oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); - const newAbsolute = oldToNew(oldAbsolute); - return newAbsolute === undefined ? undefined : ensurePathIsNonModuleName(getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); - }, - importLiteral => { - const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); - // No need to update if it's an ambient module^M - if (importedModuleSymbol?.declarations && importedModuleSymbol.declarations.some(d => isAmbientModule(d))) return undefined; + updateImportsWorker(sourceFile, changeTracker, referenceText => { + if (!pathIsRelative(referenceText)) return undefined; + const oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + const newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ensurePathIsNonModuleName(getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, importLiteral => { + const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + // No need to update if it's an ambient module^M + if (importedModuleSymbol?.declarations && importedModuleSymbol.declarations.some(d => isAmbientModule(d))) return undefined; - const toImport = oldFromNew !== undefined - // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. - // TODO:GH#18217 - ? getSourceFileToImportFromResolved(importLiteral, resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host as ModuleResolutionHost), - oldToNew, allFiles) - : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + const toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(importLiteral, resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host as ModuleResolutionHost), oldToNew, allFiles) + : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); - // Need an update if the imported file moved, or the importing file moved and was using a relative path. - return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && pathIsRelative(importLiteral.text))) - ? moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, getCanonicalFileName(newImportFromPath) as Path, toImport.newFileName, createModuleSpecifierResolutionHost(program, host), importLiteral.text) - : undefined; - }); + // Need an update if the imported file moved, or the importing file moved and was using a relative path. + return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && pathIsRelative(importLiteral.text))) + ? moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, getCanonicalFileName(newImportFromPath) as Path, toImport.newFileName, createModuleSpecifierResolutionHost(program, host), importLiteral.text) + : undefined; + }); } } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 3688a688c53d8..e622ed105d443 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -3,7 +3,8 @@ import { AssignmentExpression, AssignmentOperatorToken, CallLikeExpression, - canHaveSymbol, concatenate, + canHaveSymbol, + concatenate, createTextSpan, createTextSpanFromBounds, createTextSpanFromNode, @@ -132,14 +133,13 @@ export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile } if (node.kind === SyntaxKind.ReturnKeyword) { - const functionDeclaration = findAncestor(node.parent, n => - isClassStaticBlockDeclaration(n) ? "quit" : isFunctionLikeDeclaration(n)) as FunctionLikeDeclaration | undefined; + const functionDeclaration = findAncestor(node.parent, n => isClassStaticBlockDeclaration(n) ? "quit" : isFunctionLikeDeclaration(n)) as FunctionLikeDeclaration | undefined; return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : undefined; } if (node.kind === SyntaxKind.AwaitKeyword) { const functionDeclaration = findAncestor(node, n => isFunctionLikeDeclaration(n)) as FunctionLikeDeclaration | undefined; - const isAsyncFunction = functionDeclaration && some(functionDeclaration.modifiers, (node) => node.kind === SyntaxKind.AsyncKeyword); + const isAsyncFunction = functionDeclaration && some(functionDeclaration.modifiers, node => node.kind === SyntaxKind.AsyncKeyword); return isAsyncFunction ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : undefined; } @@ -241,8 +241,10 @@ export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile // pr/*destination*/op1: number // } // bar(({pr/*goto*/op1})=>{}); - if (isPropertyName(node) && isBindingElement(parent) && isObjectBindingPattern(parent.parent) && - (node === (parent.propertyName || parent.name))) { + if ( + isPropertyName(node) && isBindingElement(parent) && isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name)) + ) { const name = getNameFromPropertyName(node); const type = typeChecker.getTypeAtLocation(parent.parent); return name === undefined ? emptyArray : flatMap(type.isUnion() ? type.types : [type], t => { @@ -281,8 +283,7 @@ function getDefinitionFromObjectLiteralElement(typeChecker: TypeChecker, node: N if (element) { const contextualType = element && typeChecker.getContextualType(element.parent); if (contextualType) { - return flatMap(getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), propertySymbol => - getDefinitionFromSymbol(typeChecker, propertySymbol, node)); + return flatMap(getPropertySymbolsFromContextualType(element, typeChecker, contextualType, /*unionSymbolOk*/ false), propertySymbol => getDefinitionFromSymbol(typeChecker, propertySymbol, node)); } } return emptyArray; @@ -311,7 +312,7 @@ function getDefinitionFromOverriddenMember(typeChecker: TypeChecker, node: Node) } /** @internal */ -export function getReferenceAtPosition(sourceFile: SourceFile, position: number, program: Program): { reference: FileReference, fileName: string, unverified: boolean, file?: SourceFile } | undefined { +export function getReferenceAtPosition(sourceFile: SourceFile, position: number, program: Program): { reference: FileReference; fileName: string; unverified: boolean; file?: SourceFile; } | undefined { const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { const file = program.getSourceFileFromReference(sourceFile, referencePath); @@ -342,7 +343,7 @@ export function getReferenceAtPosition(sourceFile: SourceFile, position: number, reference: { pos: node.getStart(), end: node.getEnd(), - fileName: node.text + fileName: node.text, }, unverified: !verifiedFileName, }; @@ -443,20 +444,21 @@ export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile return typeDefinitions.length ? [...getFirstTypeArgumentDefinitions(typeChecker, resolvedType, node, failedAliasResolution), ...typeDefinitions] : !(symbol.flags & SymbolFlags.Value) && symbol.flags & SymbolFlags.Type ? getDefinitionFromSymbol(typeChecker, skipAlias(symbol, typeChecker), node, failedAliasResolution) - : undefined; + : undefined; } function definitionFromType(type: Type, checker: TypeChecker, node: Node, failedAliasResolution: boolean | undefined): readonly DefinitionInfo[] { - return flatMap(type.isUnion() && !(type.flags & TypeFlags.Enum) ? type.types : [type], t => - t.symbol && getDefinitionFromSymbol(checker, t.symbol, node, failedAliasResolution)); + return flatMap(type.isUnion() && !(type.flags & TypeFlags.Enum) ? type.types : [type], t => t.symbol && getDefinitionFromSymbol(checker, t.symbol, node, failedAliasResolution)); } function tryGetReturnTypeOfFunction(symbol: Symbol, type: Type, checker: TypeChecker): Type | undefined { // If the type is just a function's inferred type, // go-to-type should go to the return type instead, since go-to-definition takes you to the function anyway. - if (type.symbol === symbol || + if ( + type.symbol === symbol || // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` - symbol.valueDeclaration && type.symbol && isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration as Node) { + symbol.valueDeclaration && type.symbol && isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration as Node + ) { const sigs = type.getCallSignatures(); if (sigs.length === 1) return checker.getReturnTypeOfSignature(first(sigs)); } @@ -621,7 +623,7 @@ function createDefinitionInfoFromName(checker: TypeChecker, declaration: Declara ...FindAllReferences.toContextSpan( textSpan, sourceFile, - FindAllReferences.getContextNode(declaration) + FindAllReferences.getContextNode(declaration), ), isLocal: !isDefinitionVisible(checker, declaration), isAmbient: !!(declaration.flags & NodeFlags.Ambient), diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index f79eb63627f3c..b0e7215625e12 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -121,12 +121,21 @@ export interface ExportInfo { } /** @internal */ -export const enum ExportKind { Named, Default, ExportEquals } +export const enum ExportKind { + Named, + Default, + ExportEquals, +} /** @internal */ -export const enum ImportExport { Import, Export } +export const enum ImportExport { + Import, + Export, +} -interface AmbientModuleDeclaration extends ModuleDeclaration { body?: ModuleBlock; } +interface AmbientModuleDeclaration extends ModuleDeclaration { + body?: ModuleBlock; +} type SourceFileLike = SourceFile | AmbientModuleDeclaration; // Identifier for the case of `const x = require("y")`. type Importer = AnyImportOrReExport | ValidImportTypeNode | Identifier; @@ -140,7 +149,7 @@ function getImportersForExport( { exportingModuleSymbol, exportKind }: ExportInfo, checker: TypeChecker, cancellationToken: CancellationToken | undefined, -): { directImports: Importer[], indirectUsers: readonly SourceFile[] } { +): { directImports: Importer[]; indirectUsers: readonly SourceFile[]; } { const markSeenDirectImport = nodeSeenTracker(); const markSeenIndirectUser = nodeSeenTracker(); const directImports: Importer[] = []; @@ -449,11 +458,11 @@ function findNamespaceReExports(sourceFileLike: SourceFileLike, name: Identifier /** @internal */ export type ModuleReference = /** "import" also includes require() calls. */ - | { kind: "import", literal: StringLiteralLike } + | { kind: "import"; literal: StringLiteralLike; } /** or */ - | { kind: "reference", referencingFile: SourceFile, ref: FileReference } + | { kind: "reference"; referencingFile: SourceFile; ref: FileReference; } /** Containing file implicitly references the module (eg, via implicit jsx runtime import) */ - | { kind: "implicit", literal: StringLiteralLike, referencingFile: SourceFile }; + | { kind: "implicit"; literal: StringLiteralLike; referencingFile: SourceFile; }; /** @internal */ export function findModuleReferences(program: Program, sourceFiles: readonly SourceFile[], searchModuleSymbol: Symbol): ModuleReference[] { @@ -509,7 +518,8 @@ function getDirectImportsMap(sourceFiles: readonly SourceFile[], checker: TypeCh /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike: SourceFileLike, action: (statement: Statement) => T) { - return forEach(sourceFileLike.kind === SyntaxKind.SourceFile ? sourceFileLike.statements : sourceFileLike.body!.statements, statement => // TODO: GH#18217 + return forEach(sourceFileLike.kind === SyntaxKind.SourceFile ? sourceFileLike.statements : sourceFileLike.body!.statements, statement => + // TODO: GH#18217 action(statement) || (isAmbientModuleDeclaration(statement) && forEach(statement.body && statement.body.statements, action))); } @@ -755,9 +765,11 @@ function skipExportSpecifierSymbol(symbol: Symbol, checker: TypeChecker): Symbol // Export of form 'module.exports.propName = expr'; return checker.getSymbolAtLocation(declaration)!; } - else if (isShorthandPropertyAssignment(declaration) + else if ( + isShorthandPropertyAssignment(declaration) && isBinaryExpression(declaration.parent.parent) - && getAssignmentDeclarationKind(declaration.parent.parent) === AssignmentDeclarationKind.ModuleExports) { + && getAssignmentDeclarationKind(declaration.parent.parent) === AssignmentDeclarationKind.ModuleExports + ) { return checker.getExportSpecifierLocalTargetSymbol(declaration.name)!; } } @@ -786,6 +798,6 @@ function isAmbientModuleDeclaration(node: Node): node is AmbientModuleDeclaratio return node.kind === SyntaxKind.ModuleDeclaration && (node as ModuleDeclaration).name.kind === SyntaxKind.StringLiteral; } -function isExternalModuleImportEquals(eq: ImportEqualsDeclaration): eq is ImportEqualsDeclaration & { moduleReference: { expression: StringLiteral } } { +function isExternalModuleImportEquals(eq: ImportEqualsDeclaration): eq is ImportEqualsDeclaration & { moduleReference: { expression: StringLiteral; }; } { return eq.moduleReference.kind === SyntaxKind.ExternalModuleReference && eq.moduleReference.expression.kind === SyntaxKind.StringLiteral; } diff --git a/src/services/inlayHints.ts b/src/services/inlayHints.ts index b7c8f87b7250a..6b741dcf9506e 100644 --- a/src/services/inlayHints.ts +++ b/src/services/inlayHints.ts @@ -441,7 +441,7 @@ export function provideInlayHints(context: InlayHintsContext): InlayHint[] { return { text, span: createTextSpanFromNode(node, sourceFile), - file: sourceFile.fileName + file: sourceFile.fileName, }; } } diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 6d23f64be662a..a68fdfcbfbae6 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -173,7 +173,7 @@ const jsDocTagNames = [ "variation", "version", "virtual", - "yields" + "yields", ]; let jsDocTagNameCompletionEntries: CompletionEntry[]; let jsDocTagCompletionEntries: CompletionEntry[]; @@ -194,12 +194,14 @@ export function getJsDocCommentsFromDeclarations(declarations: readonly Declarat // Exceptions: // - @typedefs are themselves declarations with associated comments // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation - if (jsdoc.comment === undefined && !inheritDoc + if ( + jsdoc.comment === undefined && !inheritDoc || isJSDoc(jsdoc) - && declaration.kind !== SyntaxKind.JSDocTypedefTag && declaration.kind !== SyntaxKind.JSDocCallbackTag - && jsdoc.tags - && jsdoc.tags.some(t => t.kind === SyntaxKind.JSDocTypedefTag || t.kind === SyntaxKind.JSDocCallbackTag) - && !jsdoc.tags.some(t => t.kind === SyntaxKind.JSDocParameterTag || t.kind === SyntaxKind.JSDocReturnTag)) { + && declaration.kind !== SyntaxKind.JSDocTypedefTag && declaration.kind !== SyntaxKind.JSDocCallbackTag + && jsdoc.tags + && jsdoc.tags.some(t => t.kind === SyntaxKind.JSDocTypedefTag || t.kind === SyntaxKind.JSDocCallbackTag) + && !jsdoc.tags.some(t => t.kind === SyntaxKind.JSDocParameterTag || t.kind === SyntaxKind.JSDocReturnTag) + ) { continue; } let newparts = jsdoc.comment ? getDisplayPartsFromComment(jsdoc.comment, checker) : []; @@ -225,7 +227,7 @@ function getCommentHavingNodes(declaration: Declaration): readonly (JSDoc | JSDo return [declaration as JSDocPropertyTag]; case SyntaxKind.JSDocCallbackTag: case SyntaxKind.JSDocTypedefTag: - return [(declaration as JSDocTypedefTag), (declaration as JSDocTypedefTag).parent]; + return [declaration as JSDocTypedefTag, (declaration as JSDocTypedefTag).parent]; default: return getJSDocCommentsAndTags(declaration); } @@ -240,8 +242,10 @@ export function getJsDocTagsFromDeclarations(declarations?: Declaration[], check // skip comments containing @typedefs since they're not associated with particular declarations // Exceptions: // - @param or @return indicate that the author thinks of it as a 'local' @typedef that's part of the function documentation - if (tags.some(t => t.kind === SyntaxKind.JSDocTypedefTag || t.kind === SyntaxKind.JSDocCallbackTag) - && !tags.some(t => t.kind === SyntaxKind.JSDocParameterTag || t.kind === SyntaxKind.JSDocReturnTag)) { + if ( + tags.some(t => t.kind === SyntaxKind.JSDocTypedefTag || t.kind === SyntaxKind.JSDocCallbackTag) + && !tags.some(t => t.kind === SyntaxKind.JSDocParameterTag || t.kind === SyntaxKind.JSDocReturnTag) + ) { return; } for (const tag of tags) { @@ -257,7 +261,7 @@ function getDisplayPartsFromComment(comment: string | readonly JSDocComment[], c } return flatMap( comment, - node => node.kind === SyntaxKind.JSDocText ? [textPart(node.text)] : buildLinkParts(node, checker) + node => node.kind === SyntaxKind.JSDocText ? [textPart(node.text)] : buildLinkParts(node, checker), ) as SymbolDisplayPart[]; } @@ -368,7 +372,7 @@ export function getJSDocTagCompletions(): CompletionEntry[] { name: `@${tagName}`, kind: ScriptElementKind.keyword, kindModifiers: "", - sortText: Completions.SortText.LocationPriority + sortText: Completions.SortText.LocationPriority, }; })); } @@ -400,8 +404,10 @@ export function getJSDocParameterNameCompletions(tag: JSDocParameterTag): Comple if (!isIdentifier(param.name)) return undefined; const name = param.name.text; - if (jsdoc.tags!.some(t => t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) // TODO: GH#18217 - || nameThusFar !== undefined && !startsWith(name, nameThusFar)) { + if ( + jsdoc.tags!.some(t => t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) // TODO: GH#18217 + || nameThusFar !== undefined && !startsWith(name, nameThusFar) + ) { return undefined; } @@ -469,17 +475,18 @@ export function getDocCommentTemplateAtPosition(newLine: string, sourceFile: Sou const { commentOwner, parameters, hasReturn } = commentOwnerInfo; const commentOwnerJsDoc = hasJSDocNodes(commentOwner) && commentOwner.jsDoc ? commentOwner.jsDoc : undefined; const lastJsDoc = lastOrUndefined(commentOwnerJsDoc); - if (commentOwner.getStart(sourceFile) < position + if ( + commentOwner.getStart(sourceFile) < position || lastJsDoc && existingDocComment - && lastJsDoc !== existingDocComment) { + && lastJsDoc !== existingDocComment + ) { return undefined; } const indentationStr = getIndentationStringAtPosition(sourceFile, position); const isJavaScriptFile = hasJSFileExtension(sourceFile.fileName); - const tags = - (parameters ? parameterDocComments(parameters || [], isJavaScriptFile, indentationStr, newLine) : "") + + const tags = (parameters ? parameterDocComments(parameters || [], isJavaScriptFile, indentationStr, newLine) : "") + (hasReturn ? returnsDocComment(indentationStr, newLine) : ""); // A doc comment consists of the following diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index c0dae08dd2b34..d4bb1f7358587 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -234,7 +234,7 @@ function emptyNavigationBarNode(node: Node, name?: DeclarationName): NavigationB additionalNodes: undefined, parent, children: undefined, - indent: parent.indent + 1 + indent: parent.indent + 1, }; } @@ -477,7 +477,7 @@ function addChildrenRecursively(node: Node | undefined): void { return; case AssignmentDeclarationKind.Prototype: case AssignmentDeclarationKind.PrototypeProperty: { - const binaryExpression = (node as BinaryExpression); + const binaryExpression = node as BinaryExpression; const assignmentTarget = binaryExpression.left as PropertyAccessExpression; const prototypeAccess = special === AssignmentDeclarationKind.PrototypeProperty ? @@ -499,19 +499,17 @@ function addChildrenRecursively(node: Node | undefined): void { if (isObjectLiteralExpression(binaryExpression.right)) { if (binaryExpression.right.properties.length > 0) { startNode(binaryExpression, className); - forEachChild(binaryExpression.right, addChildrenRecursively); + forEachChild(binaryExpression.right, addChildrenRecursively); endNode(); } } } else if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) { - addNodeWithRecursiveChild(node, - binaryExpression.right, - className); + addNodeWithRecursiveChild(node, binaryExpression.right, className); } else { startNode(binaryExpression, className); - addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name); + addNodeWithRecursiveChild(node, binaryExpression.right, assignmentTarget.name); endNode(); } endNestedNodes(depth); @@ -526,26 +524,28 @@ function addChildrenRecursively(node: Node | undefined): void { const memberName = defineCall.arguments[1]; const [depth, classNameIdentifier] = startNestedNodes(node, className); - startNode(node, classNameIdentifier); - startNode(node, setTextRange(factory.createIdentifier(memberName.text), memberName)); - addChildrenRecursively((node as CallExpression).arguments[2]); - endNode(); - endNode(); + startNode(node, classNameIdentifier); + startNode(node, setTextRange(factory.createIdentifier(memberName.text), memberName)); + addChildrenRecursively((node as CallExpression).arguments[2]); + endNode(); + endNode(); endNestedNodes(depth); return; } case AssignmentDeclarationKind.Property: { - const binaryExpression = (node as BinaryExpression); + const binaryExpression = node as BinaryExpression; const assignmentTarget = binaryExpression.left as PropertyAccessExpression | BindableElementAccessExpression; const targetFunction = assignmentTarget.expression; - if (isIdentifier(targetFunction) && getElementOrPropertyAccessName(assignmentTarget) !== "prototype" && - trackedEs5Classes && trackedEs5Classes.has(targetFunction.text)) { + if ( + isIdentifier(targetFunction) && getElementOrPropertyAccessName(assignmentTarget) !== "prototype" && + trackedEs5Classes && trackedEs5Classes.has(targetFunction.text) + ) { if (isFunctionExpression(binaryExpression.right) || isArrowFunction(binaryExpression.right)) { addNodeWithRecursiveChild(node, binaryExpression.right, targetFunction); } else if (isBindableStaticAccessExpression(assignmentTarget)) { startNode(binaryExpression, targetFunction); - addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, getNameOrArgument(assignmentTarget)); + addNodeWithRecursiveChild(binaryExpression.left, binaryExpression.right, getNameOrArgument(assignmentTarget)); endNode(); } return; @@ -638,20 +638,21 @@ function tryMergeEs5Class(a: NavigationBarNode, b: NavigationBarNode, bIndex: nu AssignmentDeclarationKind.None; // We treat this as an es5 class and merge the nodes in in one of several cases - if ((isEs5ClassMember[bAssignmentDeclarationKind] && isEs5ClassMember[aAssignmentDeclarationKind]) // merge two class elements + if ( + (isEs5ClassMember[bAssignmentDeclarationKind] && isEs5ClassMember[aAssignmentDeclarationKind]) // merge two class elements || (isPossibleConstructor(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // ctor function & member || (isPossibleConstructor(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & ctor function || (isClassDeclaration(a.node) && isSynthesized(a.node) && isEs5ClassMember[bAssignmentDeclarationKind]) // class (generated) & member || (isClassDeclaration(b.node) && isEs5ClassMember[aAssignmentDeclarationKind]) // member & class (generated) || (isClassDeclaration(a.node) && isSynthesized(a.node) && isPossibleConstructor(b.node)) // class (generated) & ctor || (isClassDeclaration(b.node) && isPossibleConstructor(a.node) && isSynthesized(a.node)) // ctor & class (generated) - ) { - + ) { let lastANode = a.additionalNodes && lastOrUndefined(a.additionalNodes) || a.node; - if ((!isClassDeclaration(a.node) && !isClassDeclaration(b.node)) // If neither outline node is a class + if ( + (!isClassDeclaration(a.node) && !isClassDeclaration(b.node)) // If neither outline node is a class || isPossibleConstructor(a.node) || isPossibleConstructor(b.node) // If either function is a constructor function - ) { + ) { const ctorFunction = isPossibleConstructor(a.node) ? a.node : isPossibleConstructor(b.node) ? b.node : undefined; @@ -659,7 +660,8 @@ function tryMergeEs5Class(a: NavigationBarNode, b: NavigationBarNode, bIndex: nu if (ctorFunction !== undefined) { const ctorNode = setTextRange( factory.createConstructorDeclaration(/*modifiers*/ undefined, [], /*body*/ undefined), - ctorFunction); + ctorFunction, + ); const ctor = emptyNavigationBarNode(ctorNode); ctor.indent = a.indent + 1; ctor.children = a.node === ctorFunction ? a.children : b.children; @@ -675,13 +677,16 @@ function tryMergeEs5Class(a: NavigationBarNode, b: NavigationBarNode, bIndex: nu } } - lastANode = a.node = setTextRange(factory.createClassDeclaration( - /*modifiers*/ undefined, - a.name as Identifier || factory.createIdentifier("__class__"), - /*typeParameters*/ undefined, - /*heritageClauses*/ undefined, - [] - ), a.node); + lastANode = a.node = setTextRange( + factory.createClassDeclaration( + /*modifiers*/ undefined, + a.name as Identifier || factory.createIdentifier("__class__"), + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, + [], + ), + a.node, + ); } else { a.children = concatenate(a.children, b.children); @@ -702,13 +707,16 @@ function tryMergeEs5Class(a: NavigationBarNode, b: NavigationBarNode, bIndex: nu } else { if (!a.additionalNodes) a.additionalNodes = []; - a.additionalNodes.push(setTextRange(factory.createClassDeclaration( - /*modifiers*/ undefined, - a.name as Identifier || factory.createIdentifier("__class__"), - /*typeParameters*/ undefined, - /*heritageClauses*/ undefined, - [] - ), b.node)); + a.additionalNodes.push(setTextRange( + factory.createClassDeclaration( + /*modifiers*/ undefined, + a.name as Identifier || factory.createIdentifier("__class__"), + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, + [], + ), + b.node, + )); } return true; } @@ -936,7 +944,7 @@ function convertToTree(n: NavigationBarNode): NavigationTree { kindModifiers: getModifiers(n.node), spans: getSpans(n), nameSpan: n.name && getNodeSpan(n.name), - childItems: map(n.children, convertToTree) + childItems: map(n.children, convertToTree), }; } @@ -949,7 +957,7 @@ function convertToPrimaryNavBarMenuItem(n: NavigationBarNode): NavigationBarItem childItems: map(n.children, convertToSecondaryNavBarMenuItem) || emptyChildItemArray, indent: n.indent, bolded: false, - grayed: false + grayed: false, }; function convertToSecondaryNavBarMenuItem(n: NavigationBarNode): NavigationBarItem { @@ -961,7 +969,7 @@ function convertToPrimaryNavBarMenuItem(n: NavigationBarNode): NavigationBarItem childItems: emptyChildItemArray, indent: 0, bolded: false, - grayed: false + grayed: false, }; } } diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index 573f908abf974..1a5fa964a9c63 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -104,8 +104,7 @@ export function organizeImports( // Exports are always used if (mode !== OrganizeImportsMode.RemoveUnused) { // All of the old ExportDeclarations in the file, in syntactic order. - getTopLevelExportGroups(sourceFile).forEach(exportGroupDecl => - organizeImportsWorker(exportGroupDecl, group => coalesceExportsWorker(group, comparer))); + getTopLevelExportGroups(sourceFile).forEach(exportGroupDecl => organizeImportsWorker(exportGroupDecl, group => coalesceExportsWorker(group, comparer))); } for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) { @@ -270,7 +269,8 @@ function removeUnusedImports(oldImports: readonly ImportDeclaration[], sourceFil importDecl.modifiers, /*importClause*/ undefined, moduleSpecifier, - /*assertClause*/ undefined)); + /*assertClause*/ undefined, + )); } // If we're not in a declaration file, we can't remove the import clause even though // the imported symbols are unused, because removing them makes it look like the import @@ -336,18 +336,19 @@ function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], compar // Add the namespace import to the existing default ImportDeclaration. const defaultImport = defaultImports[0]; coalescedImports.push( - updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); + updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings), + ); continue; } - const sortedNamespaceImports = stableSort(namespaceImports, (i1, i2) => - comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text)); + const sortedNamespaceImports = stableSort(namespaceImports, (i1, i2) => comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text)); for (const namespaceImport of sortedNamespaceImports) { // Drop the name, if any coalescedImports.push( - updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); + updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings), + ); } const firstDefaultImport = firstOrUndefined(defaultImports); @@ -365,7 +366,8 @@ function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], compar else { for (const defaultImport of defaultImports) { newImportSpecifiers.push( - factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("default"), defaultImport.importClause.name)); + factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("default"), defaultImport.importClause.name), + ); } } @@ -373,7 +375,7 @@ function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], compar const sortedImportSpecifiers = factory.createNodeArray( sortSpecifiers(newImportSpecifiers, comparer), - firstNamedImport?.importClause.namedBindings.elements.hasTrailingComma + firstNamedImport?.importClause.namedBindings.elements.hasTrailingComma, ); const newNamedImports = sortedImportSpecifiers.length === 0 @@ -381,10 +383,11 @@ function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], compar ? undefined : factory.createNamedImports(emptyArray) : firstNamedImport - ? factory.updateNamedImports(firstNamedImport.importClause.namedBindings, sortedImportSpecifiers) - : factory.createNamedImports(sortedImportSpecifiers); + ? factory.updateNamedImports(firstNamedImport.importClause.namedBindings, sortedImportSpecifiers) + : factory.createNamedImports(sortedImportSpecifiers); - if (sourceFile && + if ( + sourceFile && newNamedImports && firstNamedImport?.importClause.namedBindings && !rangeIsOnSingleLine(firstNamedImport.importClause.namedBindings, sourceFile) @@ -397,13 +400,16 @@ function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], compar // choose not to as a stylistic preference. if (isTypeOnly && newDefaultImport && newNamedImports) { coalescedImports.push( - updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ undefined)); + updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ undefined), + ); coalescedImports.push( - updateImportDeclarationAndClause(firstNamedImport ?? importDecl, /*name*/ undefined, newNamedImports)); + updateImportDeclarationAndClause(firstNamedImport ?? importDecl, /*name*/ undefined, newNamedImports), + ); } else { coalescedImports.push( - updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); + updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports), + ); } } @@ -524,7 +530,9 @@ function coalesceExportsWorker(exportGroup: readonly ExportDeclaration[], compar factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name) ), exportDecl.moduleSpecifier, - exportDecl.assertClause)); + exportDecl.assertClause, + ), + ); } return coalescedExports; @@ -564,14 +572,15 @@ function coalesceExportsWorker(exportGroup: readonly ExportDeclaration[], compar function updateImportDeclarationAndClause( importDeclaration: ImportDeclaration, name: Identifier | undefined, - namedBindings: NamedImportBindings | undefined) { - + namedBindings: NamedImportBindings | undefined, +) { return factory.updateImportDeclaration( importDeclaration, importDeclaration.modifiers, factory.updateImportClause(importDeclaration.importClause!, importDeclaration.importClause!.isTypeOnly, name, namedBindings), // TODO: GH#18217 importDeclaration.moduleSpecifier, - importDeclaration.assertClause); + importDeclaration.assertClause, + ); } function sortSpecifiers(specifiers: readonly T[], comparer: Comparer) { @@ -617,7 +626,8 @@ function getModuleSpecifierExpression(declaration: AnyImportOrRequireStatement): export function detectSorting(sourceFile: SourceFile, preferences: UserPreferences): SortKind { return detectSortingWorker( groupByNewlineContiguous(sourceFile, sourceFile.statements.filter(isImportDeclaration)), - preferences); + preferences, + ); } function detectSortingWorker(importGroups: ImportDeclaration[][], preferences: UserPreferences): SortKind { @@ -632,7 +642,8 @@ function detectSortingWorker(importGroups: ImportDeclaration[][], preferences: U importGroup, i => tryCast(i.moduleSpecifier, isStringLiteral)?.text ?? "", collateCaseSensitive, - collateCaseInsensitive); + collateCaseInsensitive, + ); if (moduleSpecifierSort) { // Don't let a single unsorted group of module specifiers make the whole algorithm detect unsorted. // If other things are sorted consistently, that's a stronger indicator than unsorted module specifiers. @@ -647,7 +658,8 @@ function detectSortingWorker(importGroups: ImportDeclaration[][], preferences: U // Check import specifiers const declarationWithNamedImports = find( importGroup, - i => tryCast(i.importClause?.namedBindings, isNamedImports)?.elements.length! > 1); + i => tryCast(i.importClause?.namedBindings, isNamedImports)?.elements.length! > 1, + ); if (declarationWithNamedImports) { const namedImportSort = detectImportSpecifierSorting((declarationWithNamedImports.importClause!.namedBindings as NamedImports).elements, preferences); if (namedImportSort) { @@ -679,7 +691,7 @@ export function detectImportDeclarationSorting(imports: readonly AnyImportOrRequ imports, s => getExternalModuleName(getModuleSpecifierExpression(s)) || "", collateCaseSensitive, - collateCaseInsensitive + collateCaseInsensitive, ); } @@ -765,9 +777,7 @@ function getNewImportSpecifiers(namedImports: ImportDeclaration[]) { map(tryGetNamedBindingElements(namedImport), importSpecifier => importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier(importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ undefined, importSpecifier.name) - : importSpecifier - ) - ); + : importSpecifier)); } function tryGetNamedBindingElements(namedImport: ImportDeclaration) { @@ -785,10 +795,9 @@ function getOrganizeImportsUnicodeStringComparer(ignoreCase: boolean, preference const caseFirst = preferences.organizeImportsCaseFirst ?? false; const numeric = preferences.organizeImportsNumericCollation ?? false; const accents = preferences.organizeImportsAccentCollation ?? true; - const sensitivity = - ignoreCase ? - accents ? "accent" : "base" : - accents ? "variant" : "case"; + const sensitivity = ignoreCase ? + accents ? "accent" : "base" : + accents ? "variant" : "case"; const collator = new Intl.Collator(resolvedLocale, { usage: "sort", diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index 212369a9df165..7409dc5f3c62d 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -18,7 +18,7 @@ export enum PatternMatchKind { exact, prefix, substring, - camelCase + camelCase, } // Information about a match made by the pattern matcher between a candidate and the @@ -108,7 +108,7 @@ interface TextChunk { function createPatternMatch(kind: PatternMatchKind, isCaseSensitive: boolean): PatternMatch { return { kind, - isCaseSensitive + isCaseSensitive, }; } @@ -127,7 +127,7 @@ export function createPatternMatcher(pattern: string): PatternMatcher | undefine return { getFullMatch: (containers, candidate) => getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans), getMatchForLastSegmentOfPattern: candidate => matchSegment(candidate, last(dotSeparatedSegments), stringToWordSpans), - patternContainsDots: dotSeparatedSegments.length > 1 + patternContainsDots: dotSeparatedSegments.length > 1, }; } @@ -149,9 +149,7 @@ function getFullMatch(candidateContainers: readonly string[], candidate: string, } let bestMatch: PatternMatch | undefined; - for (let i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; - i >= 0; - i -= 1, j -= 1) { + for (let i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans)); } return bestMatch; @@ -328,8 +326,10 @@ function tryCamelCaseMatch(candidate: string, candidateParts: TextSpan[], chunk: // We've already gotten one pattern part match in this candidate. We will // only continue trying to consumer pattern parts if the last part and this // part are both upper case. - if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || - !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { + if ( + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start)) + ) { break; } } @@ -366,7 +366,7 @@ function tryCamelCaseMatch(candidate: string, candidateParts: TextSpan[], chunk: function createSegment(text: string): Segment { return { totalTextChunk: createTextChunk(text), - subWordTextChunks: breakPatternIntoTextChunks(text) + subWordTextChunks: breakPatternIntoTextChunks(text), }; } @@ -396,7 +396,6 @@ function isLowerCaseLetter(ch: number) { return false; } - // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. const str = String.fromCharCode(ch); @@ -473,7 +472,7 @@ function createTextChunk(text: string): TextChunk { text, textLowerCase, isLowerCase: text === textLowerCase, - characterSpans: breakIntoCharacterSpans(text) + characterSpans: breakIntoCharacterSpans(text), }; } @@ -498,12 +497,13 @@ function breakIntoSpans(identifier: string, word: boolean): TextSpan[] { const hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); const hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart); - if (charIsPunctuation(identifier.charCodeAt(i - 1)) || + if ( + charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || lastIsDigit !== currentIsDigit || hasTransitionFromLowerToUpper || - hasTransitionFromUpperToLower) { - + hasTransitionFromUpperToLower + ) { if (!isAllPunctuation(identifier, wordStart, i)) { result.push(createTextSpan(wordStart, i - wordStart)); } diff --git a/src/services/preProcess.ts b/src/services/preProcess.ts index 91bbe396a2fd6..2d98a63586c55 100644 --- a/src/services/preProcess.ts +++ b/src/services/preProcess.ts @@ -23,10 +23,10 @@ export function preProcessFile(sourceText: string, readImportFiles = true, detec libReferenceDirectives: [], amdDependencies: [], hasNoDefaultLib: undefined, - moduleName: undefined + moduleName: undefined, }; const importedFiles: FileReference[] = []; - let ambientExternalModules: { ref: FileReference, depth: number }[] | undefined; + let ambientExternalModules: { ref: FileReference; depth: number; }[] | undefined; let lastToken: SyntaxKind; let currentToken: SyntaxKind; let braceNesting = 0; @@ -279,8 +279,10 @@ export function preProcessFile(sourceText: string, readImportFiles = true, detec token = nextToken(); if (token === SyntaxKind.OpenParenToken) { token = nextToken(); - if (token === SyntaxKind.StringLiteral || - allowTemplateLiterals && token === SyntaxKind.NoSubstitutionTemplateLiteral) { + if ( + token === SyntaxKind.StringLiteral || + allowTemplateLiterals && token === SyntaxKind.NoSubstitutionTemplateLiteral + ) { // require("mod"); recordModuleName(); } @@ -328,7 +330,6 @@ export function preProcessFile(sourceText: string, readImportFiles = true, detec token = nextToken(); } return true; - } return false; } @@ -361,7 +362,8 @@ export function preProcessFile(sourceText: string, readImportFiles = true, detec if (scanner.getToken() === SyntaxKind.TemplateHead) { const stack = [scanner.getToken()]; - loop: while (length(stack)) { + loop: + while (length(stack)) { const token = scanner.scan(); switch (token) { case SyntaxKind.EndOfFileToken: @@ -395,13 +397,15 @@ export function preProcessFile(sourceText: string, readImportFiles = true, detec } // check if at least one of alternative have moved scanner forward - if (tryConsumeDeclare() || + if ( + tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || (detectJavaScriptImports && ( tryConsumeRequireCall(/*skipCurrentToken*/ false, /*allowTemplateLiterals*/ true) || tryConsumeDefine() - ))) { + )) + ) { continue; } else { diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts index a540be35b511b..71759672452b2 100644 --- a/src/services/refactorProvider.ts +++ b/src/services/refactorProvider.ts @@ -7,7 +7,9 @@ import { RefactorContext, RefactorEditInfo, } from "./_namespaces/ts"; -import { refactorKindBeginsWith } from "./_namespaces/ts.refactor"; +import { + refactorKindBeginsWith, +} from "./_namespaces/ts.refactor"; // A map with the refactor code as key, the refactor itself as value // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want @@ -26,8 +28,8 @@ export function registerRefactor(name: string, refactor: Refactor) { export function getApplicableRefactors(context: RefactorContext, includeInteractiveActions?: boolean): ApplicableRefactorInfo[] { return arrayFrom(flatMapIterator(refactors.values(), refactor => context.cancellationToken && context.cancellationToken.isCancellationRequested() || - !refactor.kinds?.some(kind => refactorKindBeginsWith(kind, context.kind)) ? undefined : - refactor.getAvailableActions(context, includeInteractiveActions))); + !refactor.kinds?.some(kind => refactorKindBeginsWith(kind, context.kind)) ? undefined : + refactor.getAvailableActions(context, includeInteractiveActions))); } /** @internal */ diff --git a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts index 40640dc73ef55..0d7489554cf8f 100644 --- a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts +++ b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts @@ -45,12 +45,12 @@ const addBracesAction = { const removeBracesAction = { name: "Remove braces from arrow function", description: getLocaleSpecificMessage(Diagnostics.Remove_braces_from_arrow_function), - kind: "refactor.rewrite.arrow.braces.remove" + kind: "refactor.rewrite.arrow.braces.remove", }; registerRefactor(refactorName, { kinds: [removeBracesAction.kind], getEditsForAction: getRefactorEditsToRemoveFunctionBraces, - getAvailableActions: getRefactorActionsToRemoveFunctionBraces + getAvailableActions: getRefactorActionsToRemoveFunctionBraces, }); interface FunctionBracesInfo { @@ -70,8 +70,8 @@ function getRefactorActionsToRemoveFunctionBraces(context: RefactorContext): rea name: refactorName, description: refactorDescription, actions: [ - info.addBraces ? addBracesAction : removeBracesAction - ] + info.addBraces ? addBracesAction : removeBracesAction, + ], }]; } @@ -82,7 +82,7 @@ function getRefactorActionsToRemoveFunctionBraces(context: RefactorContext): rea actions: [ { ...addBracesAction, notApplicableReason: info.error }, { ...removeBracesAction, notApplicableReason: info.error }, - ] + ], }]; } @@ -127,13 +127,13 @@ function getConvertibleArrowFunctionAtPosition(file: SourceFile, startPosition: if (!func) { return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function), }; } if (!isArrowFunction(func)) { return { - error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) + error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function), }; } diff --git a/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts b/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts index 414ef006bc926..05d13bdc8fd91 100644 --- a/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts +++ b/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts @@ -80,10 +80,10 @@ registerRefactor(refactorName, { kinds: [ toAnonymousFunctionAction.kind, toNamedFunctionAction.kind, - toArrowFunctionAction.kind + toArrowFunctionAction.kind, ], getEditsForAction: getRefactorEditsToConvertFunctionExpressions, - getAvailableActions: getRefactorActionsToConvertFunctionExpressions + getAvailableActions: getRefactorActionsToConvertFunctionExpressions, }); interface FunctionInfo { @@ -119,7 +119,7 @@ function getRefactorActionsToConvertFunctionExpressions(context: RefactorContext if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { const error = !selectedVariableDeclaration && isArrowFunction(func) ? - undefined: getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); + undefined : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); if (error) { errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error }); } @@ -142,7 +142,7 @@ function getRefactorActionsToConvertFunctionExpressions(context: RefactorContext name: refactorName, description: refactorDescription, actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? - errors : possibleActions + errors : possibleActions, }]; } @@ -181,7 +181,6 @@ function getRefactorEditsToConvertFunctionExpressions(context: RefactorContext, function containingThis(node: Node): boolean { let containsThis = false; node.forEachChild(function checkThis(child) { - if (isThis(child)) { containsThis = true; return; @@ -308,7 +307,7 @@ function getEditInfoForConvertToArrowFunction(context: RefactorContext, func: Fu } function canBeConvertedToExpression(body: Block, head: Statement): head is ReturnStatement { - return body.statements.length === 1 && ((isReturnStatement(head) && !!head.expression)); + return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression); } function isFunctionReferencedInFile(sourceFile: SourceFile, typeChecker: TypeChecker, node: FunctionExpression): boolean { diff --git a/src/services/refactors/convertExport.ts b/src/services/refactors/convertExport.ts index 0509e1e0c512b..342013cdac37b 100644 --- a/src/services/refactors/convertExport.ts +++ b/src/services/refactors/convertExport.ts @@ -62,18 +62,18 @@ const refactorName = "Convert export"; const defaultToNamedAction = { name: "Convert default export to named export", description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), - kind: "refactor.rewrite.export.named" + kind: "refactor.rewrite.export.named", }; const namedToDefaultAction = { name: "Convert named export to default export", description: getLocaleSpecificMessage(Diagnostics.Convert_named_export_to_default_export), - kind: "refactor.rewrite.export.default" + kind: "refactor.rewrite.export.default", }; registerRefactor(refactorName, { kinds: [ defaultToNamedAction.kind, - namedToDefaultAction.kind + namedToDefaultAction.kind, ], getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context): readonly ApplicableRefactorInfo[] { const info = getInfo(context, context.triggerReason === "invoked"); @@ -86,10 +86,14 @@ registerRefactor(refactorName, { if (context.preferences.provideRefactorNotApplicableReason) { return [ - { name: refactorName, description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), actions: [ - { ...defaultToNamedAction, notApplicableReason: info.error }, - { ...namedToDefaultAction, notApplicableReason: info.error }, - ]} + { + name: refactorName, + description: getLocaleSpecificMessage(Diagnostics.Convert_default_export_to_named_export), + actions: [ + { ...defaultToNamedAction, notApplicableReason: info.error }, + { ...namedToDefaultAction, notApplicableReason: info.error }, + ], + }, ]; } @@ -134,7 +138,7 @@ function getInfo(context: RefactorContext, considerPartialSpans = true): ExportI const noSymbolError = (id: Node) => (isIdentifier(id) && checker.getSymbolAtLocation(id)) ? undefined - : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; + : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; switch (exportNode.kind) { case SyntaxKind.FunctionDeclaration: @@ -309,7 +313,6 @@ function changeNamedToDefaultImport(importingSourceFile: SourceFile, ref: Identi default: Debug.assertNever(parent, `Unexpected parent kind ${(parent as Node).kind}`); } - } function makeImportSpecifier(propertyName: string, name: string): ImportSpecifier { diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts index 319487ddb1968..fdcaccff5773c 100644 --- a/src/services/refactors/convertImport.ts +++ b/src/services/refactors/convertImport.ts @@ -85,7 +85,7 @@ registerRefactor(refactorName, { return getOwnValues(actions).map(action => ({ name: refactorName, description: action.description, - actions: [{ ...action, notApplicableReason: info.error }] + actions: [{ ...action, notApplicableReason: info.error }], })); } @@ -97,14 +97,14 @@ registerRefactor(refactorName, { Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program, t, info)); return { edits, renameFilename: undefined, renameLocation: undefined }; - } + }, }); // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. type ImportConversionInfo = - | { convertTo: ImportKind.Default, import: NamedImports } - | { convertTo: ImportKind.Namespace, import: NamedImports } - | { convertTo: ImportKind.Named, import: NamespaceImport }; + | { convertTo: ImportKind.Default; import: NamedImports; } + | { convertTo: ImportKind.Namespace; import: NamedImports; } + | { convertTo: ImportKind.Named; import: NamespaceImport; }; function getImportConversionInfo(context: RefactorContext, considerPartialSpans = true): ImportConversionInfo | RefactorErrorInfo | undefined { const { file } = context; @@ -259,12 +259,15 @@ export function doChangeNamedToNamespaceOrDefault(sourceFile: SourceFile, progra }); } - changes.replaceNode(sourceFile, toConvert, shouldUseDefault - ? factory.createIdentifier(namespaceImportName) - : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); + changes.replaceNode( + sourceFile, + toConvert, + shouldUseDefault + ? factory.createIdentifier(namespaceImportName) + : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName)), + ); if (neededNamedImports.size) { - const newNamedImports: ImportSpecifier[] = arrayFrom(neededNamedImports.values(), element => - factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); + const newNamedImports: ImportSpecifier[] = arrayFrom(neededNamedImports.values(), element => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, newNamedImports)); } } @@ -277,6 +280,5 @@ function isExportEqualsModule(moduleSpecifier: Expression, checker: TypeChecker) } function updateImport(old: ImportDeclaration, defaultImportName: Identifier | undefined, elements: readonly ImportSpecifier[] | undefined): ImportDeclaration { - return factory.createImportDeclaration(/*modifiers*/ undefined, - factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); + return factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } diff --git a/src/services/refactors/convertOverloadListToSingleSignature.ts b/src/services/refactors/convertOverloadListToSingleSignature.ts index 1a54a297eb772..6eccdbb06af61 100644 --- a/src/services/refactors/convertOverloadListToSingleSignature.ts +++ b/src/services/refactors/convertOverloadListToSingleSignature.ts @@ -40,7 +40,9 @@ import { textChanges, TupleTypeNode, } from "../_namespaces/ts"; -import { registerRefactor } from "../_namespaces/ts.refactor"; +import { + registerRefactor, +} from "../_namespaces/ts.refactor"; const refactorName = "Convert overload list to single signature"; const refactorDescription = getLocaleSpecificMessage(Diagnostics.Convert_overload_list_to_single_signature); @@ -53,7 +55,7 @@ const functionOverloadAction = { registerRefactor(refactorName, { kinds: [functionOverloadAction.kind], getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, - getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature + getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature, }); function getRefactorActionsToConvertOverloadsToOneSignature(context: RefactorContext): readonly ApplicableRefactorInfo[] { @@ -64,7 +66,7 @@ function getRefactorActionsToConvertOverloadsToOneSignature(context: RefactorCon return [{ name: refactorName, description: refactorDescription, - actions: [functionOverloadAction] + actions: [functionOverloadAction], }]; } @@ -100,7 +102,7 @@ function getRefactorEditsToConvertOverloadsToOneSignature(context: RefactorConte lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, - lastDeclaration.body + lastDeclaration.body, ); break; } @@ -118,7 +120,7 @@ function getRefactorEditsToConvertOverloadsToOneSignature(context: RefactorConte lastDeclaration, lastDeclaration.modifiers, getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.body + lastDeclaration.body, ); break; } @@ -140,11 +142,12 @@ function getRefactorEditsToConvertOverloadsToOneSignature(context: RefactorConte lastDeclaration.typeParameters, getNewParametersForCombinedSignature(signatureDecls), lastDeclaration.type, - lastDeclaration.body + lastDeclaration.body, ); break; } - default: return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); + default: + return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); } if (updated === lastDeclaration) { @@ -169,8 +172,8 @@ function getRefactorEditsToConvertOverloadsToOneSignature(context: RefactorConte factory.createToken(SyntaxKind.DotDotDotToken), "args", /*questionToken*/ undefined, - factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)) - ) + factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)), + ), ]); } @@ -181,12 +184,15 @@ function getRefactorEditsToConvertOverloadsToOneSignature(context: RefactorConte function convertParameterToNamedTupleMember(p: ParameterDeclaration): NamedTupleMember { Debug.assert(isIdentifier(p.name)); // This is checked during refactoring applicability checking - const result = setTextRange(factory.createNamedTupleMember( - p.dotDotDotToken, - p.name, - p.questionToken, - p.type || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword) - ), p); + const result = setTextRange( + factory.createNamedTupleMember( + p.dotDotDotToken, + p.name, + p.questionToken, + p.type || factory.createKeywordTypeNode(SyntaxKind.AnyKeyword), + ), + p, + ); const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); if (parameterDocComment) { const newComment = displayPartsToString(parameterDocComment); @@ -205,7 +211,6 @@ ${newComment.split("\n").map(c => ` * ${c}`).join("\n")} } return result; } - } function isConvertableSignatureDeclaration(d: Node): d is MethodSignature | MethodDeclaration | CallSignatureDeclaration | ConstructorDeclaration | ConstructSignatureDeclaration | FunctionDeclaration { diff --git a/src/services/refactors/convertParamsToDestructuredObject.ts b/src/services/refactors/convertParamsToDestructuredObject.ts index a86e190d2d8cd..e0d32869e5877 100644 --- a/src/services/refactors/convertParamsToDestructuredObject.ts +++ b/src/services/refactors/convertParamsToDestructuredObject.ts @@ -104,7 +104,9 @@ import { TypeNode, VariableDeclaration, } from "../_namespaces/ts"; -import { registerRefactor } from "../_namespaces/ts.refactor"; +import { + registerRefactor, +} from "../_namespaces/ts.refactor"; const refactorName = "Convert parameters to destructured object"; const minimumParameterLength = 1; @@ -113,12 +115,12 @@ const refactorDescription = getLocaleSpecificMessage(Diagnostics.Convert_paramet const toDestructuredAction = { name: refactorName, description: refactorDescription, - kind: "refactor.rewrite.parameters.toDestructured" + kind: "refactor.rewrite.parameters.toDestructured", }; registerRefactor(refactorName, { kinds: [toDestructuredAction.kind], getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, - getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject + getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject, }); function getRefactorActionsToConvertParametersToDestructuredObject(context: RefactorContext): readonly ApplicableRefactorInfo[] { @@ -131,7 +133,7 @@ function getRefactorActionsToConvertParametersToDestructuredObject(context: Refa return [{ name: refactorName, description: refactorDescription, - actions: [toDestructuredAction] + actions: [toDestructuredAction], }]; } @@ -156,7 +158,8 @@ function doChange( host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration, - groupedReferences: GroupedReferences): void { + groupedReferences: GroupedReferences, +): void { const signature = groupedReferences.signature; const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), param => getSynthesizedDeepClone(param)); @@ -175,7 +178,8 @@ function doChange( first(call.arguments), last(call.arguments), newArgument, - { leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: textChanges.TrailingTriviaOption.Include }); + { leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: textChanges.TrailingTriviaOption.Include }, + ); } } @@ -190,8 +194,9 @@ function doChange( // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter indentation: 0, leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: textChanges.TrailingTriviaOption.Include - }); + trailingTriviaOption: textChanges.TrailingTriviaOption.Include, + }, + ); } } @@ -337,10 +342,12 @@ function getSymbolForContextualType(node: Node, checker: TypeChecker): Symbol | function entryToImportOrExport(entry: FindAllReferences.NodeEntry): Node | undefined { const node = entry.node; - if (isImportSpecifier(node.parent) + if ( + isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) - || isNamespaceImport(node.parent)) { + || isNamespaceImport(node.parent) + ) { return node; } @@ -434,10 +441,12 @@ function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: numbe // don't offer refactor on top-level JSDoc if (isTopLevelJSDoc(node)) return undefined; - if (functionDeclaration + if ( + functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) - && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return functionDeclaration; + && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node)) + ) return functionDeclaration; return undefined; } @@ -457,7 +466,8 @@ function isValidMethodSignature(node: Node): node is ValidMethodSignature { function isValidFunctionDeclaration( functionDeclaration: FunctionLikeDeclaration, - checker: TypeChecker): functionDeclaration is ValidFunctionDeclaration { + checker: TypeChecker, +): functionDeclaration is ValidFunctionDeclaration { if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { case SyntaxKind.FunctionDeclaration: @@ -498,14 +508,16 @@ function hasNameOrDefault(functionOrClassDeclaration: FunctionDeclaration | Clas function isValidParameterNodeArray( parameters: NodeArray, - checker: TypeChecker): parameters is ValidParameterNodeArray { + checker: TypeChecker, +): parameters is ValidParameterNodeArray { return getRefactorableParametersLength(parameters) >= minimumParameterLength && every(parameters, /*callback*/ paramDecl => isValidParameterDeclaration(paramDecl, checker)); } function isValidParameterDeclaration( parameterDeclaration: ParameterDeclaration, - checker: TypeChecker): parameterDeclaration is ValidParameterDeclaration { + checker: TypeChecker, +): parameterDeclaration is ValidParameterDeclaration { if (isRestParameter(parameterDeclaration)) { const type = checker.getTypeAtLocation(parameterDeclaration); if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; @@ -585,7 +597,8 @@ function createNewParameters(functionDeclaration: ValidFunctionDeclaration | Val objectParameterName, /*questionToken*/ undefined, objectParameterType, - objectInitializer); + objectInitializer, + ); if (hasThisParameter(functionDeclaration.parameters)) { const thisParameter = functionDeclaration.parameters[0]; @@ -594,7 +607,8 @@ function createNewParameters(functionDeclaration: ValidFunctionDeclaration | Val /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, - thisParameter.type); + thisParameter.type, + ); suppressLeadingAndTrailingTrivia(newThisParameter.name); copyComments(thisParameter.name, newThisParameter.name); @@ -612,7 +626,8 @@ function createNewParameters(functionDeclaration: ValidFunctionDeclaration | Val /*dotDotDotToken*/ undefined, /*propertyName*/ undefined, getParameterName(parameterDeclaration), - isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer); + isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer, + ); suppressLeadingAndTrailingTrivia(element); if (parameterDeclaration.initializer && element.initializer) { @@ -637,7 +652,8 @@ function createNewParameters(functionDeclaration: ValidFunctionDeclaration | Val /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? factory.createToken(SyntaxKind.QuestionToken) : parameterDeclaration.questionToken, - parameterType); + parameterType, + ); suppressLeadingAndTrailingTrivia(propertySignature); copyComments(parameterDeclaration.name, propertySignature.name); @@ -675,7 +691,8 @@ function getClassNames(constructorDeclaration: ValidConstructor): (Identifier | // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` const defaultModifier = Debug.checkDefined( findModifier(classDeclaration, SyntaxKind.DefaultKeyword), - "Nameless class declaration should be a default export"); + "Nameless class declaration should be a default export", + ); return [defaultModifier]; case SyntaxKind.ClassExpression: const classExpression = constructorDeclaration.parent; @@ -694,14 +711,16 @@ function getFunctionNames(functionDeclaration: ValidFunctionDeclaration): Node[] // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` const defaultModifier = Debug.checkDefined( findModifier(functionDeclaration, SyntaxKind.DefaultKeyword), - "Nameless function declaration should be a default export"); + "Nameless function declaration should be a default export", + ); return [defaultModifier]; case SyntaxKind.MethodDeclaration: return [functionDeclaration.name]; case SyntaxKind.Constructor: const ctrKeyword = Debug.checkDefined( findChildOfKind(functionDeclaration, SyntaxKind.ConstructorKeyword, functionDeclaration.getSourceFile()), - "Constructor declaration should have constructor keyword"); + "Constructor declaration should have constructor keyword", + ); if (functionDeclaration.parent.kind === SyntaxKind.ClassExpression) { const variableDeclaration = functionDeclaration.parent.parent; return [variableDeclaration.name, ctrKeyword]; @@ -725,7 +744,7 @@ interface ValidVariableDeclaration extends VariableDeclaration { } interface ValidConstructor extends ConstructorDeclaration { - parent: ClassDeclaration | (ClassExpression & { parent: ValidVariableDeclaration }); + parent: ClassDeclaration | (ClassExpression & { parent: ValidVariableDeclaration; }); parameters: NodeArray; body: FunctionBody; } diff --git a/src/services/refactors/convertStringOrTemplateLiteral.ts b/src/services/refactors/convertStringOrTemplateLiteral.ts index 9611151953769..a13e4f6f6eb33 100644 --- a/src/services/refactors/convertStringOrTemplateLiteral.ts +++ b/src/services/refactors/convertStringOrTemplateLiteral.ts @@ -36,7 +36,9 @@ import { textChanges, Token, } from "../_namespaces/ts"; -import { registerRefactor } from "../_namespaces/ts.refactor"; +import { + registerRefactor, +} from "../_namespaces/ts.refactor"; const refactorName = "Convert to template string"; const refactorDescription = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); @@ -44,12 +46,12 @@ const refactorDescription = getLocaleSpecificMessage(Diagnostics.Convert_to_temp const convertStringAction = { name: refactorName, description: refactorDescription, - kind: "refactor.rewrite.string" + kind: "refactor.rewrite.string", }; registerRefactor(refactorName, { kinds: [convertStringAction.kind], getEditsForAction: getRefactorEditsToConvertToTemplateString, - getAvailableActions: getRefactorActionsToConvertToTemplateString + getAvailableActions: getRefactorActionsToConvertToTemplateString, }); function getRefactorActionsToConvertToTemplateString(context: RefactorContext): readonly ApplicableRefactorInfo[] { @@ -63,9 +65,7 @@ function getRefactorActionsToConvertToTemplateString(context: RefactorContext): return [refactorInfo]; } else if (context.preferences.provideRefactorNotApplicableReason) { - refactorInfo.actions.push({ ...convertStringAction, - notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) - }); + refactorInfo.actions.push({ ...convertStringAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) }); return [refactorInfo]; } return emptyArray; @@ -143,10 +143,9 @@ function getParentBinaryExpression(expr: Node) { } function treeToArray(current: Expression) { - const loop = (current: Node): { nodes: Expression[], operators: Token[], hasString: boolean, validOperators: boolean} => { + const loop = (current: Node): { nodes: Expression[]; operators: Token[]; hasString: boolean; validOperators: boolean; } => { if (!isBinaryExpression(current)) { - return { nodes: [current as Expression], operators: [], validOperators: true, - hasString: isStringLiteral(current) || isNoSubstitutionTemplateLiteral(current) }; + return { nodes: [current as Expression], operators: [], validOperators: true, hasString: isStringLiteral(current) || isNoSubstitutionTemplateLiteral(current) }; } const { nodes, operators, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current.left); @@ -170,14 +169,13 @@ function treeToArray(current: Expression) { // "foo" + /* comment */ "bar" const copyTrailingOperatorComments = (operators: Token[], file: SourceFile) => (index: number, targetNode: Node) => { if (index < operators.length) { - copyTrailingComments(operators[index], targetNode, file, SyntaxKind.MultiLineCommentTrivia, /*hasTrailingNewLine*/ false); + copyTrailingComments(operators[index], targetNode, file, SyntaxKind.MultiLineCommentTrivia, /*hasTrailingNewLine*/ false); } }; // to copy comments following the string // "foo" /* comment */ + "bar" /* comment */ + "bar2" -const copyCommentFromMultiNode = (nodes: readonly Expression[], file: SourceFile, copyOperatorComments: (index: number, targetNode: Node) => void) => -(indexes: number[], targetNode: Node) => { +const copyCommentFromMultiNode = (nodes: readonly Expression[], file: SourceFile, copyOperatorComments: (index: number, targetNode: Node) => void) => (indexes: number[], targetNode: Node) => { while (indexes.length > 0) { const index = indexes.shift()!; copyTrailingComments(nodes[index], targetNode, file, SyntaxKind.MultiLineCommentTrivia, /*hasTrailingNewLine*/ false); @@ -224,7 +222,7 @@ function concatConsecutiveString(index: number, nodes: readonly Expression[]): [ return [index, text, rawText, indexes]; } -function nodesToTemplate({ nodes, operators }: { nodes: readonly Expression[], operators: Token[] }, file: SourceFile) { +function nodesToTemplate({ nodes, operators }: { nodes: readonly Expression[]; operators: Token[]; }, file: SourceFile) { const copyOperatorComments = copyTrailingOperatorComments(operators, file); const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); @@ -253,9 +251,12 @@ function nodesToTemplate({ nodes, operators }: { nodes: readonly Expression[], o const isLastSpan = index === currentNode.templateSpans.length - 1; const text = span.literal.text + (isLastSpan ? subsequentText : ""); const rawText = getRawTextOfTemplate(span.literal) + (isLastSpan ? rawSubsequentText : ""); - return factory.createTemplateSpan(span.expression, isLast && isLastSpan - ? factory.createTemplateTail(text, rawText) - : factory.createTemplateMiddle(text, rawText)); + return factory.createTemplateSpan( + span.expression, + isLast && isLastSpan + ? factory.createTemplateTail(text, rawText) + : factory.createTemplateMiddle(text, rawText), + ); }); templateSpans.push(...spans); } diff --git a/src/services/refactors/convertToOptionalChainExpression.ts b/src/services/refactors/convertToOptionalChainExpression.ts index a86777e97dd63..ebacc0935a5c2 100644 --- a/src/services/refactors/convertToOptionalChainExpression.ts +++ b/src/services/refactors/convertToOptionalChainExpression.ts @@ -86,18 +86,16 @@ function getRefactorActionsToConvertToOptionalChain(context: RefactorContext): r function getRefactorEditsToConvertToOptionalChain(context: RefactorContext, actionName: string): RefactorEditInfo | undefined { const info = getInfo(context); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = textChanges.ChangeTracker.with(context, t => - doChange(context.file, context.program.getTypeChecker(), t, info, actionName) - ); + const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program.getTypeChecker(), t, info, actionName)); return { edits, renameFilename: undefined, renameLocation: undefined }; } type Occurrence = PropertyAccessExpression | ElementAccessExpression | Identifier; interface OptionalChainInfo { - finalExpression: PropertyAccessExpression | ElementAccessExpression | CallExpression, - occurrences: Occurrence[], - expression: ValidExpression, + finalExpression: PropertyAccessExpression | ElementAccessExpression | CallExpression; + occurrences: Occurrence[]; + expression: ValidExpression; } type ValidExpressionOrStatement = ValidExpression | ValidStatement; @@ -152,8 +150,10 @@ function getConditionalInfo(expression: ConditionalExpression, checker: TypeChec return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; } - if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) - && getMatchingStart(condition, finalExpression.expression)) { + if ( + (isPropertyAccessExpression(condition) || isIdentifier(condition)) + && getMatchingStart(condition, finalExpression.expression) + ) { return { finalExpression, occurrences: [condition], expression }; } else if (isBinaryExpression(condition)) { @@ -194,7 +194,7 @@ function getOccurrencesInExpression(matchTo: Expression, expression: Expression) if (finalMatch) { occurrences.push(finalMatch); } - return occurrences.length > 0 ? occurrences: undefined; + return occurrences.length > 0 ? occurrences : undefined; } /** @@ -217,8 +217,10 @@ function chainStartsWith(chain: Node, subchain: Node): boolean { chain = chain.expression; } // check that the chains match at each access. Call chains in subchain are not valid. - while ((isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain)) || - (isElementAccessExpression(chain) && isElementAccessExpression(subchain))) { + while ( + (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain)) || + (isElementAccessExpression(chain) && isElementAccessExpression(subchain)) + ) { if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) return false; chain = chain.expression; subchain = subchain.expression; @@ -338,9 +340,7 @@ function doChange(sourceFile: SourceFile, checker: TypeChecker, changes: textCha changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); } else if (isConditionalExpression(expression)) { - changes.replaceNode(sourceFile, expression, - factory.createBinaryExpression(convertedChain, factory.createToken(SyntaxKind.QuestionQuestionToken), expression.whenFalse) - ); + changes.replaceNode(sourceFile, expression, factory.createBinaryExpression(convertedChain, factory.createToken(SyntaxKind.QuestionQuestionToken), expression.whenFalse)); } } } diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 9efcce3006624..906ddefbcd1c7 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -180,7 +180,7 @@ const extractFunctionAction = { registerRefactor(refactorName, { kinds: [ extractConstantAction.kind, - extractFunctionAction.kind + extractFunctionAction.kind, ], getEditsForAction: getRefactorEditsToExtractSymbol, getAvailableActions: getRefactorActionsToExtractSymbol, @@ -207,14 +207,14 @@ export function getRefactorActionsToExtractSymbol(context: RefactorContext): rea errors.push({ name: refactorName, description: extractFunctionAction.description, - actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }], }); } if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { errors.push({ name: refactorName, description: extractConstantAction.description, - actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }], }); } return errors; @@ -247,7 +247,7 @@ export function getRefactorActionsToExtractSymbol(context: RefactorContext): rea functionActions.push({ description, name: `function_scope_${i}`, - kind: extractFunctionAction.kind + kind: extractFunctionAction.kind, }); } } @@ -256,7 +256,7 @@ export function getRefactorActionsToExtractSymbol(context: RefactorContext): rea description, name: `function_scope_${i}`, notApplicableReason: getStringError(functionExtraction.errors), - kind: extractFunctionAction.kind + kind: extractFunctionAction.kind, }; } } @@ -272,7 +272,7 @@ export function getRefactorActionsToExtractSymbol(context: RefactorContext): rea constantActions.push({ description, name: `constant_scope_${i}`, - kind: extractConstantAction.kind + kind: extractConstantAction.kind, }); } } @@ -281,7 +281,7 @@ export function getRefactorActionsToExtractSymbol(context: RefactorContext): rea description, name: `constant_scope_${i}`, notApplicableReason: getStringError(constantExtraction.errors), - kind: extractConstantAction.kind + kind: extractConstantAction.kind, }; } } @@ -304,7 +304,7 @@ export function getRefactorActionsToExtractSymbol(context: RefactorContext): rea infos.push({ name: refactorName, description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: [ innermostErrorFunctionAction ] + actions: [innermostErrorFunctionAction], }); } @@ -312,14 +312,14 @@ export function getRefactorActionsToExtractSymbol(context: RefactorContext): rea infos.push({ name: refactorName, description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: constantActions + actions: constantActions, }); } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) { infos.push({ name: refactorName, description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: [ innermostErrorConstantAction ] + actions: [innermostErrorConstantAction], }); } @@ -604,7 +604,7 @@ export function getRangeToExtract(sourceFile: SourceFile, span: TextSpan, invoke None = 0, Break = 1 << 0, Continue = 1 << 1, - Return = 1 << 2 + Return = 1 << 2, } // We believe it's true because the node is from the (unmodified) tree. @@ -920,8 +920,8 @@ function getPossibleExtractions(targetRange: TargetRange, context: RefactorConte const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) - ? getDescriptionForClassLikeDeclaration(scope) - : getDescriptionForModuleLikeDeclaration(scope); + ? getDescriptionForClassLikeDeclaration(scope) + : getDescriptionForModuleLikeDeclaration(scope); let functionDescription: string; let constantDescription: string; @@ -957,7 +957,7 @@ function getPossibleExtractions(targetRange: TargetRange, context: RefactorConte return extractions; } -function getPossibleExtractionsWorker(targetRange: TargetRange, context: RefactorContext): { readonly scopes: Scope[], readonly readsAndWrites: ReadsAndWrites } { +function getPossibleExtractionsWorker(targetRange: TargetRange, context: RefactorContext): { readonly scopes: Scope[]; readonly readsAndWrites: ReadsAndWrites; } { const { file: sourceFile } = context; const scopes = collectEnclosingScopes(targetRange); @@ -968,7 +968,8 @@ function getPossibleExtractionsWorker(targetRange: TargetRange, context: Refacto enclosingTextRange, sourceFile, context.program.getTypeChecker(), - context.cancellationToken!); + context.cancellationToken!, + ); return { scopes, readsAndWrites }; } @@ -976,8 +977,8 @@ function getDescriptionForFunctionInScope(scope: Scope): string { return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) - ? "method" - : "function"; + ? "method" + : "function"; } function getDescriptionForConstantInScope(scope: Scope): string { return isClassLike(scope) @@ -1031,8 +1032,8 @@ function extractFunctionInScope( { usages: usagesInScope, typeParameterUsages, substitutions }: ScopeUsages, exposedVariableDeclarations: readonly VariableDeclaration[], range: TargetRange, - context: RefactorContext): RefactorEditInfo { - + context: RefactorContext, +): RefactorEditInfo { const checker = context.program.getTypeChecker(); const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); const importAdder = codefix.createImportAdder(context.file, context.program, context.preferences, context.host); @@ -1062,7 +1063,7 @@ function extractFunctionInScope( /*dotDotDotToken*/ undefined, /*name*/ name, /*questionToken*/ undefined, - typeNode + typeNode, ); parameters.push(paramDecl); if (usage.usage === Usage.Write) { @@ -1115,7 +1116,7 @@ function extractFunctionInScope( typeParameters, parameters, returnType, - body + body, ); } else { @@ -1129,10 +1130,10 @@ function extractFunctionInScope( checker.typeToTypeNode( checker.getTypeAtLocation(range.thisNode!), scope, - NodeBuilderFlags.NoTruncation + NodeBuilderFlags.NoTruncation, ), /*initializer*/ undefined, - ) + ), ); } newFunction = factory.createFunctionDeclaration( @@ -1142,7 +1143,7 @@ function extractFunctionInScope( typeParameters, parameters, returnType, - body + body, ); } @@ -1168,10 +1169,11 @@ function extractFunctionInScope( let call: Expression = factory.createCallExpression( callThis ? factory.createPropertyAccessExpression( called, - "call" + "call", ) : called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference - callArguments); + callArguments, + ); if (range.facts & RangeFacts.IsGenerator) { call = factory.createYieldExpression(factory.createToken(SyntaxKind.AsteriskToken), call); } @@ -1196,7 +1198,9 @@ function extractFunctionInScope( /*modifiers*/ undefined, factory.createVariableDeclarationList( [factory.createVariableDeclaration(getSynthesizedDeepClone(variableDeclaration.name), /*exclamationToken*/ undefined, /*type*/ getSynthesizedDeepClone(variableDeclaration.type), /*initializer*/ call)], - variableDeclaration.parent.flags))); + variableDeclaration.parent.flags, + ), + )); } else { // Declaring multiple variables / return properties: @@ -1209,19 +1213,22 @@ function extractFunctionInScope( bindingElements.push(factory.createBindingElement( /*dotDotDotToken*/ undefined, /*propertyName*/ undefined, - /*name*/ getSynthesizedDeepClone(variableDeclaration.name))); + /*name*/ getSynthesizedDeepClone(variableDeclaration.name), + )); // Being returned through an object literal will have widened the type. const variableType: TypeNode | undefined = checker.typeToTypeNode( checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, - NodeBuilderFlags.NoTruncation); + NodeBuilderFlags.NoTruncation, + ); typeElements.push(factory.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, /*questionToken*/ undefined, - /*type*/ variableType)); + /*type*/ variableType, + )); sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; } @@ -1238,8 +1245,11 @@ function extractFunctionInScope( factory.createObjectBindingPattern(bindingElements), /*exclamationToken*/ undefined, /*type*/ typeLiteral, - /*initializer*/call)], - commonNodeFlags))); + /*initializer*/ call, + )], + commonNodeFlags, + ), + )); } } else if (exposedVariableDeclarations.length || writes) { @@ -1255,7 +1265,9 @@ function extractFunctionInScope( /*modifiers*/ undefined, factory.createVariableDeclarationList( [factory.createVariableDeclaration(variableDeclaration.symbol.name, /*exclamationToken*/ undefined, getTypeDeepCloneUnionUndefined(variableDeclaration.type))], - flags))); + flags, + ), + )); } } @@ -1265,7 +1277,9 @@ function extractFunctionInScope( /*modifiers*/ undefined, factory.createVariableDeclarationList( [factory.createVariableDeclaration(returnValueProperty, /*exclamationToken*/ undefined, getTypeDeepCloneUnionUndefined(returnType))], - NodeFlags.Let))); + NodeFlags.Let, + ), + )); } const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); @@ -1346,8 +1360,8 @@ function extractConstantInScope( scope: Scope, { substitutions }: ScopeUsages, rangeFacts: RangeFacts, - context: RefactorContext): RefactorEditInfo { - + context: RefactorContext, +): RefactorEditInfo { const checker = context.program.getTypeChecker(); // Make a unique name for the extracted variable @@ -1383,13 +1397,15 @@ function extractConstantInScope( localNameText, /*questionOrExclamationToken*/ undefined, variableType, - initializer); + initializer, + ); let localReference: Expression = factory.createPropertyAccessExpression( rangeFacts & RangeFacts.InStaticRegion ? factory.createIdentifier(scope.name!.getText()) // TODO: GH#18217 : factory.createThis(), - factory.createIdentifier(localNameText)); + factory.createIdentifier(localNameText), + ); if (isInJSXContent(node)) { localReference = factory.createJsxExpression(/*dotDotDotToken*/ undefined, localReference); @@ -1425,13 +1441,15 @@ function extractConstantInScope( // replace the statement with the declaration. const newVariableStatement = factory.createVariableStatement( /*modifiers*/ undefined, - factory.createVariableDeclarationList([newVariableDeclaration], NodeFlags.Const)); + factory.createVariableDeclarationList([newVariableDeclaration], NodeFlags.Const), + ); changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { const newVariableStatement = factory.createVariableStatement( /*modifiers*/ undefined, - factory.createVariableDeclarationList([newVariableDeclaration], NodeFlags.Const)); + factory.createVariableDeclarationList([newVariableDeclaration], NodeFlags.Const), + ); // Declare const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); @@ -1465,7 +1483,7 @@ function extractConstantInScope( const renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*preferLastLocation*/ true); return { renameFilename, renameLocation, edits }; - function transformFunctionInitializerAndType(variableType: TypeNode | undefined, initializer: Expression): { variableType: TypeNode | undefined, initializer: Expression } { + function transformFunctionInitializerAndType(variableType: TypeNode | undefined, initializer: Expression): { variableType: TypeNode | undefined; initializer: Expression; } { // If no contextual type exists there is nothing to transfer to the function signature if (variableType === undefined) return { variableType, initializer }; // Only do this for function expressions and arrow functions that are not generic @@ -1489,9 +1507,7 @@ function extractConstantInScope( const paramType = checker.getTypeAtLocation(p); if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(factory.updateParameterDeclaration(p, - p.modifiers, p.dotDotDotToken, - p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, NodeBuilderFlags.NoTruncation), p.initializer)); + parameters.push(factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, NodeBuilderFlags.NoTruncation), p.initializer)); } } // If a parameter was inferred as any we skip adding function parameters at all. @@ -1500,11 +1516,7 @@ function extractConstantInScope( if (hasAny) return { variableType, initializer }; variableType = undefined; if (isArrowFunction(initializer)) { - initializer = factory.updateArrowFunction(initializer, canHaveModifiers(node) ? getModifiers(node) : undefined, initializer.typeParameters, - parameters, - initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, NodeBuilderFlags.NoTruncation), - initializer.equalsGreaterThanToken, - initializer.body); + initializer = factory.updateArrowFunction(initializer, canHaveModifiers(node) ? getModifiers(node) : undefined, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, NodeBuilderFlags.NoTruncation), initializer.equalsGreaterThanToken, initializer.body); } else { if (functionSignature && !!functionSignature.thisParameter) { @@ -1513,20 +1525,20 @@ function extractConstantInScope( // Note: If this parameter was already there, it would have been previously updated with the type if not type was present if ((!firstParameter || (isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this"))) { const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); - parameters.splice(0, 0, factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - "this", - /*questionToken*/ undefined, - checker.typeToTypeNode(thisType, scope, NodeBuilderFlags.NoTruncation) - )); + parameters.splice( + 0, + 0, + factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + "this", + /*questionToken*/ undefined, + checker.typeToTypeNode(thisType, scope, NodeBuilderFlags.NoTruncation), + ), + ); } } - initializer = factory.updateFunctionExpression(initializer, canHaveModifiers(node) ? getModifiers(node) : undefined, initializer.asteriskToken, - initializer.name, initializer.typeParameters, - parameters, - initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, NodeBuilderFlags.NoTruncation), - initializer.body); + initializer = factory.updateFunctionExpression(initializer, canHaveModifiers(node) ? getModifiers(node) : undefined, initializer.asteriskToken, initializer.name, initializer.typeParameters, parameters, initializer.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, NodeBuilderFlags.NoTruncation), initializer.body); } return { variableType, initializer }; } @@ -1535,11 +1547,12 @@ function extractConstantInScope( function getContainingVariableDeclarationIfInList(node: Node, scope: Scope) { let prevNode; while (node !== undefined && node !== scope) { - if (isVariableDeclaration(node) && + if ( + isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && - node.parent.declarations.length > 1) { - + node.parent.declarations.length > 1 + ) { return node; } @@ -1564,13 +1577,14 @@ function getFirstDeclarationBeforePosition(type: Type, position: number): Declar } function compareTypesByDeclarationOrder( - { type: type1, declaration: declaration1 }: { type: Type, declaration?: Declaration }, - { type: type2, declaration: declaration2 }: { type: Type, declaration?: Declaration }) { - + { type: type1, declaration: declaration1 }: { type: Type; declaration?: Declaration; }, + { type: type2, declaration: declaration2 }: { type: Type; declaration?: Declaration; }, +) { return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( type1.symbol ? type1.symbol.getName() : "", - type2.symbol ? type2.symbol.getName() : "") + type2.symbol ? type2.symbol.getName() : "", + ) || compareValues(type1.id, type2.id); } @@ -1585,7 +1599,7 @@ function getCalledExpression(scope: Node, range: TargetRange, functionNameText: } } -function transformFunctionBody(body: Node, exposedVariableDeclarations: readonly VariableDeclaration[], writes: readonly UsageEntry[] | undefined, substitutions: ReadonlyMap, hasReturn: boolean): { body: Block, returnValueProperty: string | undefined } { +function transformFunctionBody(body: Node, exposedVariableDeclarations: readonly VariableDeclaration[], writes: readonly UsageEntry[] | undefined, substitutions: ReadonlyMap, hasReturn: boolean): { body: Block; returnValueProperty: string | undefined; } { const hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0; if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { // already block, no declarations or writes to propagate back, no substitutions - can use node as is @@ -1677,8 +1691,7 @@ function getStatementsOrClassElements(scope: Scope): readonly Statement[] | read * Otherwise, return `undefined`. */ function getNodeToInsertFunctionBefore(minPos: number, scope: Scope): Statement | ClassElement | undefined { - return find(getStatementsOrClassElements(scope), child => - child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); + return find(getStatementsOrClassElements(scope), child => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); } function getNodeToInsertPropertyBefore(maxPos: number, scope: ClassLikeDeclaration): ClassElement { @@ -1717,7 +1730,7 @@ function getNodeToInsertConstantBefore(node: Node, scope: Scope): Statement { } } - for (let curr = (prevScope || node).parent; ; curr = curr.parent) { + for (let curr = (prevScope || node).parent;; curr = curr.parent) { if (isBlockLike(curr)) { let prevStatement: Statement | undefined; for (const statement of curr.statements) { @@ -1743,7 +1756,7 @@ function getNodeToInsertConstantBefore(node: Node, scope: Scope): Statement { function getPropertyAssignmentsForWritesAndVariableDeclarations( exposedVariableDeclarations: readonly VariableDeclaration[], - writes: readonly UsageEntry[] | undefined + writes: readonly UsageEntry[] | undefined, ): ShorthandPropertyAssignment[] { const variableAssignments = map(exposedVariableDeclarations, v => factory.createShorthandPropertyAssignment(v.symbol.name)); const writeAssignments = map(writes, w => factory.createShorthandPropertyAssignment(w.symbol.name)); @@ -1752,8 +1765,8 @@ function getPropertyAssignmentsForWritesAndVariableDeclarations( return variableAssignments === undefined ? writeAssignments! : writeAssignments === undefined - ? variableAssignments - : variableAssignments.concat(writeAssignments); + ? variableAssignments + : variableAssignments.concat(writeAssignments); } function isReadonlyArray(v: any): v is readonly any[] { @@ -1779,7 +1792,7 @@ const enum Usage { // value should be passed to extracted method Read = 1, // value should be passed to extracted method and propagated back - Write = 2 + Write = 2, } interface UsageEntry { @@ -1807,8 +1820,8 @@ function collectReadsAndWrites( enclosingTextRange: TextRange, sourceFile: SourceFile, checker: TypeChecker, - cancellationToken: CancellationToken): ReadsAndWrites { - + cancellationToken: CancellationToken, +): ReadsAndWrites { const allTypeParameterUsages = new Map(); // Key is type ID const usagesPerScope: ScopeUsages[] = []; const substitutionsPerScope: Map[] = []; @@ -1822,8 +1835,8 @@ function collectReadsAndWrites( const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) - ? targetRange.range[0].expression - : undefined; + ? targetRange.range[0].expression + : undefined; let expressionDiagnostic: Diagnostic | undefined; if (expression === undefined) { @@ -1932,9 +1945,11 @@ function collectReadsAndWrites( usagesPerScope[i].usages.forEach(value => { if (value.usage === Usage.Write) { hasWrite = true; - if (value.symbol.flags & SymbolFlags.ClassMember && + if ( + value.symbol.flags & SymbolFlags.ClassMember && value.symbol.valueDeclaration && - hasEffectiveModifier(value.symbol.valueDeclaration, ModifierFlags.Readonly)) { + hasEffectiveModifier(value.symbol.valueDeclaration, ModifierFlags.Readonly) + ) { readonlyClassPropertyWrite = value.symbol.valueDeclaration; } } diff --git a/src/services/refactors/extractType.ts b/src/services/refactors/extractType.ts index 02e5f10ba22d9..205a23345930e 100644 --- a/src/services/refactors/extractType.ts +++ b/src/services/refactors/extractType.ts @@ -85,14 +85,14 @@ const extractToInterfaceAction = { const extractToTypeDefAction = { name: "Extract to typedef", description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), - kind: "refactor.extract.typedef" + kind: "refactor.extract.typedef", }; registerRefactor(refactorName, { kinds: [ extractToTypeAliasAction.kind, extractToInterfaceAction.kind, - extractToTypeDefAction.kind + extractToTypeDefAction.kind, ], getAvailableActions: function getRefactorActionsToExtractType(context): readonly ApplicableRefactorInfo[] { const info = getRangeToExtract(context, context.triggerReason === "invoked"); @@ -103,7 +103,7 @@ registerRefactor(refactorName, { name: refactorName, description: getLocaleSpecificMessage(Diagnostics.Extract_type), actions: info.isJS ? - [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction) + [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction), }]; } @@ -115,7 +115,7 @@ registerRefactor(refactorName, { { ...extractToTypeDefAction, notApplicableReason: info.error }, { ...extractToTypeAliasAction, notApplicableReason: info.error }, { ...extractToInterfaceAction, notApplicableReason: info.error }, - ] + ], }]; } @@ -146,15 +146,23 @@ registerRefactor(refactorName, { const renameFilename = file.fileName; const renameLocation = getRenameLocation(edits, renameFilename, name, /*preferLastLocation*/ false); return { edits, renameFilename, renameLocation }; - } + }, }); interface TypeAliasInfo { - isJS: boolean; selection: TypeNode; enclosingNode: Node; typeParameters: readonly TypeParameterDeclaration[]; typeElements?: readonly TypeElement[]; + isJS: boolean; + selection: TypeNode; + enclosingNode: Node; + typeParameters: readonly TypeParameterDeclaration[]; + typeElements?: readonly TypeElement[]; } interface InterfaceInfo { - isJS: boolean; selection: TypeNode; enclosingNode: Node; typeParameters: readonly TypeParameterDeclaration[]; typeElements: readonly TypeElement[]; + isJS: boolean; + selection: TypeNode; + enclosingNode: Node; + typeParameters: readonly TypeParameterDeclaration[]; + typeElements: readonly TypeElement[]; } type ExtractInfo = TypeAliasInfo | InterfaceInfo; @@ -166,8 +174,9 @@ function getRangeToExtract(context: RefactorContext, considerEmptySpans = true): const range = createTextRangeFromSpan(getRefactorContextSpan(context)); const cursorRequest = range.pos === range.end && considerEmptySpans; - const selection = findAncestor(current, (node => node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && - (cursorRequest || nodeOverlapsWithStartEnd(current, file, range.pos, range.end)))); + const selection = findAncestor(current, node => + node.parent && isTypeNode(node) && !rangeContainsSkipTrivia(range, node.parent, file) && + (cursorRequest || nodeOverlapsWithStartEnd(current, file, range.pos, range.end))); if (!selection || !isTypeNode(selection)) return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; const checker = context.program.getTypeChecker(); @@ -275,7 +284,7 @@ function doTypeAliasChange(changes: textChanges.ChangeTracker, file: SourceFile, /*modifiers*/ undefined, name, typeParameters.map(id => factory.updateTypeParameterDeclaration(id, id.modifiers, id.name, id.constraint, /*defaultType*/ undefined)), - selection + selection, ); changes.insertNodeBefore(file, enclosingNode, ignoreSourceNewlines(newTypeNode), /*blankLineBetween*/ true); changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map(id => factory.createTypeReferenceNode(id.name, /*typeArguments*/ undefined))), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: textChanges.TrailingTriviaOption.ExcludeWhitespace }); @@ -289,7 +298,7 @@ function doInterfaceChange(changes: textChanges.ChangeTracker, file: SourceFile, name, typeParameters, /*heritageClauses*/ undefined, - typeElements + typeElements, ); setTextRange(newTypeNode, typeElements[0]?.parent); changes.insertNodeBefore(file, enclosingNode, ignoreSourceNewlines(newTypeNode), /*blankLineBetween*/ true); @@ -304,7 +313,8 @@ function doTypedefChange(changes: textChanges.ChangeTracker, context: RefactorCo const node = factory.createJSDocTypedefTag( factory.createIdentifier("typedef"), factory.createJSDocTypeExpression(selection), - factory.createIdentifier(name)); + factory.createIdentifier(name), + ); const templates: JSDocTemplateTag[] = []; forEach(typeParameters, typeParameter => { @@ -313,7 +323,7 @@ function doTypedefChange(changes: textChanges.ChangeTracker, context: RefactorCo const template = factory.createJSDocTemplateTag( factory.createIdentifier("template"), constraint && cast(constraint, isJSDocTypeExpression), - [parameter] + [parameter], ); templates.push(template); }); @@ -323,7 +333,7 @@ function doTypedefChange(changes: textChanges.ChangeTracker, context: RefactorCo const pos = enclosingNode.getStart(file); const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext?.options); changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { - suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) + suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos), }); } else { diff --git a/src/services/refactors/generateGetAccessorAndSetAccessor.ts b/src/services/refactors/generateGetAccessorAndSetAccessor.ts index 86ca118d2c935..2756ae20471ed 100644 --- a/src/services/refactors/generateGetAccessorAndSetAccessor.ts +++ b/src/services/refactors/generateGetAccessorAndSetAccessor.ts @@ -61,5 +61,5 @@ registerRefactor(actionName, { } return emptyArray; - } + }, }); diff --git a/src/services/refactors/helpers.ts b/src/services/refactors/helpers.ts index acafb54f1e36a..ce50f672d23b8 100644 --- a/src/services/refactors/helpers.ts +++ b/src/services/refactors/helpers.ts @@ -1,4 +1,3 @@ - /** * Returned by refactor functions when some error message needs to be surfaced to users. * @@ -24,6 +23,6 @@ export function isRefactorErrorInfo(info: unknown): info is RefactorErrorInfo { * @internal */ export function refactorKindBeginsWith(known: string, requested: string | undefined): boolean { - if(!requested) return true; + if (!requested) return true; return known.substr(0, requested.length) === requested; } diff --git a/src/services/refactors/inferFunctionReturnType.ts b/src/services/refactors/inferFunctionReturnType.ts index 1e54133c1ff61..d4f4a5c871cfc 100644 --- a/src/services/refactors/inferFunctionReturnType.ts +++ b/src/services/refactors/inferFunctionReturnType.ts @@ -40,12 +40,12 @@ const refactorDescription = getLocaleSpecificMessage(Diagnostics.Infer_function_ const inferReturnTypeAction = { name: refactorName, description: refactorDescription, - kind: "refactor.rewrite.function.returnType" + kind: "refactor.rewrite.function.returnType", }; registerRefactor(refactorName, { kinds: [inferReturnTypeAction.kind], getEditsForAction: getRefactorEditsToInferReturnType, - getAvailableActions: getRefactorActionsToInferReturnType + getAvailableActions: getRefactorActionsToInferReturnType, }); function getRefactorEditsToInferReturnType(context: RefactorContext): RefactorEditInfo | undefined { @@ -64,14 +64,14 @@ function getRefactorActionsToInferReturnType(context: RefactorContext): readonly return [{ name: refactorName, description: refactorDescription, - actions: [inferReturnTypeAction] + actions: [inferReturnTypeAction], }]; } if (context.preferences.provideRefactorNotApplicableReason) { return [{ name: refactorName, description: refactorDescription, - actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }] + actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }], }]; } return emptyArray; diff --git a/src/services/refactors/inlineVariable.ts b/src/services/refactors/inlineVariable.ts index c5e8660462eba..3b9b94c062424 100644 --- a/src/services/refactors/inlineVariable.ts +++ b/src/services/refactors/inlineVariable.ts @@ -38,7 +38,10 @@ import { TypeChecker, VariableDeclaration, } from "../_namespaces/ts"; -import { RefactorErrorInfo, registerRefactor } from "../_namespaces/ts.refactor"; +import { + RefactorErrorInfo, + registerRefactor, +} from "../_namespaces/ts.refactor"; const refactorName = "Inline variable"; const refactorDescription = getLocaleSpecificMessage(Diagnostics.Inline_variable); @@ -46,7 +49,7 @@ const refactorDescription = getLocaleSpecificMessage(Diagnostics.Inline_variable const inlineVariableAction = { name: refactorName, description: refactorDescription, - kind: "refactor.inline.variable" + kind: "refactor.inline.variable", }; interface InliningInfo { @@ -64,7 +67,7 @@ registerRefactor(refactorName, { program, preferences, startPosition, - triggerReason + triggerReason, } = context; // tryWithReferenceToken is true below when triggerReason === "invoked", since we want to @@ -79,7 +82,7 @@ registerRefactor(refactorName, { return [{ name: refactorName, description: refactorDescription, - actions: [inlineVariableAction] + actions: [inlineVariableAction], }]; } @@ -89,8 +92,8 @@ registerRefactor(refactorName, { description: refactorDescription, actions: [{ ...inlineVariableAction, - notApplicableReason: info.error - }] + notApplicableReason: info.error, + }], }]; } @@ -118,7 +121,7 @@ registerRefactor(refactorName, { }); return { edits }; - } + }, }); function getInliningInfo(file: SourceFile, startPosition: number, tryWithReferenceToken: boolean, program: Program): InliningInfo | RefactorErrorInfo | undefined { diff --git a/src/services/refactors/moveToFile.ts b/src/services/refactors/moveToFile.ts index b0b02a3484278..352c9043b40f4 100644 --- a/src/services/refactors/moveToFile.ts +++ b/src/services/refactors/moveToFile.ts @@ -1,4 +1,6 @@ -import { getModuleSpecifier } from "../../compiler/moduleSpecifiers"; +import { + getModuleSpecifier, +} from "../../compiler/moduleSpecifiers"; import { __String, AnyImportOrRequireStatement, @@ -142,7 +144,9 @@ import { VariableDeclarationList, VariableStatement, } from "../_namespaces/ts"; -import { registerRefactor } from "../refactorProvider"; +import { + registerRefactor, +} from "../refactorProvider"; const refactorNameForMoveToFile = "Move to file"; const description = getLocaleSpecificMessage(Diagnostics.Move_to_file); @@ -163,9 +167,7 @@ registerRefactor(refactorNameForMoveToFile, { return [{ name: refactorNameForMoveToFile, description, actions: [moveToFileAction] }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [{ name: refactorNameForMoveToFile, description, actions: - [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] - }]; + return [{ name: refactorNameForMoveToFile, description, actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; } return emptyArray; }, @@ -183,7 +185,7 @@ registerRefactor(refactorNameForMoveToFile, { return { edits, renameFilename: undefined, renameLocation: undefined }; } return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid)); - } + }, }); function error(notApplicableReason: string) { @@ -193,7 +195,7 @@ function error(notApplicableReason: string) { function doChange(context: RefactorContext, oldFile: SourceFile, targetFile: string, program: Program, toMove: ToMove, changes: textChanges.ChangeTracker, host: LanguageServiceHost, preferences: UserPreferences): void { const checker = program.getTypeChecker(); const usage = getUsageInfo(oldFile, toMove.all, checker); - //For a new file + // For a new file if (!host.fileExists(targetFile)) { changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile(oldFile, targetFile, usage, changes, toMove, program, host, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host)); @@ -214,7 +216,7 @@ function getNewStatementsAndRemoveFromOldFile( program: Program, host: LanguageServiceHost, preferences: UserPreferences, - importAdder?: codefix.ImportAdder + importAdder?: codefix.ImportAdder, ) { const checker = program.getTypeChecker(); const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); @@ -223,7 +225,7 @@ function getNewStatementsAndRemoveFromOldFile( return [...prologueDirectives, ...toMove.all]; } - //If the targetFile is a string, it’s the file name for a new file, if it’s a SourceFile, it’s the existing target file. + // If the targetFile is a string, it’s the file name for a new file, if it’s a SourceFile, it’s the existing target file. const targetFileName = typeof targetFile === "string" ? targetFile : targetFile.fileName; const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFileName, program, host, !!oldFile.commonJsModuleIndicator); @@ -258,7 +260,7 @@ function getNewStatementsAndRemoveFromOldFile( ...prologueDirectives, ...imports, SyntaxKind.NewLineTrivia as const, - ...body + ...body, ]; } @@ -321,7 +323,7 @@ function getTargetFileImportsAndAddExportInOldFile( } } - //Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. const targetFileSourceFile = program.getSourceFile(targetFile); let oldFileDefault: Identifier | undefined; const oldFileNamedImports: string[] = []; @@ -352,7 +354,7 @@ function getTargetFileImportsAndAddExportInOldFile( } } }); - return (targetFileSourceFile) + return targetFileSourceFile ? append(copiedOldImports, makeImportOrRequire(targetFileSourceFile, oldFileDefault, oldFileNamedImports, oldFile.fileName, program, host, useEsModuleSyntax, quotePreference)) : append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, oldFile.fileName, program, host, useEsModuleSyntax, quotePreference)); } @@ -366,8 +368,7 @@ export function addNewFileToTsconfig(program: Program, changes: textChanges.Chan const newFilePath = getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); const cfgObject = cfg.statements[0] && tryCast(cfg.statements[0].expression, isObjectLiteralExpression); - const filesProp = cfgObject && find(cfgObject.properties, (prop): prop is PropertyAssignment => - isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files"); + const filesProp = cfgObject && find(cfgObject.properties, (prop): prop is PropertyAssignment => isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files"); if (filesProp && isArrayLiteralExpression(filesProp.initializer)) { changes.insertNodeInListAfter(cfg, last(filesProp.initializer.elements), factory.createStringLiteral(newFilePath), filesProp.initializer.elements); } @@ -390,7 +391,13 @@ export function deleteUnusedOldImports(oldFile: SourceFile, toMove: readonly Sta /** @internal */ export function updateImportsInOtherFiles( - changes: textChanges.ChangeTracker, program: Program, host: LanguageServiceHost, oldFile: SourceFile, movedSymbols: Set, targetFileName: string, quotePreference: QuotePreference + changes: textChanges.ChangeTracker, + program: Program, + host: LanguageServiceHost, + oldFile: SourceFile, + movedSymbols: Set, + targetFileName: string, + quotePreference: QuotePreference, ): void { const checker = program.getTypeChecker(); for (const sourceFile of program.getSourceFiles()) { @@ -441,7 +448,7 @@ function updateNamespaceLikeImport( newModuleSpecifier: string, oldImportId: Identifier, oldImportNode: SupportedImport, - quotePreference: QuotePreference + quotePreference: QuotePreference, ): void { const preferredNewNamespaceName = codefix.moduleSpecifierToValidIdentifier(newModuleSpecifier, ScriptTarget.ESNext); let needUniqueName = false; @@ -472,7 +479,8 @@ function updateNamespaceLikeImportNode(node: SupportedImport, newNamespaceName: /*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, factory.createNamespaceImport(newNamespaceId)), newModuleString, - /*assertClause*/ undefined); + /*assertClause*/ undefined, + ); case SyntaxKind.ImportEqualsDeclaration: return factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, newNamespaceId, factory.createExternalModuleReference(newModuleString)); case SyntaxKind.VariableDeclaration: @@ -514,9 +522,9 @@ export function forEachImportInStatement(statement: Statement, cb: (importNode: /** @internal */ export type SupportedImport = - | ImportDeclaration & { moduleSpecifier: StringLiteralLike } - | ImportEqualsDeclaration & { moduleReference: ExternalModuleReference & { expression: StringLiteralLike } } - | VariableDeclaration & { initializer: RequireOrImportCall }; + | ImportDeclaration & { moduleSpecifier: StringLiteralLike; } + | ImportEqualsDeclaration & { moduleReference: ExternalModuleReference & { expression: StringLiteralLike; }; } + | VariableDeclaration & { initializer: RequireOrImportCall; }; /** @internal */ export type SupportedImportStatement = @@ -532,7 +540,7 @@ export function createOldFileImportsFromTargetFile( program: Program, host: LanguageServiceHost, useEs6Imports: boolean, - quotePreference: QuotePreference + quotePreference: QuotePreference, ): AnyImportOrRequireStatement | undefined { let defaultImport: Identifier | undefined; const imports: string[] = []; @@ -556,7 +564,7 @@ export function makeImportOrRequire( program: Program, host: LanguageServiceHost, useEs6Imports: boolean, - quotePreference: QuotePreference + quotePreference: QuotePreference, ): AnyImportOrRequireStatement | undefined { const pathToTargetFile = resolvePath(getDirectoryPath(sourceFile.path), targetFileNameWithExtension); const pathToTargetFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFile, createModuleSpecifierResolutionHost(program, host)); @@ -581,9 +589,11 @@ function makeVariableStatement(name: BindingName, type: TypeNode | undefined, in /** @internal */ export function addExports(sourceFile: SourceFile, toMove: readonly Statement[], needExport: Set, useEs6Exports: boolean): readonly Statement[] { return flatMap(toMove, statement => { - if (isTopLevelDeclarationStatement(statement) && + if ( + isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && - forEachTopLevelDeclaration(statement, d => needExport.has(Debug.checkDefined(tryCast(d, canHaveSymbol)?.symbol)))) { + forEachTopLevelDeclaration(statement, d => needExport.has(Debug.checkDefined(tryCast(d, canHaveSymbol)?.symbol))) + ) { const exports = addExport(getSynthesizedDeepClone(statement), useEs6Exports); if (exports) return exports; } @@ -636,7 +646,7 @@ function deleteUnusedImportsInDeclaration(sourceFile: SourceFile, importDecl: Im changes.replaceNode( sourceFile, importDecl.importClause, - factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ undefined) + factory.updateImportClause(importDecl.importClause, importDecl.importClause.isTypeOnly, name, /*namedBindings*/ undefined), ); } else if (namedBindings.kind === SyntaxKind.NamedImports) { @@ -654,8 +664,7 @@ function deleteUnusedImportsInVariableDeclaration(sourceFile: SourceFile, varDec case SyntaxKind.Identifier: if (isUnused(name)) { if (varDecl.initializer && isRequireCall(varDecl.initializer, /*requireStringLiteralLikeArgument*/ true)) { - changes.delete(sourceFile, - isVariableDeclarationList(varDecl.parent) && length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); + changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); } else { changes.delete(sourceFile, name); @@ -666,8 +675,7 @@ function deleteUnusedImportsInVariableDeclaration(sourceFile: SourceFile, varDec break; case SyntaxKind.ObjectBindingPattern: if (name.elements.every(e => isIdentifier(e.name) && isUnused(e.name))) { - changes.delete(sourceFile, - isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); } else { for (const element of name.elements) { @@ -729,7 +737,9 @@ function createExportAssignment(name: string): Statement { factory.createBinaryExpression( factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), SyntaxKind.EqualsToken, - factory.createIdentifier(name))); + factory.createIdentifier(name), + ), + ); } function getNamesToExportInCommonJS(decl: TopLevelDeclarationStatement): readonly string[] { @@ -812,7 +822,8 @@ export function getTopLevelDeclarationStatement(d: TopLevelDeclaration): TopLeve return d.parent.parent; case SyntaxKind.BindingElement: return getTopLevelDeclarationStatement( - cast(d.parent.parent, (p): p is TopLevelVariableDeclaration | BindingElement => isVariableDeclaration(p) || isBindingElement(p))); + cast(d.parent.parent, (p): p is TopLevelVariableDeclaration | BindingElement => isVariableDeclaration(p) || isBindingElement(p)), + ); default: return d; } @@ -858,7 +869,7 @@ export interface UsageInfo { } /** @internal */ -export type TopLevelExpressionStatement = ExpressionStatement & { expression: BinaryExpression & { left: PropertyAccessExpression } }; // 'exports.x = ...' +export type TopLevelExpressionStatement = ExpressionStatement & { expression: BinaryExpression & { left: PropertyAccessExpression; }; }; // 'exports.x = ...' /** @internal */ export type NonVariableTopLevelDeclaration = @@ -871,8 +882,10 @@ export type NonVariableTopLevelDeclaration = | TopLevelExpressionStatement | ImportEqualsDeclaration; - /** @internal */ -export interface TopLevelVariableDeclaration extends VariableDeclaration { parent: VariableDeclarationList & { parent: VariableStatement; }; } +/** @internal */ +export interface TopLevelVariableDeclaration extends VariableDeclaration { + parent: VariableDeclarationList & { parent: VariableStatement; }; +} /** @internal */ export type TopLevelDeclaration = NonVariableTopLevelDeclaration | TopLevelVariableDeclaration | BindingElement; @@ -887,23 +900,28 @@ export function createNewFileName(oldFile: SourceFile, program: Program, context const currentDirectory = getDirectoryPath(oldFile.fileName); const extension = extensionFromPath(oldFile.fileName); const newFileName = combinePaths( - // new file is always placed in the same directory as the old file - currentDirectory, - // ensures the filename computed below isn't already taken - makeUniqueFilename( - // infers a name for the new file from the symbols being moved - inferNewFileName(usage.oldFileImportsFromTargetFile, usage.movedSymbols), - extension, + // new file is always placed in the same directory as the old file currentDirectory, - host)) - // new file has same extension as old file - + extension; - return newFileName; + // ensures the filename computed below isn't already taken + makeUniqueFilename( + // infers a name for the new file from the symbols being moved + inferNewFileName(usage.oldFileImportsFromTargetFile, usage.movedSymbols), + extension, + currentDirectory, + host, + ), + ) + // new file has same extension as old file + + extension; + return newFileName; } return ""; } -interface RangeToMove { readonly toMove: readonly Statement[]; readonly afterLast: Statement | undefined; } +interface RangeToMove { + readonly toMove: readonly Statement[]; + readonly afterLast: Statement | undefined; +} function getRangeToMove(context: RefactorContext): RangeToMove | undefined { const { file } = context; @@ -936,7 +954,7 @@ function getRangeToMove(context: RefactorContext): RangeToMove | undefined { return { toMove: statements.slice(startNodeIndex, endNodeIndex === -1 ? statements.length : endNodeIndex + 1), - afterLast: endNodeIndex === -1 ? undefined : statements[endNodeIndex + 1] + afterLast: endNodeIndex === -1 ? undefined : statements[endNodeIndex + 1], }; } @@ -1045,7 +1063,7 @@ export function getUsageInfo(oldFile: SourceFile, toMove: readonly Statement[], function makeUniqueFilename(proposedFilename: string, extension: string, inDirectory: string, host: LanguageServiceHost): string { let newFilename = proposedFilename; - for (let i = 1; ; i++) { + for (let i = 1;; i++) { const name = combinePaths(inDirectory, newFilename + extension); if (!host.fileExists(name)) return newFilename; newFilename = `${proposedFilename}.${i}`; @@ -1162,8 +1180,7 @@ function moveStatementsToTargetFile(changes: textChanges.ChangeTracker, program: isExportDeclaration(d) ? d : isExportSpecifier(d) ? tryCast(d.parent.parent, isExportDeclaration) : undefined); if (exportDeclaration && exportDeclaration.moduleSpecifier) { - targetToSourceExports.set(exportDeclaration, - (targetToSourceExports.get(exportDeclaration) || new Set()).add(declaration)); + targetToSourceExports.set(exportDeclaration, (targetToSourceExports.get(exportDeclaration) || new Set()).add(declaration)); } }); } @@ -1172,8 +1189,7 @@ function moveStatementsToTargetFile(changes: textChanges.ChangeTracker, program: for (const [exportDeclaration, topLevelDeclarations] of arrayFrom(targetToSourceExports)) { if (exportDeclaration.exportClause && isNamedExports(exportDeclaration.exportClause) && length(exportDeclaration.exportClause.elements)) { const elements = exportDeclaration.exportClause.elements; - const updatedElements = filter(elements, elem => - find(skipAlias(elem.symbol, checker).declarations, d => isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === undefined); + const updatedElements = filter(elements, elem => find(skipAlias(elem.symbol, checker).declarations, d => isTopLevelDeclaration(d) && topLevelDeclarations.has(d)) === undefined); if (length(updatedElements) === 0) { changes.deleteNode(targetFile, exportDeclaration); @@ -1182,16 +1198,13 @@ function moveStatementsToTargetFile(changes: textChanges.ChangeTracker, program: } if (length(updatedElements) < length(elements)) { - changes.replaceNode(targetFile, exportDeclaration, - factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, exportDeclaration.isTypeOnly, - factory.updateNamedExports(exportDeclaration.exportClause , factory.createNodeArray(updatedElements, elements.hasTrailingComma)), exportDeclaration.moduleSpecifier, exportDeclaration.assertClause)); + changes.replaceNode(targetFile, exportDeclaration, factory.updateExportDeclaration(exportDeclaration, exportDeclaration.modifiers, exportDeclaration.isTypeOnly, factory.updateNamedExports(exportDeclaration.exportClause, factory.createNodeArray(updatedElements, elements.hasTrailingComma)), exportDeclaration.moduleSpecifier, exportDeclaration.assertClause)); } } } } - const lastReExport = findLast(targetFile.statements, n => - isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n)); + const lastReExport = findLast(targetFile.statements, n => isExportDeclaration(n) && !!n.moduleSpecifier && !removedExports.has(n)); if (lastReExport) { changes.insertNodesBefore(targetFile, lastReExport, statements, /*blankLineBetween*/ true); } diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 10183ad20acc4..275ed16bd5a9d 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -49,7 +49,7 @@ import { SupportedImportStatement, ToMove, updateImportsInOtherFiles, - UsageInfo + UsageInfo, } from "../_namespaces/ts.refactor"; const refactorName = "Move to a new file"; @@ -68,9 +68,7 @@ registerRefactor(refactorName, { return [{ name: refactorName, description, actions: [moveToNewFileAction] }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [{ name: refactorName, description, actions: - [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] - }]; + return [{ name: refactorName, description, actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; } return emptyArray; }, @@ -79,7 +77,7 @@ registerRefactor(refactorName, { const statements = Debug.checkDefined(getStatementsToMove(context)); const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program, statements, t, context.host, context.preferences, context)); return { edits, renameFilename: undefined, renameLocation: undefined }; - } + }, }); function doChange(oldFile: SourceFile, program: Program, toMove: ToMove, changes: textChanges.ChangeTracker, host: LanguageServiceHost, preferences: UserPreferences, context: RefactorContext): void { @@ -95,7 +93,14 @@ function doChange(oldFile: SourceFile, program: Program, toMove: ToMove, changes } function getNewStatementsAndRemoveFromOldFile( - oldFile: SourceFile, usage: UsageInfo, changes: textChanges.ChangeTracker, toMove: ToMove, program: Program, host: LanguageServiceHost, newFilename: string, preferences: UserPreferences, + oldFile: SourceFile, + usage: UsageInfo, + changes: textChanges.ChangeTracker, + toMove: ToMove, + program: Program, + host: LanguageServiceHost, + newFilename: string, + preferences: UserPreferences, ) { const checker = program.getTypeChecker(); const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); @@ -122,7 +127,7 @@ function getNewStatementsAndRemoveFromOldFile( ...prologueDirectives, ...imports, SyntaxKind.NewLineTrivia as const, - ...body + ...body, ]; } diff --git a/src/services/rename.ts b/src/services/rename.ts index 094e22b15a0f9..4083612dae428 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -70,14 +70,17 @@ function getRenameInfoForNode( typeChecker: TypeChecker, sourceFile: SourceFile, program: Program, - preferences: UserPreferences): RenameInfo | undefined { + preferences: UserPreferences, +): RenameInfo | undefined { const symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) { if (isStringLiteralLike(node)) { const type = getContextualTypeFromParentOrAncestorTypeNode(node, typeChecker); - if (type && ((type.flags & TypeFlags.StringLiteral) || ( - (type.flags & TypeFlags.Union) && every((type as UnionType).types, type => !!(type.flags & TypeFlags.StringLiteral)) - ))) { + if ( + type && ((type.flags & TypeFlags.StringLiteral) || ( + (type.flags & TypeFlags.Union) && every((type as UnionType).types, type => !!(type.flags & TypeFlags.StringLiteral)) + )) + ) { return getRenameInfoSuccess(node.text, node.text, ScriptElementKind.string, "", node, sourceFile); } } @@ -117,7 +120,7 @@ function getRenameInfoForNode( : undefined; const displayName = specifierName || typeChecker.symbolToString(symbol); const fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); - return getRenameInfoSuccess(displayName, fullDisplayName, kind, SymbolDisplay.getSymbolModifiers(typeChecker,symbol), node, sourceFile); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, SymbolDisplay.getSymbolModifiers(typeChecker, symbol), node, sourceFile); } function isDefinedInLibraryFile(program: Program, declaration: Node) { @@ -129,7 +132,7 @@ function wouldRenameInOtherNodeModules( originalFile: SourceFile, symbol: Symbol, checker: TypeChecker, - preferences: UserPreferences + preferences: UserPreferences, ): DiagnosticMessage | undefined { if (!preferences.providePrefixAndSuffixTextForRename && symbol.flags & SymbolFlags.Alias) { const importSpecifier = symbol.declarations && find(symbol.declarations, decl => isImportSpecifier(decl)); @@ -206,7 +209,7 @@ function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind displayName, fullDisplayName, kindModifiers, - triggerSpan: createTriggerSpanForNode(node, sourceFile) + triggerSpan: createTriggerSpanForNode(node, sourceFile), }; } diff --git a/src/services/services.ts b/src/services/services.ts index b0e56cc06453f..efb12ce4b7759 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -325,7 +325,9 @@ import { } from "./_namespaces/ts"; import * as NavigateTo from "./_namespaces/ts.NavigateTo"; import * as NavigationBar from "./_namespaces/ts.NavigationBar"; -import { createNewFileName } from "./_namespaces/ts.refactor"; +import { + createNewFileName, +} from "./_namespaces/ts.refactor"; import * as classifier from "./classifier"; import * as classifier2020 from "./classifier2020"; @@ -335,8 +337,8 @@ export const servicesVersion = "0.8"; function createNode(kind: TKind, pos: number, end: number, parent: Node): NodeObject | TokenObject | IdentifierObject | PrivateIdentifierObject { const node = isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === SyntaxKind.Identifier ? new IdentifierObject(SyntaxKind.Identifier, pos, end) : - kind === SyntaxKind.PrivateIdentifier ? new PrivateIdentifierObject(SyntaxKind.PrivateIdentifier, pos, end) : - new TokenObject(kind, pos, end); + kind === SyntaxKind.PrivateIdentifier ? new PrivateIdentifierObject(SyntaxKind.PrivateIdentifier, pos, end) : + new TokenObject(kind, pos, end); node.parent = parent; node.flags = parent.flags & NodeFlags.ContextFlags; return node; @@ -752,7 +754,7 @@ class IdentifierObject extends TokenOrIdentifierObject implements Identifier { declare _declarationBrand: any; declare _jsdocContainerBrand: any; declare _flowContainerBrand: any; - /** @internal */typeArguments!: NodeArray; + /** @internal */ typeArguments!: NodeArray; constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) { super(pos, end); } @@ -1016,7 +1018,7 @@ class SourceFileObject extends NodeObject implements SourceFile { public statements!: NodeArray; public endOfFileToken!: Token; - public amdDependencies!: { name: string; path: string }[]; + public amdDependencies!: { name: string; path: string; }[]; public moduleName!: string; public referencedFiles!: FileReference[]; public typeReferenceDirectives!: FileReference[]; @@ -1250,7 +1252,7 @@ class SourceFileObject extends NodeObject implements SourceFile { class SourceMapSourceObject implements SourceMapSource { lineMap!: number[]; - constructor(public fileName: string, public text: string, public skipTrivia?: (pos: number) => number) { } + constructor(public fileName: string, public text: string, public skipTrivia?: (pos: number) => number) {} public getLineAndCharacterOfPosition(pos: number): LineAndCharacter { return getLineAndCharacterOfPosition(this, pos); @@ -1319,7 +1321,7 @@ export function getDefaultCompilerOptions(): CompilerOptions { // Always default to "ScriptTarget.ES5" for the language service return { target: ScriptTarget.ES5, - jsx: JsxEmit.Preserve + jsx: JsxEmit.Preserve, }; } @@ -1357,9 +1359,9 @@ class SyntaxTreeCache { toPath(fileName, this.host.getCurrentDirectory(), this.host.getCompilerHost?.()?.getCanonicalFileName || hostGetCanonicalFileName(this.host)), this.host.getCompilerHost?.()?.getModuleResolutionCache?.()?.getPackageJsonInfoCache(), this.host, - this.host.getCompilationSettings() + this.host.getCompilationSettings(), ), - setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings()) + setExternalModuleIndicator: getSetExternalModuleIndicator(this.host.getCompilationSettings()), }; sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, options, version, /*setNodeParents*/ true, scriptKind); } @@ -1420,8 +1422,8 @@ export function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSn newText = prefix && suffix ? prefix + changedText + suffix : prefix - ? (prefix + changedText) - : (changedText + suffix); + ? (prefix + changedText) + : (changedText + suffix); } const newSourceFile = updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); @@ -1595,7 +1597,7 @@ export function createLanguageService( readFile: maybeBind(host, host.readFile), getDocumentPositionMapper: maybeBind(host, host.getDocumentPositionMapper), getSourceFileLike: maybeBind(host, host.getSourceFileLike), - log + log, }); function getValidSourceFile(fileName: string): SourceFile { @@ -1693,7 +1695,7 @@ export function createLanguageService( const { getSourceFileWithCache } = changeCompilerHostLikeToUseCache( compilerHost, fileName => toPath(fileName, currentDirectory, getCanonicalFileName), - (...args) => originalGetSourceFile.call(compilerHost, ...args) + (...args) => originalGetSourceFile.call(compilerHost, ...args), ); compilerHost.getSourceFile = getSourceFileWithCache!; @@ -1737,7 +1739,7 @@ export function createLanguageService( options: newSettings, host: compilerHost, oldProgram: program, - projectReferences + projectReferences, }; program = createProgram(options); @@ -1943,8 +1945,7 @@ export function createLanguageService( if (program) { // Use paths to ensure we are using correct key and paths as document registry could be created with different current directory than host const key = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); - forEach(program.getSourceFiles(), f => - documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind, f.impliedNodeFormat)); + forEach(program.getSourceFiles(), f => documentRegistry.releaseDocumentWithKey(f.resolvedPath, key, f.scriptKind, f.impliedNodeFormat)); program = undefined!; // TODO: GH#18217 } } @@ -2012,7 +2013,8 @@ export function createLanguageService( options.triggerKind, cancellationToken, formattingSettings && formatting.getFormatContext(formattingSettings, host), - options.includeSymbol); + options.includeSymbol, + ); } function getCompletionEntryDetails(fileName: string, position: number, name: string, formattingOptions: FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences = emptyOptions, data?: CompletionEntryData): CompletionEntryDetails | undefined { @@ -2057,13 +2059,11 @@ export function createLanguageService( textSpan: createTextSpanFromNode(nodeForQuickInfo, sourceFile), displayParts: typeChecker.runWithCancellationToken(cancellationToken, typeChecker => typeToDisplayParts(typeChecker, type, getContainerNode(nodeForQuickInfo))), documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : undefined + tags: type.symbol ? type.symbol.getJsDocTags(typeChecker) : undefined, }; } - const { symbolKind, displayParts, documentation, tags } = typeChecker.runWithCancellationToken(cancellationToken, typeChecker => - SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo) - ); + const { symbolKind, displayParts, documentation, tags } = typeChecker.runWithCancellationToken(cancellationToken, typeChecker => SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, getContainerNode(nodeForQuickInfo), nodeForQuickInfo)); return { kind: symbolKind, kindModifiers: SymbolDisplay.getSymbolModifiers(typeChecker, symbol), @@ -2156,15 +2156,14 @@ export function createLanguageService( return { fileName: sourceFile.fileName, textSpan, - ...FindAllReferences.toContextSpan(textSpan, sourceFile, node.parent) + ...FindAllReferences.toContextSpan(textSpan, sourceFile, node.parent), }; }); } else { const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions); const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences?.providePrefixAndSuffixTextForRename; - return getReferencesWorker(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: FindAllReferences.FindReferencesUse.Rename }, - (entry, originalNode, checker) => FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)); + return getReferencesWorker(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: FindAllReferences.FindReferencesUse.Rename }, (entry, originalNode, checker) => FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)); } } @@ -2263,8 +2262,10 @@ export function createLanguageService( // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === SyntaxKind.ModuleDeclaration && - (nodeForStartPos.parent.parent as ModuleDeclaration).body === nodeForStartPos.parent) { + if ( + nodeForStartPos.parent.parent.kind === SyntaxKind.ModuleDeclaration && + (nodeForStartPos.parent.parent as ModuleDeclaration).body === nodeForStartPos.parent + ) { // Use parent module declarations name for start pos nodeForStartPos = (nodeForStartPos.parent.parent as ModuleDeclaration).name; } @@ -2534,13 +2535,12 @@ export function createLanguageService( } else { // determines if the cursor is in an element tag - const tag = findAncestor(token.parent, - n => { - if (isJsxOpeningElement(n) || isJsxClosingElement(n)) { - return true; - } - return false; - }); + const tag = findAncestor(token.parent, n => { + if (isJsxOpeningElement(n) || isJsxClosingElement(n)) { + return true; + } + return false; + }); if (!tag) return undefined; Debug.assert(isJsxOpeningElement(tag) || isJsxClosingElement(tag), "tag should be opening or closing element"); @@ -2570,7 +2570,7 @@ export function createLanguageService( return { lineStarts: sourceFile.getLineStarts(), firstLine: sourceFile.getLineAndCharacterOfPosition(textRange.pos).line, - lastLine: sourceFile.getLineAndCharacterOfPosition(textRange.end).line + lastLine: sourceFile.getLineAndCharacterOfPosition(textRange.end).line, }; } @@ -2621,8 +2621,8 @@ export function createLanguageService( newText: openComment, span: { length: 0, - start: lineStarts[i] + leftMostPosition - } + start: lineStarts[i] + leftMostPosition, + }, }); } else if (sourceFile.text.substr(lineStarts[i] + lineTextStart, openComment.length) === openComment) { @@ -2630,8 +2630,8 @@ export function createLanguageService( newText: "", span: { length: openComment.length, - start: lineStarts[i] + lineTextStart - } + start: lineStarts[i] + lineTextStart, + }, }); } } @@ -2704,8 +2704,8 @@ export function createLanguageService( newText: openMultiline, span: { length: 0, - start: firstPos - } + start: firstPos, + }, }); } @@ -2716,8 +2716,8 @@ export function createLanguageService( newText: closeMultiline, span: { length: 0, - start: positions[i] - } + start: positions[i], + }, }); } @@ -2726,8 +2726,8 @@ export function createLanguageService( newText: openMultiline, span: { length: 0, - start: positions[i] - } + start: positions[i], + }, }); } } @@ -2738,8 +2738,8 @@ export function createLanguageService( newText: closeMultiline, span: { length: 0, - start: positions[positions.length - 1] - } + start: positions[positions.length - 1], + }, }); } } @@ -2752,8 +2752,8 @@ export function createLanguageService( newText: "", span: { length: openMultiline.length, - start: pos - offset - } + start: pos - offset, + }, }); } } @@ -2980,7 +2980,7 @@ export function createLanguageService( cancellationToken, preferences, triggerReason, - kind + kind, }; } @@ -3005,12 +3005,13 @@ export function createLanguageService( return refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind), includeInteractiveActions); } - function getMoveToRefactoringFileSuggestions(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences = emptyOptions): { newFileName: string, files: string[] } { + function getMoveToRefactoringFileSuggestions(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences = emptyOptions): { newFileName: string; files: string[]; } { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const allFiles = Debug.checkDefined(program.getSourceFiles()); const extension = extensionFromPath(fileName); - const files = mapDefined(allFiles, file => !program?.isSourceFileFromExternalLibrary(sourceFile) && + const files = mapDefined(allFiles, file => + !program?.isSourceFileFromExternalLibrary(sourceFile) && !(sourceFile === getValidSourceFile(file.fileName) || extension === Extension.Ts && extensionFromPath(file.fileName) === Extension.Dts || extension === Extension.Dts && startsWith(getBaseFileName(file.fileName), "lib.") && extensionFromPath(file.fileName) === Extension.Dts) && extension === extensionFromPath(file.fileName) ? file.fileName : undefined); @@ -3232,14 +3233,14 @@ function getContainingObjectLiteralElementWorker(node: Node): ObjectLiteralEleme case SyntaxKind.Identifier: return isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === SyntaxKind.ObjectLiteralExpression || node.parent.parent.kind === SyntaxKind.JsxAttributes) && - node.parent.name === node ? node.parent : undefined; + (node.parent.parent.kind === SyntaxKind.ObjectLiteralExpression || node.parent.parent.kind === SyntaxKind.JsxAttributes) && + node.parent.name === node ? node.parent : undefined; } return undefined; } /** @internal */ -export type ObjectLiteralElementWithName = ObjectLiteralElement & { name: PropertyName; parent: ObjectLiteralExpression | JsxAttributes }; +export type ObjectLiteralElementWithName = ObjectLiteralElement & { name: PropertyName; parent: ObjectLiteralExpression | JsxAttributes; }; function getSymbolAtLocationForQuickInfo(node: Node, checker: TypeChecker): Symbol | undefined { const object = getContainingObjectLiteralElement(node); @@ -3266,7 +3267,7 @@ export function getPropertySymbolsFromContextualType(node: ObjectLiteralElementW return symbol ? [symbol] : emptyArray; } - const discriminatedPropertySymbols = mapDefined(contextualType.types, t => (isObjectLiteralExpression(node.parent)|| isJsxAttributes(node.parent)) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name)); + const discriminatedPropertySymbols = mapDefined(contextualType.types, t => (isObjectLiteralExpression(node.parent) || isJsxAttributes(node.parent)) && checker.isTypeInvalidDueToUnionDiscriminant(t, node.parent) ? undefined : t.getProperty(name)); if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { const symbol = contextualType.getProperty(name); if (symbol) return [symbol]; diff --git a/src/services/shims.ts b/src/services/shims.ts index 1c3bdae55e9f0..1fe06d9e1fbf5 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -83,13 +83,14 @@ import { // /** @internal */ -let debugObjectHost: { CollectGarbage(): void } = (function (this: any) { // eslint-disable-line prefer-const +let debugObjectHost: { CollectGarbage(): void; } = (function (this: any) { // eslint-disable-line prefer-const return this; })(); // We need to use 'null' to interface with the managed side. /* eslint-disable local/no-in-operator */ +// dprint-ignore interface DiscoverTypingsInfo { fileNames: string[]; // The file names that belong to the same project. projectRootPath: string; // The path to the project root directory @@ -236,7 +237,7 @@ export interface LanguageServiceShim extends Shim { getEncodedSemanticClassifications(fileName: string, start: number, length: number, format?: SemanticClassificationFormat): string; getCompletionsAtPosition(fileName: string, position: number, preferences: UserPreferences | undefined, formattingSettings: FormatCodeSettings | undefined): string; - getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): string; + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string /*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined): string; getQuickInfoAtPosition(fileName: string, position: number): string; @@ -333,11 +334,11 @@ export interface LanguageServiceShim extends Shim { getTodoComments(fileName: string, todoCommentDescriptors: string): string; getBraceMatchingAtPosition(fileName: string, position: number): string; - getIndentationAtPosition(fileName: string, position: number, options: string/*Services.EditorOptions*/): string; + getIndentationAtPosition(fileName: string, position: number, options: string /*Services.EditorOptions*/): string; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string; - getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: string /*Services.FormatCodeOptions*/): string; + getFormattingEditsForDocument(fileName: string, options: string /*Services.FormatCodeOptions*/): string; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string /*Services.FormatCodeOptions*/): string; /** * Returns JSON-encoded value of the type TextInsertion. @@ -413,7 +414,9 @@ class ScriptSnapshotShimAdapter implements IScriptSnapshot { const decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded!); // TODO: GH#18217 return createTextChangeRange( - createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + createTextSpan(decoded.span.start, decoded.span.length), + decoded.newLength, + ); } public dispose(): void { @@ -563,8 +566,7 @@ export class LanguageServiceShimHostAdapter implements LanguageServiceHost { } public readDirectory(path: string, extensions?: readonly string[], exclude?: string[], include?: string[], depth?: number): string[] { - const pattern = getFileMatcherPatterns(path, exclude, include, - this.shimHost.useCaseSensitiveFileNames!(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + const pattern = getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames!(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory( path, JSON.stringify(extensions), @@ -572,7 +574,7 @@ export class LanguageServiceShimHostAdapter implements LanguageServiceHost { pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, - depth + depth, )); } @@ -587,7 +589,6 @@ export class LanguageServiceShimHostAdapter implements LanguageServiceHost { /** @internal */ export class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost, JsTyping.TypingResolutionHost { - public directoryExists: (directoryName: string) => boolean; public realpath: (path: string) => string; public useCaseSensitiveFileNames: boolean; @@ -609,8 +610,7 @@ export class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResol } public readDirectory(rootDir: string, extensions: readonly string[], exclude: readonly string[], include: readonly string[], depth?: number): string[] { - const pattern = getFileMatcherPatterns(rootDir, exclude, include, - this.shimHost.useCaseSensitiveFileNames!(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 + const pattern = getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames!(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory( rootDir, JSON.stringify(extensions), @@ -618,7 +618,7 @@ export class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResol pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, - depth + depth, )); } @@ -678,7 +678,6 @@ function forwardCall(logger: Logger, actionDescription: string, returnJson: b } } - class ShimBase implements Shim { constructor(private factory: ShimFactory) { factory.registerShim(this); @@ -711,7 +710,7 @@ function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): RealizedDia category: diagnosticCategoryName(diagnostic), code: diagnostic.code, reportsUnnecessary: diagnostic.reportsUnnecessary, - reportsDeprecated: diagnostic.reportsDeprecated + reportsDeprecated: diagnostic.reportsDeprecated, }; } @@ -719,9 +718,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim private logger: Logger; private logPerformance = false; - constructor(factory: ShimFactory, - private host: LanguageServiceShimHost, - public languageService: LanguageService) { + constructor(factory: ShimFactory, private host: LanguageServiceShimHost, public languageService: LanguageService) { super(factory); this.logger = this.host; } @@ -760,7 +757,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public refresh(throwOnError: boolean): void { this.forwardJSONCall( `refresh(${throwOnError})`, - () => null // eslint-disable-line no-null/no-null + () => null, // eslint-disable-line no-null/no-null ); } @@ -770,7 +767,8 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim () => { this.languageService.cleanupSemanticCache(); return null; // eslint-disable-line no-null/no-null - }); + }, + ); } private realizeDiagnostics(diagnostics: readonly Diagnostic[]): { message: string; start: number; length: number; category: string; }[] { @@ -781,14 +779,14 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getSyntacticClassifications(fileName: string, start: number, length: number): string { return this.forwardJSONCall( `getSyntacticClassifications('${fileName}', ${start}, ${length})`, - () => this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length)) + () => this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length)), ); } public getSemanticClassifications(fileName: string, start: number, length: number): string { return this.forwardJSONCall( `getSemanticClassifications('${fileName}', ${start}, ${length})`, - () => this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length)) + () => this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length)), ); } @@ -797,7 +795,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim `getEncodedSyntacticClassifications('${fileName}', ${start}, ${length})`, // directly serialize the spans out to a string. This is much faster to decode // on the managed side versus a full JSON array. - () => convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length))) + () => convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length))), ); } @@ -806,7 +804,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim `getEncodedSemanticClassifications('${fileName}', ${start}, ${length})`, // directly serialize the spans out to a string. This is much faster to decode // on the managed side versus a full JSON array. - () => convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length))) + () => convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length))), ); } @@ -816,7 +814,8 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim () => { const diagnostics = this.languageService.getSyntacticDiagnostics(fileName); return this.realizeDiagnostics(diagnostics); - }); + }, + ); } public getSemanticDiagnostics(fileName: string): string { @@ -825,7 +824,8 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim () => { const diagnostics = this.languageService.getSemanticDiagnostics(fileName); return this.realizeDiagnostics(diagnostics); - }); + }, + ); } public getSuggestionDiagnostics(fileName: string): string { @@ -838,7 +838,8 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim () => { const diagnostics = this.languageService.getCompilerOptionsDiagnostics(); return this.realizeDiagnostics(diagnostics); - }); + }, + ); } /// QUICKINFO @@ -850,11 +851,10 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getQuickInfoAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getQuickInfoAtPosition('${fileName}', ${position})`, - () => this.languageService.getQuickInfoAtPosition(fileName, position) + () => this.languageService.getQuickInfoAtPosition(fileName, position), ); } - /// NAMEORDOTTEDNAMESPAN /** @@ -864,7 +864,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string { return this.forwardJSONCall( `getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`, - () => this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos) + () => this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos), ); } @@ -875,7 +875,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getBreakpointStatementAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getBreakpointStatementAtPosition('${fileName}', ${position})`, - () => this.languageService.getBreakpointStatementAtPosition(fileName, position) + () => this.languageService.getBreakpointStatementAtPosition(fileName, position), ); } @@ -884,7 +884,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): string { return this.forwardJSONCall( `getSignatureHelpItems('${fileName}', ${position})`, - () => this.languageService.getSignatureHelpItems(fileName, position, options) + () => this.languageService.getSignatureHelpItems(fileName, position, options), ); } @@ -897,7 +897,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getDefinitionAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getDefinitionAtPosition('${fileName}', ${position})`, - () => this.languageService.getDefinitionAtPosition(fileName, position) + () => this.languageService.getDefinitionAtPosition(fileName, position), ); } @@ -908,7 +908,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getDefinitionAndBoundSpan(fileName: string, position: number): string { return this.forwardJSONCall( `getDefinitionAndBoundSpan('${fileName}', ${position})`, - () => this.languageService.getDefinitionAndBoundSpan(fileName, position) + () => this.languageService.getDefinitionAndBoundSpan(fileName, position), ); } @@ -921,7 +921,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getTypeDefinitionAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getTypeDefinitionAtPosition('${fileName}', ${position})`, - () => this.languageService.getTypeDefinitionAtPosition(fileName, position) + () => this.languageService.getTypeDefinitionAtPosition(fileName, position), ); } @@ -934,28 +934,28 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getImplementationAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getImplementationAtPosition('${fileName}', ${position})`, - () => this.languageService.getImplementationAtPosition(fileName, position) + () => this.languageService.getImplementationAtPosition(fileName, position), ); } public getRenameInfo(fileName: string, position: number, preferences: UserPreferences): string { return this.forwardJSONCall( `getRenameInfo('${fileName}', ${position})`, - () => this.languageService.getRenameInfo(fileName, position, preferences) + () => this.languageService.getRenameInfo(fileName, position, preferences), ); } public getSmartSelectionRange(fileName: string, position: number): string { return this.forwardJSONCall( `getSmartSelectionRange('${fileName}', ${position})`, - () => this.languageService.getSmartSelectionRange(fileName, position) + () => this.languageService.getSmartSelectionRange(fileName, position), ); } public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, preferences: UserPreferences): string { return this.forwardJSONCall( `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`, - () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, preferences) + () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, preferences), ); } @@ -963,21 +963,21 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getBraceMatchingAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getBraceMatchingAtPosition('${fileName}', ${position})`, - () => this.languageService.getBraceMatchingAtPosition(fileName, position) + () => this.languageService.getBraceMatchingAtPosition(fileName, position), ); } public isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string { return this.forwardJSONCall( `isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`, - () => this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace) + () => this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace), ); } public getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): string { return this.forwardJSONCall( `getSpanOfEnclosingComment('${fileName}', ${position})`, - () => this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine) + () => this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine), ); } @@ -988,7 +988,8 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim () => { const localOptions: EditorOptions = JSON.parse(options); return this.languageService.getIndentationAtPosition(fileName, position, localOptions); - }); + }, + ); } /// GET REFERENCES @@ -996,21 +997,21 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getReferencesAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getReferencesAtPosition('${fileName}', ${position})`, - () => this.languageService.getReferencesAtPosition(fileName, position) + () => this.languageService.getReferencesAtPosition(fileName, position), ); } public findReferences(fileName: string, position: number): string { return this.forwardJSONCall( `findReferences('${fileName}', ${position})`, - () => this.languageService.findReferences(fileName, position) + () => this.languageService.findReferences(fileName, position), ); } public getFileReferences(fileName: string) { return this.forwardJSONCall( `getFileReferences('${fileName})`, - () => this.languageService.getFileReferences(fileName) + () => this.languageService.getFileReferences(fileName), ); } @@ -1022,7 +1023,8 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim // workaround for VS document highlighting issue - keep only items from the initial file const normalizedName = toFileNameLowerCase(normalizeSlashes(fileName)); return filter(results, r => toFileNameLowerCase(normalizeSlashes(r.fileName)) === normalizedName); - }); + }, + ); } /// COMPLETION LISTS @@ -1035,52 +1037,55 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getCompletionsAtPosition(fileName: string, position: number, preferences: GetCompletionsAtPositionOptions | undefined, formattingSettings: FormatCodeSettings | undefined) { return this.forwardJSONCall( `getCompletionsAtPosition('${fileName}', ${position}, ${preferences}, ${formattingSettings})`, - () => this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings) + () => this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings), ); } /** Get a string based representation of a completion list entry details */ - public getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string/*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined) { + public getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: string /*Services.FormatCodeOptions*/ | undefined, source: string | undefined, preferences: UserPreferences | undefined, data: CompletionEntryData | undefined) { return this.forwardJSONCall( `getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`, () => { const localOptions: FormatCodeOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); - } + }, ); } - public getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string { + public getFormattingEditsForRange(fileName: string, start: number, end: number, options: string /*Services.FormatCodeOptions*/): string { return this.forwardJSONCall( `getFormattingEditsForRange('${fileName}', ${start}, ${end})`, () => { const localOptions: FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); - }); + }, + ); } - public getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string { + public getFormattingEditsForDocument(fileName: string, options: string /*Services.FormatCodeOptions*/): string { return this.forwardJSONCall( `getFormattingEditsForDocument('${fileName}')`, () => { const localOptions: FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsForDocument(fileName, localOptions); - }); + }, + ); } - public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string { + public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string /*Services.FormatCodeOptions*/): string { return this.forwardJSONCall( `getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`, () => { const localOptions: FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); - }); + }, + ); } public getDocCommentTemplateAtPosition(fileName: string, position: number, options?: DocCommentTemplateOptions, formatOptions?: FormatCodeSettings): string { return this.forwardJSONCall( `getDocCommentTemplateAtPosition('${fileName}', ${position})`, - () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions) + () => this.languageService.getDocCommentTemplateAtPosition(fileName, position, options, formatOptions), ); } @@ -1090,35 +1095,35 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string { return this.forwardJSONCall( `getNavigateToItems('${searchValue}', ${maxResultCount}, ${fileName})`, - () => this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName) + () => this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName), ); } public getNavigationBarItems(fileName: string): string { return this.forwardJSONCall( `getNavigationBarItems('${fileName}')`, - () => this.languageService.getNavigationBarItems(fileName) + () => this.languageService.getNavigationBarItems(fileName), ); } public getNavigationTree(fileName: string): string { return this.forwardJSONCall( `getNavigationTree('${fileName}')`, - () => this.languageService.getNavigationTree(fileName) + () => this.languageService.getNavigationTree(fileName), ); } public getOutliningSpans(fileName: string): string { return this.forwardJSONCall( `getOutliningSpans('${fileName}')`, - () => this.languageService.getOutliningSpans(fileName) + () => this.languageService.getOutliningSpans(fileName), ); } public getTodoComments(fileName: string, descriptors: string): string { return this.forwardJSONCall( `getTodoComments('${fileName}')`, - () => this.languageService.getTodoComments(fileName, JSON.parse(descriptors)) + () => this.languageService.getTodoComments(fileName, JSON.parse(descriptors)), ); } @@ -1127,28 +1132,28 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim public prepareCallHierarchy(fileName: string, position: number): string { return this.forwardJSONCall( `prepareCallHierarchy('${fileName}', ${position})`, - () => this.languageService.prepareCallHierarchy(fileName, position) + () => this.languageService.prepareCallHierarchy(fileName, position), ); } public provideCallHierarchyIncomingCalls(fileName: string, position: number): string { return this.forwardJSONCall( `provideCallHierarchyIncomingCalls('${fileName}', ${position})`, - () => this.languageService.provideCallHierarchyIncomingCalls(fileName, position) + () => this.languageService.provideCallHierarchyIncomingCalls(fileName, position), ); } public provideCallHierarchyOutgoingCalls(fileName: string, position: number): string { return this.forwardJSONCall( `provideCallHierarchyOutgoingCalls('${fileName}', ${position})`, - () => this.languageService.provideCallHierarchyOutgoingCalls(fileName, position) + () => this.languageService.provideCallHierarchyOutgoingCalls(fileName, position), ); } public provideInlayHints(fileName: string, span: TextSpan, preference: UserPreferences | undefined): string { return this.forwardJSONCall( `provideInlayHints('${fileName}', '${JSON.stringify(span)}', ${JSON.stringify(preference)})`, - () => this.languageService.provideInlayHints(fileName, span, preference) + () => this.languageService.provideInlayHints(fileName, span, preference), ); } @@ -1159,7 +1164,7 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim () => { const { diagnostics, ...rest } = this.languageService.getEmitOutput(fileName); return { ...rest, diagnostics: this.realizeDiagnostics(diagnostics) }; - } + }, ); } @@ -1169,39 +1174,40 @@ class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim `getEmitOutput('${fileName}')`, /*returnJson*/ false, () => this.languageService.getEmitOutput(fileName), - this.logPerformance) as EmitOutput; + this.logPerformance, + ) as EmitOutput; } public toggleLineComment(fileName: string, textRange: TextRange): string { return this.forwardJSONCall( `toggleLineComment('${fileName}', '${JSON.stringify(textRange)}')`, - () => this.languageService.toggleLineComment(fileName, textRange) + () => this.languageService.toggleLineComment(fileName, textRange), ); } public toggleMultilineComment(fileName: string, textRange: TextRange): string { return this.forwardJSONCall( `toggleMultilineComment('${fileName}', '${JSON.stringify(textRange)}')`, - () => this.languageService.toggleMultilineComment(fileName, textRange) + () => this.languageService.toggleMultilineComment(fileName, textRange), ); } public commentSelection(fileName: string, textRange: TextRange): string { return this.forwardJSONCall( `commentSelection('${fileName}', '${JSON.stringify(textRange)}')`, - () => this.languageService.commentSelection(fileName, textRange) + () => this.languageService.commentSelection(fileName, textRange), ); } public uncommentSelection(fileName: string, textRange: TextRange): string { return this.forwardJSONCall( `uncommentSelection('${fileName}', '${JSON.stringify(textRange)}')`, - () => this.languageService.uncommentSelection(fileName, textRange) + () => this.languageService.uncommentSelection(fileName, textRange), ); } } -function convertClassifications(classifications: Classifications): { spans: string, endOfLineState: EndOfLineState } { +function convertClassifications(classifications: Classifications): { spans: string; endOfLineState: EndOfLineState; } { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } @@ -1215,9 +1221,7 @@ class ClassifierShimObject extends ShimBase implements ClassifierShim { } public getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent = false): string { - return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", - () => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)), - this.logPerformance); + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", () => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)), this.logPerformance); } /// COLORIZATION @@ -1269,7 +1273,7 @@ class CoreServicesShimObject extends ShimBase implements CoreServicesShim { return { resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined, primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, - failedLookupLocations: result.failedLookupLocations + failedLookupLocations: result.failedLookupLocations, }; }); } @@ -1286,9 +1290,10 @@ class CoreServicesShimObject extends ShimBase implements CoreServicesShim { ambientExternalModules: result.ambientExternalModules, isLibFile: result.isLibFile, typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives), - libReferenceDirectives: this.convertFileReferences(result.libReferenceDirectives) + libReferenceDirectives: this.convertFileReferences(result.libReferenceDirectives), }; - }); + }, + ); } public getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string { @@ -1297,7 +1302,7 @@ class CoreServicesShimObject extends ShimBase implements CoreServicesShim { () => { const compilerOptions = JSON.parse(compilerOptionsJson) as CompilerOptions; return getAutomaticTypeDirectiveNames(compilerOptions, this.host); - } + }, ); } @@ -1310,7 +1315,7 @@ class CoreServicesShimObject extends ShimBase implements CoreServicesShim { result.push({ path: normalizeSlashes(ref.fileName), position: ref.pos, - length: ref.end - ref.pos + length: ref.end - ref.pos, }); } return result; @@ -1329,15 +1334,16 @@ class CoreServicesShimObject extends ShimBase implements CoreServicesShim { typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, - errors: realizeDiagnostics([...result.parseDiagnostics, ...configFile.errors], "\r\n") + errors: realizeDiagnostics([...result.parseDiagnostics, ...configFile.errors], "\r\n"), }; - }); + }, + ); } public getDefaultCompilationSettings(): string { return this.forwardJSONCall( "getDefaultCompilationSettings()", - () => getDefaultCompilerOptions() + () => getDefaultCompilerOptions(), ); } @@ -1358,7 +1364,8 @@ class CoreServicesShimObject extends ShimBase implements CoreServicesShim { info.typeAcquisition, info.unresolvedImports, info.typesRegistry, - emptyOptions); + emptyOptions, + ); }); } } diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 9d3c350943987..bde65d54583c5 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -90,9 +90,19 @@ import { TypeParameter, } from "./_namespaces/ts"; -const enum InvocationKind { Call, TypeArgs, Contextual } -interface CallInvocation { readonly kind: InvocationKind.Call; readonly node: CallLikeExpression; } -interface TypeArgsInvocation { readonly kind: InvocationKind.TypeArgs; readonly called: Identifier; } +const enum InvocationKind { + Call, + TypeArgs, + Contextual, +} +interface CallInvocation { + readonly kind: InvocationKind.Call; + readonly node: CallLikeExpression; +} +interface TypeArgsInvocation { + readonly kind: InvocationKind.TypeArgs; + readonly called: Identifier; +} interface ContextualInvocation { readonly kind: InvocationKind.Contextual; readonly signature: Signature; @@ -151,7 +161,10 @@ export function getSignatureHelpItems(program: Program, sourceFile: SourceFile, : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker)); } -const enum CandidateOrTypeKind { Candidate, Type } +const enum CandidateOrTypeKind { + Candidate, + Type, +} interface CandidateInfo { readonly kind: CandidateOrTypeKind.Candidate; readonly candidates: readonly Signature[]; @@ -220,13 +233,16 @@ function createJSSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Pro if (callSignatures && callSignatures.length) { return typeChecker.runWithCancellationToken( cancellationToken, - typeChecker => createSignatureHelpItems( - callSignatures, - callSignatures[0], - argumentInfo, - sourceFile, - typeChecker, - /*useFullPrefix*/ true)); + typeChecker => + createSignatureHelpItems( + callSignatures, + callSignatures[0], + argumentInfo, + sourceFile, + typeChecker, + /*useFullPrefix*/ true, + ), + ); } })); } @@ -262,7 +278,7 @@ export function getArgumentInfoForCompletions(node: Node, position: number, sour : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; } -function getArgumentOrParameterListInfo(node: Node, position: number, sourceFile: SourceFile): { readonly list: Node, readonly argumentIndex: number, readonly argumentCount: number, readonly argumentsSpan: TextSpan } | undefined { +function getArgumentOrParameterListInfo(node: Node, position: number, sourceFile: SourceFile): { readonly list: Node; readonly argumentIndex: number; readonly argumentCount: number; readonly argumentsSpan: TextSpan; } | undefined { const info = getArgumentOrParameterListAndIndex(node, sourceFile); if (!info) return undefined; const { list, argumentIndex } = info; @@ -274,7 +290,7 @@ function getArgumentOrParameterListInfo(node: Node, position: number, sourceFile const argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { list, argumentIndex, argumentCount, argumentsSpan }; } -function getArgumentOrParameterListAndIndex(node: Node, sourceFile: SourceFile): { readonly list: Node, readonly argumentIndex: number } | undefined { +function getArgumentOrParameterListAndIndex(node: Node, sourceFile: SourceFile): { readonly list: Node; readonly argumentIndex: number; } | undefined { if (node.kind === SyntaxKind.LessThanToken || node.kind === SyntaxKind.OpenParenToken) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. @@ -365,7 +381,7 @@ function getImmediatelyContainingArgumentInfo(node: Node, position: number, sour invocation: { kind: InvocationKind.Call, node: parent }, argumentsSpan: createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart), argumentIndex: 0, - argumentCount: 1 + argumentCount: 1, }; } else { @@ -419,12 +435,16 @@ function getAdjustedNode(node: Node) { case SyntaxKind.CommaToken: return node; default: - return findAncestor(node.parent, n => - isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); + return findAncestor(node.parent, n => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); } } -interface ContextualSignatureLocationInfo { readonly contextualType: Type; readonly argumentIndex: number; readonly argumentCount: number; readonly argumentsSpan: TextSpan; } +interface ContextualSignatureLocationInfo { + readonly contextualType: Type; + readonly argumentIndex: number; + readonly argumentCount: number; + readonly argumentsSpan: TextSpan; +} function getContextualSignatureLocationInfo(node: Node, sourceFile: SourceFile, position: number, checker: TypeChecker): ContextualSignatureLocationInfo | undefined { const { parent } = node; switch (parent.kind) { @@ -513,11 +533,9 @@ function getArgumentIndexForTemplatePiece(spanIndex: number, node: Node, positio // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // - /* eslint-disable local/no-double-space */ // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 - /* eslint-enable local/no-double-space */ Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (isTemplateLiteralToken(node)) { if (isInsideTemplateLiteral(node, position, sourceFile)) { @@ -539,7 +557,7 @@ function getArgumentListInfoForTemplate(tagExpression: TaggedTemplateExpression, invocation: { kind: InvocationKind.Call, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex, - argumentCount + argumentCount, }; } @@ -667,7 +685,7 @@ function createTypeHelpItems( symbol: Symbol, { argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }: ArgumentListInfo, sourceFile: SourceFile, - checker: TypeChecker + checker: TypeChecker, ): SignatureHelpItems | undefined { const typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (!typeParameters) return undefined; @@ -714,7 +732,12 @@ function returnTypeToDisplayParts(candidateSignature: Signature, enclosingDeclar }); } -interface SignatureHelpItemInfo { readonly isVariadic: boolean; readonly parameters: SignatureHelpParameter[]; readonly prefix: readonly SymbolDisplayPart[]; readonly suffix: readonly SymbolDisplayPart[]; } +interface SignatureHelpItemInfo { + readonly isVariadic: boolean; + readonly parameters: SignatureHelpParameter[]; + readonly prefix: readonly SymbolDisplayPart[]; + readonly suffix: readonly SymbolDisplayPart[]; +} function itemInfoForTypeParameters(candidateSignature: Signature, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile): SignatureHelpItemInfo[] { const typeParameters = (candidateSignature.target || candidateSignature).typeParameters; @@ -740,15 +763,14 @@ function itemInfoForParameters(candidateSignature: Signature, checker: TypeCheck } }); const lists = checker.getExpandedParameters(candidateSignature); - const isVariadic: (parameterList: readonly Symbol[]) => boolean = - !checker.hasEffectiveRestParameter(candidateSignature) ? _ => false + const isVariadic: (parameterList: readonly Symbol[]) => boolean = !checker.hasEffectiveRestParameter(candidateSignature) ? _ => false : lists.length === 1 ? _ => true : pList => !!(pList.length && tryCast(pList[pList.length - 1], isTransientSymbol)?.links.checkFlags! & CheckFlags.RestParameter); return lists.map(parameterList => ({ isVariadic: isVariadic(parameterList), parameters: parameterList.map(p => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer)), prefix: [...typeParameterParts, punctuationPart(SyntaxKind.OpenParenToken)], - suffix: [punctuationPart(SyntaxKind.CloseParenToken)] + suffix: [punctuationPart(SyntaxKind.CloseParenToken)], })); } diff --git a/src/services/smartSelection.ts b/src/services/smartSelection.ts index 887fe86c0cbb2..d1cc5ca92472b 100644 --- a/src/services/smartSelection.ts +++ b/src/services/smartSelection.ts @@ -51,11 +51,12 @@ import { /** @internal */ export function getSmartSelectionRange(pos: number, sourceFile: SourceFile): SelectionRange { let selectionRange: SelectionRange = { - textSpan: createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) + textSpan: createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()), }; let parentNode: Node = sourceFile; - outer: while (true) { + outer: + while (true) { const children = getSelectionChildren(parentNode); if (!children.length) break; for (let i = 0; i < children.length; i++) { @@ -73,8 +74,10 @@ export function getSmartSelectionRange(pos: number, sourceFile: SourceFile): Sel } if (positionShouldSnapToNode(sourceFile, pos, node)) { - if (isFunctionBody(node) - && isFunctionLikeDeclaration(parentNode) && !positionsAreOnSameLine(node.getStart(sourceFile), node.getEnd(), sourceFile)) { + if ( + isFunctionBody(node) + && isFunctionLikeDeclaration(parentNode) && !positionsAreOnSameLine(node.getStart(sourceFile), node.getEnd(), sourceFile) + ) { pushSelectionRange(node.getStart(sourceFile), node.getEnd()); } @@ -84,13 +87,15 @@ export function getSmartSelectionRange(pos: number, sourceFile: SourceFile): Sel // 3. A VariableStatement's children are just a VaraiableDeclarationList and a semicolon. // 4. A lone VariableDeclaration in a VaraibleDeclaration feels redundant with the VariableStatement. // Dive in without pushing a selection range. - if (isBlock(node) + if ( + isBlock(node) || isTemplateSpan(node) || isTemplateHead(node) || isTemplateTail(node) || prevNode && isTemplateHead(prevNode) || isVariableDeclarationList(node) && isVariableStatement(parentNode) || isSyntaxList(node) && isVariableDeclarationList(parentNode) || isVariableDeclaration(node) && isSyntaxList(parentNode) && children.length === 1 - || isJSDocTypeExpression(node) || isJSDocSignature(node) || isJSDocTypeLiteral(node)) { + || isJSDocTypeExpression(node) || isJSDocSignature(node) || isJSDocTypeLiteral(node) + ) { parentNode = node; break; } @@ -150,12 +155,14 @@ export function getSmartSelectionRange(pos: number, sourceFile: SourceFile): Sel // Skip empty ranges if (start !== end) { const textSpan = createTextSpanFromBounds(start, end); - if (!selectionRange || ( - // Skip ranges that are identical to the parent - !textSpansEqual(textSpan, selectionRange.textSpan) && - // Skip ranges that don't contain the original position - textSpanIntersectsWithPosition(textSpan, pos) - )) { + if ( + !selectionRange || ( + // Skip ranges that are identical to the parent + !textSpansEqual(textSpan, selectionRange.textSpan) && + // Skip ranges that don't contain the original position + textSpanIntersectsWithPosition(textSpan, pos) + ) + ) { selectionRange = { textSpan, ...selectionRange && { parent: selectionRange } }; } } @@ -235,8 +242,7 @@ function getSelectionChildren(node: Node): readonly Node[] { const groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, ({ kind }) => kind === SyntaxKind.OpenBracketToken || kind === SyntaxKind.TypeParameter || - kind === SyntaxKind.CloseBracketToken - ); + kind === SyntaxKind.CloseBracketToken); return [ openBraceToken, // Pivot on `:` @@ -247,20 +253,17 @@ function getSelectionChildren(node: Node): readonly Node[] { // Group modifiers and property name, then pivot on `:`. if (isPropertySignature(node)) { - const children = groupChildren(node.getChildren(), child => - child === node.name || contains(node.modifiers, child)); + const children = groupChildren(node.getChildren(), child => child === node.name || contains(node.modifiers, child)); const firstJSDocChild = children[0]?.kind === SyntaxKind.JSDoc ? children[0] : undefined; - const withJSDocSeparated = firstJSDocChild? children.slice(1) : children; + const withJSDocSeparated = firstJSDocChild ? children.slice(1) : children; const splittedChildren = splitChildren(withJSDocSeparated, ({ kind }) => kind === SyntaxKind.ColonToken); - return firstJSDocChild? [firstJSDocChild, createSyntaxList(splittedChildren)] : splittedChildren; + return firstJSDocChild ? [firstJSDocChild, createSyntaxList(splittedChildren)] : splittedChildren; } // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`. if (isParameter(node)) { - const groupedDotDotDotAndName = groupChildren(node.getChildren(), child => - child === node.dotDotDotToken || child === node.name); - const groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName, child => - child === groupedDotDotDotAndName[0] || child === node.questionToken); + const groupedDotDotDotAndName = groupChildren(node.getChildren(), child => child === node.dotDotDotToken || child === node.name); + const groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName, child => child === groupedDotDotDotAndName[0] || child === node.questionToken); return splitChildren(groupedWithQuestionToken, ({ kind }) => kind === SyntaxKind.EqualsToken); } diff --git a/src/services/sourcemaps.ts b/src/services/sourcemaps.ts index 9408098305551..72947635e6ae0 100644 --- a/src/services/sourcemaps.ts +++ b/src/services/sourcemaps.ts @@ -77,7 +77,7 @@ export function getSourceMapper(host: SourceMapperHost): SourceMapper { { getSourceFileLike, getCanonicalFileName, log: s => host.log(s) }, generatedFileName, getLineInfo(file.text, getLineStarts(file)), - f => !host.fileExists || host.fileExists(f) ? host.readFile!(f) : undefined + f => !host.fileExists || host.fileExists(f) ? host.readFile!(f) : undefined, ); } documentPositionMappers.set(path, mapper || identitySourceMapConsumer); @@ -176,7 +176,8 @@ export function getDocumentPositionMapper( host: DocumentPositionMapperHost, generatedFileName: string, generatedFileLineInfo: LineInfo, - readMapFile: ReadMapFile) { + readMapFile: ReadMapFile, +) { let mapFileName = tryGetSourceMappingURL(generatedFileLineInfo); if (mapFileName) { const match = base64UrlRegExp.exec(mapFileName); @@ -227,6 +228,6 @@ function createSourceFileLike(text: string, lineMap?: SourceFileLike["lineMap"]) lineMap, getLineAndCharacterOfPosition(pos: number) { return computeLineAndCharacterOfPosition(getLineStarts(this), pos); - } + }, }; } diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index bb41bf4d594bc..657f104418fa5 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -197,7 +197,8 @@ export function getStringLiteralCompletions( program: Program, log: Log, preferences: UserPreferences, - includeSymbol: boolean): CompletionInfo | undefined { + includeSymbol: boolean, +): CompletionInfo | undefined { if (isInReferenceComment(sourceFile, position)) { const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); return entries && convertPathCompletions(entries); @@ -257,7 +258,7 @@ function convertStringLiteralCompletions( /*symbolToSortTextMap*/ undefined, /*isJsxIdentifierExpected*/ undefined, /*isRightOfOpenTag*/ undefined, - includeSymbol + includeSymbol, ); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan, entries }; } @@ -267,7 +268,7 @@ function convertStringLiteralCompletions( kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.string, sortText: SortText.LocationPriority, - replacementSpan: getReplacementSpanForContextToken(contextToken) + replacementSpan: getReplacementSpanForContextToken(contextToken), })); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, optionalReplacementSpan, entries }; } @@ -303,32 +304,49 @@ function stringLiteralCompletionDetails(name: string, location: Node, completion function convertPathCompletions(pathCompletions: readonly PathCompletion[]): CompletionInfo { const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. - const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry => - ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span })); + const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry => ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span })); return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries }; } function kindModifiersFromExtension(extension: Extension | undefined): ScriptElementKindModifier { switch (extension) { - case Extension.Dts: return ScriptElementKindModifier.dtsModifier; - case Extension.Js: return ScriptElementKindModifier.jsModifier; - case Extension.Json: return ScriptElementKindModifier.jsonModifier; - case Extension.Jsx: return ScriptElementKindModifier.jsxModifier; - case Extension.Ts: return ScriptElementKindModifier.tsModifier; - case Extension.Tsx: return ScriptElementKindModifier.tsxModifier; - case Extension.Dmts: return ScriptElementKindModifier.dmtsModifier; - case Extension.Mjs: return ScriptElementKindModifier.mjsModifier; - case Extension.Mts: return ScriptElementKindModifier.mtsModifier; - case Extension.Dcts: return ScriptElementKindModifier.dctsModifier; - case Extension.Cjs: return ScriptElementKindModifier.cjsModifier; - case Extension.Cts: return ScriptElementKindModifier.ctsModifier; - case Extension.TsBuildInfo: return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported.`); - case undefined: return ScriptElementKindModifier.none; + case Extension.Dts: + return ScriptElementKindModifier.dtsModifier; + case Extension.Js: + return ScriptElementKindModifier.jsModifier; + case Extension.Json: + return ScriptElementKindModifier.jsonModifier; + case Extension.Jsx: + return ScriptElementKindModifier.jsxModifier; + case Extension.Ts: + return ScriptElementKindModifier.tsModifier; + case Extension.Tsx: + return ScriptElementKindModifier.tsxModifier; + case Extension.Dmts: + return ScriptElementKindModifier.dmtsModifier; + case Extension.Mjs: + return ScriptElementKindModifier.mjsModifier; + case Extension.Mts: + return ScriptElementKindModifier.mtsModifier; + case Extension.Dcts: + return ScriptElementKindModifier.dctsModifier; + case Extension.Cjs: + return ScriptElementKindModifier.cjsModifier; + case Extension.Cts: + return ScriptElementKindModifier.ctsModifier; + case Extension.TsBuildInfo: + return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported.`); + case undefined: + return ScriptElementKindModifier.none; default: return Debug.assertNever(extension); } } -const enum StringLiteralCompletionKind { Paths, Properties, Types } +const enum StringLiteralCompletionKind { + Paths, + Properties, + Types, +} interface StringLiteralCompletionsFromProperties { readonly kind: StringLiteralCompletionKind.Properties; readonly symbols: readonly Symbol[]; @@ -339,7 +357,7 @@ interface StringLiteralCompletionsFromTypes { readonly types: readonly StringLiteralType[]; readonly isNewIdentifier: boolean; } -type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: readonly PathCompletion[] } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; +type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths; readonly paths: readonly PathCompletion[]; } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost, preferences: UserPreferences): StringLiteralCompletion | undefined { const parent = walkUpParentheses(node.parent); switch (parent.kind) { @@ -477,8 +495,7 @@ function walkUpParentheses(node: Node) { } function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): readonly string[] { - return mapDefined(union.types, type => - type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined); + return mapDefined(union.types, type => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined); } function getStringLiteralCompletionsFromSignature(call: CallLikeExpression, arg: StringLiteralLike, argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker, checkMode = CheckMode.IsForStringLiteralArgumentCompletions): StringLiteralCompletionsFromTypes | undefined { @@ -506,7 +523,7 @@ function stringLiteralCompletionsFromProperties(type: Type | undefined): StringL return type && { kind: StringLiteralCompletionKind.Properties, symbols: filter(type.getApparentProperties(), prop => !(prop.valueDeclaration && isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration))), - hasIndexSignature: hasIndexSignature(type) + hasIndexSignature: hasIndexSignature(type), }; } @@ -519,13 +536,13 @@ function stringLiteralCompletionsForObjectLiteral(checker: TypeChecker, objectLi contextualType, completionsType, objectLiteralExpression, - checker + checker, ); return { kind: StringLiteralCompletionKind.Properties, symbols, - hasIndexSignature: hasIndexSignature(contextualType) + hasIndexSignature: hasIndexSignature(contextualType), }; } @@ -555,8 +572,7 @@ function directoryResult(name: string): NameAndKind { function addReplacementSpans(text: string, textStart: number, names: readonly NameAndKind[]): readonly PathCompletion[] { const span = getDirectoryFragmentTextSpan(text, textStart); const wholeSpan = text.length === 0 ? undefined : createTextSpan(textStart, text.length); - return names.map(({ name, kind, extension }): PathCompletion => - Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span }); + return names.map(({ name, kind, extension }): PathCompletion => Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span }); } function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker, preferences: UserPreferences): readonly PathCompletion[] { @@ -596,7 +612,14 @@ function getExtensionOptions(compilerOptions: CompilerOptions, referenceKind: Re function getCompletionEntriesForRelativeModules(literalValue: string, scriptDirectory: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, scriptPath: Path, extensionOptions: ExtensionOptions) { if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs( - compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); + compilerOptions.rootDirs, + literalValue, + scriptDirectory, + extensionOptions, + compilerOptions, + host, + scriptPath, + ); } else { return arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, /*moduleSpecifierIsRelative*/ true, scriptPath).values()); @@ -605,13 +628,11 @@ function getCompletionEntriesForRelativeModules(literalValue: string, scriptDire function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions, typeChecker?: TypeChecker): readonly string[][] { /** file extensions from ambient modules declarations e.g. *.css */ - const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), - module => { - const name = module.name.slice(1, -1); - if (!name.startsWith("*.") || name.includes("/")) return; - return name.slice(1); - } - ); + const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), module => { + const name = module.name.slice(1, -1); + if (!name.startsWith("*.") || name.includes("/")) return; + return name.slice(1); + }); const extensions = [...getSupportedExtensions(compilerOptions), ambientModulesExtensions]; const moduleResolution = getEmitModuleResolutionKind(compilerOptions); @@ -629,14 +650,14 @@ function getBaseDirectoriesFromRootDirs(rootDirs: string[], basePath: string, sc rootDirs = rootDirs.map(rootDirectory => normalizePath(isRootedDiskPath(rootDirectory) ? rootDirectory : combinePaths(basePath, rootDirectory))); // Determine the path to the directory containing the script relative to the root directory it is contained within - const relativeDirectory = firstDefined(rootDirs, rootDirectory => - containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined)!; // TODO: GH#18217 + const relativeDirectory = firstDefined(rootDirs, rootDirectory => containsPath(rootDirectory, scriptDirectory, basePath, ignoreCase) ? scriptDirectory.substr(rootDirectory.length) : undefined)!; // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script return deduplicate( [...rootDirs.map(rootDirectory => combinePaths(rootDirectory, relativeDirectory)), scriptDirectory], equateStringsCaseSensitive, - compareStringsCaseSensitive); + compareStringsCaseSensitive, + ); } function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptDirectory: string, extensionOptions: ExtensionOptions, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude: string): readonly NameAndKind[] { @@ -660,7 +681,7 @@ function getCompletionEntriesForDirectoryFragment( host: LanguageServiceHost, moduleSpecifierIsRelative: boolean, exclude?: string, - result = createNameAndKindSet() + result = createNameAndKindSet(), ): NameAndKindSet { if (fragment === undefined) { fragment = ""; @@ -689,7 +710,7 @@ function getCompletionEntriesForDirectoryFragment( // check for a version redirect const packageJsonPath = findPackageJson(baseDirectory, host); if (packageJsonPath) { - const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined }); + const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined; }); const typesVersions = (packageJson as any).typesVersions; if (typeof typesVersions === "object") { const versionPaths = getPackageJsonTypesVersionsPaths(typesVersions)?.paths; @@ -739,7 +760,7 @@ function getCompletionEntriesForDirectoryFragment( return result; } -function getFilenameWithExtensionOption(name: string, compilerOptions: CompilerOptions, extensionOptions: ExtensionOptions): { name: string, extension: Extension | undefined } { +function getFilenameWithExtensionOption(name: string, compilerOptions: CompilerOptions, extensionOptions: ExtensionOptions): { name: string; extension: Extension | undefined; } { const nonJsResult = moduleSpecifiers.tryGetRealFileNameForNonJsDeclarationFileName(name); if (nonJsResult) { return { name: nonJsResult, extension: tryGetExtensionFromPath(nonJsResult) }; @@ -759,7 +780,8 @@ function getFilenameWithExtensionOption(name: string, compilerOptions: CompilerO : { name, extension: tryGetExtensionFromPath(name) }; } - if ((endingPreference === ModuleSpecifierEnding.Minimal || endingPreference === ModuleSpecifierEnding.Index) && + if ( + (endingPreference === ModuleSpecifierEnding.Minimal || endingPreference === ModuleSpecifierEnding.Index) && fileExtensionIsOneOf(name, [Extension.Js, Extension.Jsx, Extension.Ts, Extension.Tsx, Extension.Dts]) ) { return { name: removeFileExtension(name), extension: tryGetExtensionFromPath(name) }; @@ -778,7 +800,7 @@ function addCompletionEntriesFromPaths( baseDirectory: string, extensionOptions: ExtensionOptions, host: LanguageServiceHost, - paths: MapLike + paths: MapLike, ) { const getPatternsForKey = (key: string) => paths[key]; const comparePaths = (a: string, b: string): Comparison => { @@ -802,7 +824,7 @@ function addCompletionEntriesFromPathsOrExports( getPatternsForKey: (key: string) => string[] | undefined, comparePaths: (a: string, b: string) => Comparison, ) { - let pathResults: { results: NameAndKind[], matchedPattern: boolean }[] = []; + let pathResults: { results: NameAndKind[]; matchedPattern: boolean; }[] = []; let matchedPath: string | undefined; for (const key of keys) { if (key === ".") continue; @@ -936,7 +958,8 @@ function getCompletionEntriesForNonRelativeModules( host, keys, key => singleElementArray(getPatternFromFirstMatchingCondition(exports[key], conditions)), - comparePatternKeys); + comparePatternKeys, + ); return; } } @@ -985,8 +1008,7 @@ function getCompletionsForPathMapping( const remainingFragment = tryRemovePrefix(fragment, pathPrefix); if (remainingFragment === undefined) { const starIsFullPathComponent = path[path.length - 2] === "/"; - return starIsFullPathComponent ? justPathMappingName(pathPrefix, ScriptElementKind.directory) : flatMap(patterns, pattern => - getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)?.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest }))); + return starIsFullPathComponent ? justPathMappingName(pathPrefix, ScriptElementKind.directory) : flatMap(patterns, pattern => getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)?.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest }))); } return flatMap(patterns, pattern => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host)); @@ -1160,7 +1182,7 @@ function enumerateNodeModulesVisibleToScript(host: LanguageServiceHost, scriptPa const result: string[] = []; for (const packageJson of findPackageJsons(scriptPath, host)) { - const contents = readJson(packageJson, host as { readFile: (filename: string) => string | undefined }); // Cast to assert that readFile is defined + const contents = readJson(packageJson, host as { readFile: (filename: string) => string | undefined; }); // Cast to assert that readFile is defined // Provide completions for all non @types dependencies for (const key of nodeModulesDependencyKeys) { const dependencies: object | undefined = (contents as any)[key]; diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 4e425a1a32d0d..a11fedee2acc0 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -68,12 +68,14 @@ export function computeSuggestionDiagnostics(sourceFile: SourceFile, program: Pr program.getSemanticDiagnostics(sourceFile, cancellationToken); const diags: DiagnosticWithLocation[] = []; const checker = program.getTypeChecker(); - const isCommonJSFile = sourceFile.impliedNodeFormat === ModuleKind.CommonJS || fileExtensionIsOneOf(sourceFile.fileName, [Extension.Cts, Extension.Cjs]) ; + const isCommonJSFile = sourceFile.impliedNodeFormat === ModuleKind.CommonJS || fileExtensionIsOneOf(sourceFile.fileName, [Extension.Cts, Extension.Cjs]); - if (!isCommonJSFile && + if ( + !isCommonJSFile && sourceFile.commonJsModuleIndicator && (programContainsEsModules(program) || compilerOptionsIndicateEsModules(program.getCompilerOptions())) && - containsTopLevelCommonjs(sourceFile)) { + containsTopLevelCommonjs(sourceFile) + ) { diags.push(createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module)); } @@ -106,10 +108,12 @@ export function computeSuggestionDiagnostics(sourceFile: SourceFile, program: Pr } } else { - if (isVariableStatement(node) && + if ( + isVariableStatement(node) && node.parent === sourceFile && node.declarationList.flags & NodeFlags.Const && - node.declarationList.declarations.length === 1) { + node.declarationList.declarations.length === 1 + ) { const init = node.declarationList.declarations[0].initializer; if (init && isRequireCall(init, /*requireStringLiteralLikeArgument*/ true)) { diags.push(createDiagnosticForNode(init, Diagnostics.require_call_may_be_converted_to_an_import)); @@ -138,8 +142,7 @@ function containsTopLevelCommonjs(sourceFile: SourceFile): boolean { return sourceFile.statements.some(statement => { switch (statement.kind) { case SyntaxKind.VariableStatement: - return (statement as VariableStatement).declarationList.declarations.some(decl => - !!decl.initializer && isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*requireStringLiteralLikeArgument*/ true)); + return (statement as VariableStatement).declarationList.declarations.some(decl => !!decl.initializer && isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*requireStringLiteralLikeArgument*/ true)); case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; if (!isBinaryExpression(expression)) return isRequireCall(expression, /*requireStringLiteralLikeArgument*/ true); @@ -175,7 +178,8 @@ function addConvertToAsyncFunctionDiagnostics(node: FunctionLikeDeclaration, che if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) { diags.push(createDiagnosticForNode( !node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node, - Diagnostics.This_may_be_converted_to_an_async_function)); + Diagnostics.This_may_be_converted_to_an_async_function, + )); } } @@ -203,7 +207,7 @@ function hasReturnStatementWithPromiseHandler(body: Block, checker: TypeChecker) } /** @internal */ -export function isReturnStatementWithFixablePromiseHandler(node: Node, checker: TypeChecker): node is ReturnStatement & { expression: CallExpression } { +export function isReturnStatementWithFixablePromiseHandler(node: Node, checker: TypeChecker): node is ReturnStatement & { expression: CallExpression; } { return isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } @@ -231,14 +235,15 @@ export function isFixablePromiseHandler(node: Node, checker: TypeChecker): boole return true; } -function isPromiseHandler(node: Node): node is CallExpression & { readonly expression: PropertyAccessExpression } { +function isPromiseHandler(node: Node): node is CallExpression & { readonly expression: PropertyAccessExpression; } { return isCallExpression(node) && ( hasPropertyAccessExpressionWithName(node, "then") || hasPropertyAccessExpressionWithName(node, "catch") || - hasPropertyAccessExpressionWithName(node, "finally")); + hasPropertyAccessExpressionWithName(node, "finally") + ); } -function hasSupportedNumberOfArguments(node: CallExpression & { readonly expression: PropertyAccessExpression }) { +function hasSupportedNumberOfArguments(node: CallExpression & { readonly expression: PropertyAccessExpression; }) { const name = node.expression.name.text; const maxArguments = name === "then" ? 2 : name === "catch" ? 1 : name === "finally" ? 1 : 0; if (node.arguments.length > maxArguments) return false; diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index e77a2647f4884..6d453d135ef01 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -139,10 +139,12 @@ export function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind { const roots = typeChecker.getRootSymbols(symbol); // If this is a method from a mapped type, leave as a method so long as it still has a call signature. - if (roots.length === 1 + if ( + roots.length === 1 && first(roots).flags & SymbolFlags.Method // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`. - && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) { + && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0 + ) { return ScriptElementKind.memberFunctionElement; } @@ -254,8 +256,7 @@ export interface SymbolDisplayPartsDocumentationAndSymbolKind { tags: JSDocTagInfo[] | undefined; } -function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node | undefined, - location: Node, type: Type | undefined, semanticMeaning: SemanticMeaning, alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind { +function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node | undefined, location: Node, type: Type | undefined, semanticMeaning: SemanticMeaning, alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind { const displayParts: SymbolDisplayPart[] = []; let documentation: SymbolDisplayPart[] = []; let tags: JSDocTagInfo[] = []; @@ -277,7 +278,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { const declaration = find(symbol.declarations as ((GetAccessorDeclaration | SetAccessorDeclaration | PropertyDeclaration)[]), declaration => declaration.name === location); if (declaration) { - switch(declaration.kind){ + switch (declaration.kind) { case SyntaxKind.GetAccessor: symbolKind = ScriptElementKind.memberGetAccessorElement; break; @@ -289,7 +290,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type break; default: Debug.assertNever(declaration); - } + } } else { symbolKind = ScriptElementKind.memberVariableElement; @@ -390,13 +391,14 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type hasMultipleSignatures = allSignatures.length > 1; } } - else if ((isNameOfFunctionDeclaration(location) && !(symbolFlags & SymbolFlags.Accessor)) || // name of function declaration - (location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor)) { // At constructor keyword of constructor declaration + else if ( + (isNameOfFunctionDeclaration(location) && !(symbolFlags & SymbolFlags.Accessor)) || // name of function declaration + (location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor) + ) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it const functionDeclaration = location.parent as SignatureDeclaration; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, declaration => - declaration === (location.kind === SyntaxKind.ConstructorKeyword ? functionDeclaration.parent : functionDeclaration)); + const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, declaration => declaration === (location.kind === SyntaxKind.ConstructorKeyword ? functionDeclaration.parent : functionDeclaration)); if (locationIsSymbolDeclaration) { const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); @@ -414,8 +416,11 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === SyntaxKind.CallSignature && - !(type.symbol.flags & SymbolFlags.TypeLiteral || type.symbol.flags & SymbolFlags.ObjectLiteral) ? type.symbol : symbol, symbolKind); + addPrefixForAnyFunctionOrVar( + functionDeclaration.kind === SyntaxKind.CallSignature && + !(type.symbol.flags & SymbolFlags.TypeLiteral || type.symbol.flags & SymbolFlags.ObjectLiteral) ? type.symbol : symbol, + symbolKind, + ); } if (signature) { addSignatureDisplayParts(signature, allSignatures); @@ -532,8 +537,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type displayParts.push(spacePart()); displayParts.push(operatorPart(SyntaxKind.EqualsToken)); displayParts.push(spacePart()); - displayParts.push(displayPart(getTextOfConstantValue(constantValue), - typeof constantValue === "number" ? SymbolDisplayPartKind.numericLiteral : SymbolDisplayPartKind.stringLiteral)); + displayParts.push(displayPart(getTextOfConstantValue(constantValue), typeof constantValue === "number" ? SymbolDisplayPartKind.numericLiteral : SymbolDisplayPartKind.stringLiteral)); } } } @@ -546,8 +550,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type const resolvedNode = resolvedSymbol.declarations[0]; const declarationName = getNameOfDeclaration(resolvedNode); if (declarationName && !hasAddedSymbolInfo) { - const isExternalModuleDeclaration = - isModuleWithStringLiteralName(resolvedNode) && + const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, ModifierFlags.Ambient); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKindWorker( @@ -558,7 +561,8 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type declarationName, type, semanticMeaning, - shouldUseAliasName ? symbol : resolvedSymbol); + shouldUseAliasName ? symbol : resolvedSymbol, + ); displayParts.push(...resolvedInfo.displayParts); displayParts.push(lineBreakPart()); documentationFromAlias = resolvedInfo.documentation; @@ -628,7 +632,8 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type addPrefixForAnyFunctionOrVar(symbol, symbolKind); } // For properties, variables and local vars: show the type - if (symbolKind === ScriptElementKind.memberVariableElement || + if ( + symbolKind === ScriptElementKind.memberVariableElement || symbolKind === ScriptElementKind.memberAccessorVariableElement || symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement || @@ -638,7 +643,8 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type symbolKind === ScriptElementKind.indexSignatureElement || symbolKind === ScriptElementKind.variableUsingElement || symbolKind === ScriptElementKind.variableAwaitUsingElement || - isThisExpression) { + isThisExpression + ) { displayParts.push(punctuationPart(SyntaxKind.ColonToken)); displayParts.push(spacePart()); // If the type is type parameter, format it specially @@ -661,12 +667,14 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type displayParts.push(punctuationPart(SyntaxKind.CloseParenToken)); } } - else if (symbolFlags & SymbolFlags.Function || + else if ( + symbolFlags & SymbolFlags.Function || symbolFlags & SymbolFlags.Method || symbolFlags & SymbolFlags.Constructor || symbolFlags & SymbolFlags.Signature || symbolFlags & SymbolFlags.Accessor || - symbolKind === ScriptElementKind.memberFunctionElement) { + symbolKind === ScriptElementKind.memberFunctionElement + ) { const allSignatures = type.getNonNullableType().getCallSignatures(); if (allSignatures.length) { addSignatureDisplayParts(allSignatures[0], allSignatures); @@ -775,9 +783,9 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay.parent); } fullSymbolDisplayParts.push(punctuationPart(SyntaxKind.OpenBracketToken)); - //Needed to handle more than one type of index + // Needed to handle more than one type of index indexInfos.forEach((info, i) => { - //Needed to handle template literals + // Needed to handle template literals fullSymbolDisplayParts.push(...typeToDisplayParts(typeChecker, info.keyType)); if (i !== indexInfos.length - 1) { fullSymbolDisplayParts.push(spacePart()); @@ -788,8 +796,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type fullSymbolDisplayParts.push(punctuationPart(SyntaxKind.CloseBracketToken)); } else { - fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, - SymbolFormatFlags.WriteTypeParametersOrArguments | SymbolFormatFlags.UseOnlyExternalAliasing | SymbolFormatFlags.AllowAnyNodeKind); + fullSymbolDisplayParts = symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments | SymbolFormatFlags.UseOnlyExternalAliasing | SymbolFormatFlags.AllowAnyNodeKind); } addRange(displayParts, fullSymbolDisplayParts); if (symbol.flags & SymbolFlags.Optional) { @@ -858,8 +865,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location /** @internal */ -export function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node | undefined, - location: Node, semanticMeaning = getMeaningFromLocation(location), alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind { +export function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node | undefined, location: Node, semanticMeaning = getMeaningFromLocation(location), alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind { return getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symbol, sourceFile, enclosingDeclaration, location, /*type*/ undefined, semanticMeaning, alias); } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index fbfdba0f59bc3..47f5cceabd8a7 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -489,9 +489,9 @@ export function isThisTypeAnnotatable(containingFunction: SignatureDeclaration): /** @internal */ export class ChangeTracker { private readonly changes: Change[] = []; - private newFileChanges?: MultiMap ; - private readonly classesWithNodesInsertedAtStart = new Map(); // Set implemented as Map - private readonly deletedNodes: { readonly sourceFile: SourceFile, readonly node: Node | NodeArray }[] = []; + private newFileChanges?: MultiMap; + private readonly classesWithNodesInsertedAtStart = new Map(); // Set implemented as Map + private readonly deletedNodes: { readonly sourceFile: SourceFile; readonly node: Node | NodeArray; }[] = []; public static fromContext(context: TextChangesContext): ChangeTracker { return new ChangeTracker(getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); @@ -634,14 +634,16 @@ export class ChangeTracker { public insertNodesAtEndOfFile( sourceFile: SourceFile, newNodes: readonly Statement[], - blankLineBetween: boolean): void { + blankLineBetween: boolean, + ): void { this.insertAtEndOfFile(sourceFile, newNodes, blankLineBetween); } private insertAtEndOfFile( sourceFile: SourceFile, insert: readonly Statement[], - blankLineBetween: boolean): void { + blankLineBetween: boolean, + ): void { const pos = sourceFile.end + 1; const options = { prefix: this.newLineCharacter, @@ -703,7 +705,7 @@ export class ChangeTracker { for (const jsdoc of node.jsDoc) { this.deleteRange(sourceFile, { pos: getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), - end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}), }); } } @@ -713,8 +715,7 @@ export class ChangeTracker { } private createJSDocText(sourceFile: SourceFile, node: HasJSDoc) { - const comments = flatMap(node.jsDoc, jsDoc => - isString(jsDoc.comment) ? factory.createJSDocText(jsDoc.comment) : jsDoc.comment) as JSDocComment[]; + const comments = flatMap(node.jsDoc, jsDoc => isString(jsDoc.comment) ? factory.createJSDocText(jsDoc.comment) : jsDoc.comment) as JSDocComment[]; const jsDoc = singleOrUndefined(node.jsDoc); return jsDoc && positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && length(comments) === 0 ? undefined : factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n"))); @@ -726,11 +727,13 @@ export class ChangeTracker { public addJSDocTags(sourceFile: SourceFile, parent: HasJSDoc, newTags: readonly JSDocTag[]): void { const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags); - const unmergedNewTags = newTags.filter(newTag => !oldTags.some((tag, i) => { - const merged = tryMergeJsdocTags(tag, newTag); - if (merged) oldTags[i] = merged; - return !!merged; - })); + const unmergedNewTags = newTags.filter(newTag => + !oldTags.some((tag, i) => { + const merged = tryMergeJsdocTags(tag, newTag); + if (merged) oldTags[i] = merged; + return !!merged; + }) + ); this.replaceJSDocComment(sourceFile, parent, [...oldTags, ...unmergedNewTags]); } @@ -835,7 +838,7 @@ export class ChangeTracker { const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken()!, {}); this.insertNodeAt(sourceFile, pos, newNode, { prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken()!.pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, - suffix: this.newLineCharacter + suffix: this.newLineCharacter, }); } @@ -903,7 +906,7 @@ export class ChangeTracker { return { indentation, prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, - suffix: insertTrailingComma ? "," : isInterfaceDeclaration(node) && isEmpty ? ";" : "" + suffix: insertTrailingComma ? "," : isInterfaceDeclaration(node) && isEmpty ? ";" : "", }; } @@ -1015,7 +1018,8 @@ export class ChangeTracker { sourceFile, namedImports.elements[0], importSpecifier, - !positionsAreOnSameLine(namedImports.elements[0].getStart(), namedImports.parent.parent.getStart(), sourceFile)); + !positionsAreOnSameLine(namedImports.elements[0].getStart(), namedImports.parent.parent.getStart(), sourceFile), + ); } } @@ -1257,8 +1261,7 @@ namespace changesToText { const normalized = stableSort(changesInFile, (a, b) => (a.range.pos - b.range.pos) || (a.range.end - b.range.end)); // verify that change intervals do not overlap, except possibly at end points. for (let i = 0; i < normalized.length - 1; i++) { - Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", () => - `${JSON.stringify(normalized[i].range)} and ${JSON.stringify(normalized[i + 1].range)}`); + Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", () => `${JSON.stringify(normalized[i].range)} and ${JSON.stringify(normalized[i + 1].range)}`); } const textChanges = mapDefined(normalized, c => { @@ -1308,7 +1311,7 @@ namespace changesToText { // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line const noIndent = (options.indentation !== undefined || getLineStartPositionForPosition(pos, targetSourceFile) === pos) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent - + ((!options.suffix || endsWith(noIndent, options.suffix)) + + ((!options.suffix || endsWith(noIndent, options.suffix)) ? "" : options.suffix); } @@ -1317,10 +1320,9 @@ namespace changesToText { const { node, text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter); if (validate) validate(node, text); const formatOptions = getFormatCodeSettingsForWriting(formatContext, targetSourceFile); - const initialIndentation = - indentation !== undefined - ? indentation - : formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos); + const initialIndentation = indentation !== undefined + ? indentation + : formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos); if (delta === undefined) { delta = formatting.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? (formatOptions.indentSize || 0) : 0; } @@ -1329,21 +1331,21 @@ namespace changesToText { text, getLineAndCharacterOfPosition(pos) { return getLineAndCharacterOfPosition(this, pos); - } + }, }; const changes = formatting.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); return applyChanges(text, changes); } /** Note: output node may be mutated input node. */ - export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } { + export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string; node: Node; } { const writer = createWriter(newLineCharacter); const newLine = getNewLineKind(newLineCharacter); createPrinter({ newLine, neverAsciiEscape: true, preserveSourceNewlines: true, - terminateUnterminatedLiterals: true + terminateUnterminatedLiterals: true, }, writer).writeNode(EmitHint.Unspecified, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } @@ -1368,7 +1370,8 @@ const textChangesTransformationContext: TransformationContext = { ...nullTransformationContext, factory: createNodeFactory( nullTransformationContext.factory.flags | NodeFactoryFlags.NoParenthesizerRules, - nullTransformationContext.factory.baseFactory), + nullTransformationContext.factory.baseFactory, + ), }; /** @internal */ @@ -1563,7 +1566,7 @@ export function createWriter(newLine: string): TextChangesWriter { isAtStartOfLine, hasTrailingComment: () => writer.hasTrailingComment(), hasTrailingWhitespace: () => writer.hasTrailingWhitespace(), - clear + clear, }; } @@ -1664,9 +1667,11 @@ namespace deleteDeclaration { switch (node.kind) { case SyntaxKind.Parameter: { const oldFunction = node.parent; - if (isArrowFunction(oldFunction) && + if ( + isArrowFunction(oldFunction) && oldFunction.parameters.length === 1 && - !findChildOfKind(oldFunction, SyntaxKind.OpenParenToken, sourceFile)) { + !findChildOfKind(oldFunction, SyntaxKind.OpenParenToken, sourceFile) + ) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). diff --git a/src/services/transpile.ts b/src/services/transpile.ts index 0f7e2b238c002..d68f49fd4a3ed 100644 --- a/src/services/transpile.ts +++ b/src/services/transpile.ts @@ -46,7 +46,7 @@ export interface TranspileOutput { const optionsRedundantWithVerbatimModuleSyntax = new Set([ "isolatedModules", "preserveValueImports", - "importsNotUsedAsValues" + "importsNotUsedAsValues", ]); /* @@ -89,7 +89,7 @@ export function transpileModule(input: string, transpileOptions: TranspileOption const newLine = getNewLineCharacter(options); // Create a compilerHost object to allow the compiler to read and write files const compilerHost: CompilerHost = { - getSourceFile: (fileName) => fileName === normalizePath(inputFileName) ? sourceFile : undefined, + getSourceFile: fileName => fileName === normalizePath(inputFileName) ? sourceFile : undefined, writeFile: (name, text) => { if (fileExtensionIs(name, ".map")) { Debug.assertEqual(sourceMapText, undefined, "Unexpected multiple source map outputs, file:", name); @@ -108,7 +108,7 @@ export function transpileModule(input: string, transpileOptions: TranspileOption fileExists: (fileName): boolean => fileName === inputFileName, readFile: () => "", directoryExists: () => true, - getDirectories: () => [] + getDirectories: () => [], }; // if jsx is specified then treat file as .tsx @@ -119,8 +119,8 @@ export function transpileModule(input: string, transpileOptions: TranspileOption { languageVersion: getEmitScriptTarget(options), impliedNodeFormat: getImpliedNodeFormatForFile(toPath(inputFileName, "", compilerHost.getCanonicalFileName), /*packageJsonInfoCache*/ undefined, compilerHost, options), - setExternalModuleIndicator: getSetExternalModuleIndicator(options) - } + setExternalModuleIndicator: getSetExternalModuleIndicator(options), + }, ); if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; diff --git a/src/services/types.ts b/src/services/types.ts index dc69092d3fe9a..9c1fe3a73eb73 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -95,7 +95,7 @@ declare module "../compiler/types" { getDeclarations(): Declaration[] | undefined; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; /** @internal */ - getContextualDocumentationComment(context: Node | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] + getContextualDocumentationComment(context: Node | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[]; getJsDocTags(checker?: TypeChecker): JSDocTagInfo[]; /** @internal */ getContextualJsDocTags(context: Node | undefined, checker: TypeChecker | undefined): JSDocTagInfo[]; @@ -215,7 +215,6 @@ export interface IScriptSnapshot { export namespace ScriptSnapshot { class StringScriptSnapshot implements IScriptSnapshot { - constructor(private text: string) { } @@ -376,7 +375,7 @@ export interface LanguageServiceHost extends GetEffectiveTypeRootsHost, MinimalR redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile: SourceFile | undefined, - reusedNames: readonly T[] | undefined + reusedNames: readonly T[] | undefined, ): readonly ResolvedTypeReferenceDirectiveWithFailedLookupLocations[]; /** @internal */ resolveLibrary?( @@ -436,7 +435,7 @@ export type WithMetadata = T & { metadata?: unknown; }; export const enum SemanticClassificationFormat { Original = "original", - TwentyTwenty = "2020" + TwentyTwenty = "2020", } // @@ -603,7 +602,7 @@ export interface LanguageService { provideCallHierarchyIncomingCalls(fileName: string, position: number): CallHierarchyIncomingCall[]; provideCallHierarchyOutgoingCalls(fileName: string, position: number): CallHierarchyOutgoingCall[]; - provideInlayHints(fileName: string, span: TextSpan, preferences: UserPreferences | undefined): InlayHint[] + provideInlayHints(fileName: string, span: TextSpan, preferences: UserPreferences | undefined): InlayHint[]; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; @@ -653,7 +652,7 @@ export interface LanguageService { */ getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string, includeInteractiveActions?: boolean): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined, interactiveRefactorArguments?: InteractiveRefactorArguments): RefactorEditInfo | undefined; - getMoveToRefactoringFileSuggestions(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): { newFileName: string, files: string[] }; + getMoveToRefactoringFileSuggestions(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): { newFileName: string; files: string[]; }; organizeImports(args: OrganizeImportsArgs, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; @@ -689,7 +688,10 @@ export interface LinkedEditingInfo { wordPattern?: string; } -export interface CombinedCodeFixScope { type: "file"; fileName: string; } +export interface CombinedCodeFixScope { + type: "file"; + fileName: string; +} export const enum OrganizeImportsMode { All = "All", @@ -729,7 +731,7 @@ export interface GetCompletionsAtPositionOptions extends UserPreferences { * so use caution when serializing or retaining completion entries retrieved with this option. * @default false */ - includeSymbol?: boolean + includeSymbol?: boolean; /** @deprecated Use includeCompletionsForModuleExports */ includeExternalModuleExports?: boolean; /** @deprecated Use includeCompletionsWithInsertText */ @@ -1181,7 +1183,7 @@ export function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatC placeOpenBraceOnNewLineForControlBlocks: false, semicolons: SemicolonPreference.Ignore, trimTrailingWhitespace: true, - indentSwitchCase: true + indentSwitchCase: true, }; } @@ -1436,7 +1438,7 @@ export interface CompletionEntry { * Included for non-string completions only when `includeSymbol: true` option is passed to `getCompletionsAtPosition`. * @example Get declaration of completion: `symbol.valueDeclaration` */ - symbol?: Symbol + symbol?: Symbol; /** * A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`, * that allows TS Server to look up the symbol represented by the completion item, disambiguating @@ -1456,7 +1458,7 @@ export interface CompletionEntryLabelDetails { export interface CompletionEntryDetails { name: string; kind: ScriptElementKind; - kindModifiers: string; // see ScriptElementKindModifier, comma separated + kindModifiers: string; // see ScriptElementKindModifier, comma separated displayParts: SymbolDisplayPart[]; documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; @@ -1499,13 +1501,13 @@ export const enum OutliningSpanKind { Code = "code", /** Contiguous blocks of import declarations */ - Imports = "imports" + Imports = "imports", } export const enum OutputFileType { JavaScript, SourceMap, - Declaration + Declaration, } export const enum EndOfLineState { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 4d94041411e8b..daf401d496379 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -376,7 +376,7 @@ import { } from "./_namespaces/ts"; // These utilities are common to multiple language service features. -//#region +// #region /** @internal */ export const scanner: Scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true); @@ -386,7 +386,7 @@ export const enum SemanticMeaning { Value = 0x1, Type = 0x2, Namespace = 0x4, - All = Value | Type | Namespace + All = Value | Type | Namespace, } /** @internal */ @@ -462,12 +462,14 @@ export function getMeaningFromLocation(node: Node): SemanticMeaning { if (node.kind === SyntaxKind.SourceFile) { return SemanticMeaning.Value; } - else if (isExportAssignment(parent) + else if ( + isExportAssignment(parent) || isExportSpecifier(parent) || isExternalModuleReference(parent) || isImportSpecifier(parent) || isImportClause(parent) - || isImportEqualsDeclaration(parent) && node === parent.name) { + || isImportEqualsDeclaration(parent) && node === parent.name + ) { return SemanticMeaning.All; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -657,7 +659,7 @@ export function hasPropertyAccessExpressionWithName(node: CallExpression, funcNa } /** @internal */ -export function isJumpStatementTarget(node: Node): node is Identifier & { parent: BreakOrContinueStatement } { +export function isJumpStatementTarget(node: Node): node is Identifier & { parent: BreakOrContinueStatement; } { return isIdentifier(node) && tryCast(node.parent, isBreakOrContinueStatement)?.label === node; } @@ -772,12 +774,14 @@ export function getNodeKind(node: Node): ScriptElementKind { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: return ScriptElementKind.classElement; - case SyntaxKind.InterfaceDeclaration: return ScriptElementKind.interfaceElement; + case SyntaxKind.InterfaceDeclaration: + return ScriptElementKind.interfaceElement; case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.JSDocCallbackTag: case SyntaxKind.JSDocTypedefTag: return ScriptElementKind.typeElement; - case SyntaxKind.EnumDeclaration: return ScriptElementKind.enumElement; + case SyntaxKind.EnumDeclaration: + return ScriptElementKind.enumElement; case SyntaxKind.VariableDeclaration: return getKindOfVariableDeclaration(node as VariableDeclaration); case SyntaxKind.BindingElement: @@ -786,8 +790,10 @@ export function getNodeKind(node: Node): ScriptElementKind { case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: return ScriptElementKind.functionElement; - case SyntaxKind.GetAccessor: return ScriptElementKind.memberGetAccessorElement; - case SyntaxKind.SetAccessor: return ScriptElementKind.memberSetAccessorElement; + case SyntaxKind.GetAccessor: + return ScriptElementKind.memberGetAccessorElement; + case SyntaxKind.SetAccessor: + return ScriptElementKind.memberSetAccessorElement; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: return ScriptElementKind.memberFunctionElement; @@ -799,15 +805,21 @@ export function getNodeKind(node: Node): ScriptElementKind { case SyntaxKind.ShorthandPropertyAssignment: case SyntaxKind.SpreadAssignment: return ScriptElementKind.memberVariableElement; - case SyntaxKind.IndexSignature: return ScriptElementKind.indexSignatureElement; - case SyntaxKind.ConstructSignature: return ScriptElementKind.constructSignatureElement; - case SyntaxKind.CallSignature: return ScriptElementKind.callSignatureElement; + case SyntaxKind.IndexSignature: + return ScriptElementKind.indexSignatureElement; + case SyntaxKind.ConstructSignature: + return ScriptElementKind.constructSignatureElement; + case SyntaxKind.CallSignature: + return ScriptElementKind.callSignatureElement; case SyntaxKind.Constructor: case SyntaxKind.ClassStaticBlockDeclaration: return ScriptElementKind.constructorImplementationElement; - case SyntaxKind.TypeParameter: return ScriptElementKind.typeParameterElement; - case SyntaxKind.EnumMember: return ScriptElementKind.enumMemberElement; - case SyntaxKind.Parameter: return hasSyntacticModifier(node, ModifierFlags.ParameterPropertyModifier) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case SyntaxKind.TypeParameter: + return ScriptElementKind.typeParameterElement; + case SyntaxKind.EnumMember: + return ScriptElementKind.enumMemberElement; + case SyntaxKind.Parameter: + return hasSyntacticModifier(node, ModifierFlags.ParameterPropertyModifier) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: @@ -855,8 +867,8 @@ export function getNodeKind(node: Node): ScriptElementKind { return isVarConst(v) ? ScriptElementKind.constElement : isLet(v) - ? ScriptElementKind.letElement - : ScriptElementKind.variableElement; + ? ScriptElementKind.letElement + : ScriptElementKind.variableElement; } } @@ -1117,7 +1129,7 @@ export function findListItemInfo(node: Node): ListItemInfo | undefined { return { listItemIndex, - list + list, }; } @@ -1317,24 +1329,28 @@ function getAdjustedLocation(node: Node, forRename: boolean): Node { // // NOTE: If the node is a modifier, we don't adjust its location if it is the `default` modifier as that is handled // specially by `getSymbolAtLocation`. - if (isModifier(node) && (forRename || node.kind !== SyntaxKind.DefaultKeyword) ? canHaveModifiers(parent) && contains(parent.modifiers, node) : - node.kind === SyntaxKind.ClassKeyword ? isClassDeclaration(parent) || isClassExpression(node) : + if ( + isModifier(node) && (forRename || node.kind !== SyntaxKind.DefaultKeyword) ? canHaveModifiers(parent) && contains(parent.modifiers, node) : + node.kind === SyntaxKind.ClassKeyword ? isClassDeclaration(parent) || isClassExpression(node) : node.kind === SyntaxKind.FunctionKeyword ? isFunctionDeclaration(parent) || isFunctionExpression(node) : - node.kind === SyntaxKind.InterfaceKeyword ? isInterfaceDeclaration(parent) : - node.kind === SyntaxKind.EnumKeyword ? isEnumDeclaration(parent) : - node.kind === SyntaxKind.TypeKeyword ? isTypeAliasDeclaration(parent) : - node.kind === SyntaxKind.NamespaceKeyword || node.kind === SyntaxKind.ModuleKeyword ? isModuleDeclaration(parent) : - node.kind === SyntaxKind.ImportKeyword ? isImportEqualsDeclaration(parent) : - node.kind === SyntaxKind.GetKeyword ? isGetAccessorDeclaration(parent) : - node.kind === SyntaxKind.SetKeyword && isSetAccessorDeclaration(parent)) { + node.kind === SyntaxKind.InterfaceKeyword ? isInterfaceDeclaration(parent) : + node.kind === SyntaxKind.EnumKeyword ? isEnumDeclaration(parent) : + node.kind === SyntaxKind.TypeKeyword ? isTypeAliasDeclaration(parent) : + node.kind === SyntaxKind.NamespaceKeyword || node.kind === SyntaxKind.ModuleKeyword ? isModuleDeclaration(parent) : + node.kind === SyntaxKind.ImportKeyword ? isImportEqualsDeclaration(parent) : + node.kind === SyntaxKind.GetKeyword ? isGetAccessorDeclaration(parent) : + node.kind === SyntaxKind.SetKeyword && isSetAccessorDeclaration(parent) + ) { const location = getAdjustedLocationForDeclaration(parent, forRename); if (location) { return location; } } // /**/ [|name|] ... - if ((node.kind === SyntaxKind.VarKeyword || node.kind === SyntaxKind.ConstKeyword || node.kind === SyntaxKind.LetKeyword) && - isVariableDeclarationList(parent) && parent.declarations.length === 1) { + if ( + (node.kind === SyntaxKind.VarKeyword || node.kind === SyntaxKind.ConstKeyword || node.kind === SyntaxKind.LetKeyword) && + isVariableDeclarationList(parent) && parent.declarations.length === 1 + ) { const decl = parent.declarations[0]; if (isIdentifier(decl.name)) { return decl.name; @@ -1367,10 +1383,12 @@ function getAdjustedLocation(node: Node, forRename: boolean): Node { // export { propertyName /**/as [|name|] } ... // export * /**/as [|name|] ... if (node.kind === SyntaxKind.AsKeyword) { - if (isImportSpecifier(parent) && parent.propertyName || + if ( + isImportSpecifier(parent) && parent.propertyName || isExportSpecifier(parent) && parent.propertyName || isNamespaceImport(parent) || - isNamespaceExport(parent)) { + isNamespaceExport(parent) + ) { return parent.name; } if (isExportDeclaration(parent) && parent.exportClause && isNamespaceExport(parent.exportClause)) { @@ -1445,13 +1463,17 @@ function getAdjustedLocation(node: Node, forRename: boolean): Node { return parent.name; } // /**/keyof [|T|] - if (node.kind === SyntaxKind.KeyOfKeyword && isTypeOperatorNode(parent) && parent.operator === SyntaxKind.KeyOfKeyword && - isTypeReferenceNode(parent.type)) { + if ( + node.kind === SyntaxKind.KeyOfKeyword && isTypeOperatorNode(parent) && parent.operator === SyntaxKind.KeyOfKeyword && + isTypeReferenceNode(parent.type) + ) { return parent.type.typeName; } // /**/readonly [|name|][] - if (node.kind === SyntaxKind.ReadonlyKeyword && isTypeOperatorNode(parent) && parent.operator === SyntaxKind.ReadonlyKeyword && - isArrayTypeNode(parent.type) && isTypeReferenceNode(parent.type.elementType)) { + if ( + node.kind === SyntaxKind.ReadonlyKeyword && isTypeOperatorNode(parent) && parent.operator === SyntaxKind.ReadonlyKeyword && + isArrayTypeNode(parent.type) && isTypeReferenceNode(parent.type.elementType) + ) { return parent.type.elementType.typeName; } if (!forRename) { @@ -1465,12 +1487,14 @@ function getAdjustedLocation(node: Node, forRename: boolean): Node { // /**/yield [|name|] // /**/yield obj.[|name|] // /**/delete obj.[|name|] - if (node.kind === SyntaxKind.NewKeyword && isNewExpression(parent) || + if ( + node.kind === SyntaxKind.NewKeyword && isNewExpression(parent) || node.kind === SyntaxKind.VoidKeyword && isVoidExpression(parent) || node.kind === SyntaxKind.TypeOfKeyword && isTypeOfExpression(parent) || node.kind === SyntaxKind.AwaitKeyword && isAwaitExpression(parent) || node.kind === SyntaxKind.YieldKeyword && isYieldExpression(parent) || - node.kind === SyntaxKind.DeleteKeyword && isDeleteExpression(parent)) { + node.kind === SyntaxKind.DeleteKeyword && isDeleteExpression(parent) + ) { if (parent.expression) { return skipOuterExpressions(parent.expression); } @@ -1486,8 +1510,10 @@ function getAdjustedLocation(node: Node, forRename: boolean): Node { } // for (... /**/in [|name|]) // for (... /**/of [|name|]) - if (node.kind === SyntaxKind.InKeyword && isForInStatement(parent) || - node.kind === SyntaxKind.OfKeyword && isForOfStatement(parent)) { + if ( + node.kind === SyntaxKind.InKeyword && isForInStatement(parent) || + node.kind === SyntaxKind.OfKeyword && isForOfStatement(parent) + ) { return skipOuterExpressions(parent.expression); } } @@ -1546,7 +1572,8 @@ export function getTokenAtPosition(sourceFile: SourceFile, position: number): No function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includePrecedingTokenAtEndPosition: ((n: Node) => boolean) | undefined, includeEndPosition: boolean): Node { let current: Node = sourceFile; let foundToken: Node | undefined; - outer: while (true) { + outer: + while (true) { // find the child that contains 'position' const children = current.getChildren(sourceFile); @@ -1572,7 +1599,6 @@ function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allo // kind. Meanwhile, if includePrecedingTokenAtEndPosition is unset, we look for the first node whose start is <= the // position and whose end is greater than the position. - // There are more sophisticated end tests later, but this one is very fast // and allows us to skip a bunch of work const end = children[middle].getEnd(); @@ -1661,7 +1687,6 @@ export function findFirstNonJsxWhitespaceToken(sourceFile: SourceFile, position: * fo|o -> will return foo * foo |bar -> will return foo * - * * @internal */ export function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node | undefined { @@ -1739,8 +1764,7 @@ export function findPrecedingToken(position: number, sourceFile: SourceFileLike, // 2) `position` is within the same span: we recurse on `child`. if (position < child.end) { const start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc); - const lookInPreviousChild = - (start >= position) || // cursor in the leading trivia + const lookInPreviousChild = (start >= position) || // cursor in the leading trivia !nodeHasTokens(child, sourceFile) || isWhiteSpaceOnlyJsxText(child); @@ -1833,7 +1857,6 @@ export function isInString(sourceFile: SourceFile, position: number, previousTok } /** - * * @internal */ export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number) { @@ -1901,14 +1924,16 @@ export function isInJSXText(sourceFile: SourceFile, position: number) { export function isInsideJsxElement(sourceFile: SourceFile, position: number): boolean { function isInsideJsxElementTraversal(node: Node): boolean { while (node) { - if (node.kind >= SyntaxKind.JsxSelfClosingElement && node.kind <= SyntaxKind.JsxExpression + if ( + node.kind >= SyntaxKind.JsxSelfClosingElement && node.kind <= SyntaxKind.JsxExpression || node.kind === SyntaxKind.JsxText || node.kind === SyntaxKind.LessThanToken || node.kind === SyntaxKind.GreaterThanToken || node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.CloseBraceToken || node.kind === SyntaxKind.OpenBraceToken - || node.kind === SyntaxKind.SlashToken) { + || node.kind === SyntaxKind.SlashToken + ) { node = node.parent; } else if (node.kind === SyntaxKind.JsxElement) { @@ -1971,7 +1996,7 @@ export function findPrecedingMatchingToken(token: Node, matchingTokenKind: Synta export function removeOptionality(type: Type, isOptionalExpression: boolean, isOptionalChain: boolean) { return isOptionalExpression ? type.getNonNullableType() : isOptionalChain ? type.getNonOptionalType() : - type; + type; } /** @internal */ @@ -2038,11 +2063,11 @@ export function getPossibleTypeArgumentsInfo(tokenIn: Node | undefined, sourceFi break; case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: - remainingLessThanTokens = + 3; + remainingLessThanTokens = +3; break; case SyntaxKind.GreaterThanGreaterThanToken: - remainingLessThanTokens = + 2; + remainingLessThanTokens = +2; break; case SyntaxKind.GreaterThanToken: @@ -2077,7 +2102,6 @@ export function getPossibleTypeArgumentsInfo(tokenIn: Node | undefined, sourceFi case SyntaxKind.EqualsGreaterThanToken: // falls through - case SyntaxKind.Identifier: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: @@ -2085,7 +2109,6 @@ export function getPossibleTypeArgumentsInfo(tokenIn: Node | undefined, sourceFi case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: // falls through - case SyntaxKind.TypeOfKeyword: case SyntaxKind.ExtendsKeyword: case SyntaxKind.KeyOfKeyword: @@ -2174,9 +2197,11 @@ export function isComment(kind: SyntaxKind): boolean { /** @internal */ export function isStringOrRegularExpressionOrTemplateLiteral(kind: SyntaxKind): boolean { - if (kind === SyntaxKind.StringLiteral + if ( + kind === SyntaxKind.StringLiteral || kind === SyntaxKind.RegularExpressionLiteral - || isTemplateLiteralKind(kind)) { + || isTemplateLiteralKind(kind) + ) { return true; } return false; @@ -2200,7 +2225,7 @@ export function isStringAndEmptyAnonymousObjectIntersection(type: Type) { /** @internal */ export function isInsideTemplateLiteral(node: TemplateLiteralToken, position: number, sourceFile: SourceFile): boolean { return isTemplateLiteralKind(node.kind) - && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); + && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); } /** @internal */ @@ -2224,20 +2249,26 @@ export function cloneCompilerOptions(options: CompilerOptions): CompilerOptions /** @internal */ export function isArrayLiteralOrObjectLiteralDestructuringPattern(node: Node) { - if (node.kind === SyntaxKind.ArrayLiteralExpression || - node.kind === SyntaxKind.ObjectLiteralExpression) { + if ( + node.kind === SyntaxKind.ArrayLiteralExpression || + node.kind === SyntaxKind.ObjectLiteralExpression + ) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === SyntaxKind.BinaryExpression && + if ( + node.parent.kind === SyntaxKind.BinaryExpression && (node.parent as BinaryExpression).left === node && - (node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { + (node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken + ) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === SyntaxKind.ForOfStatement && - (node.parent as ForOfStatement).initializer === node) { + if ( + node.parent.kind === SyntaxKind.ForOfStatement && + (node.parent as ForOfStatement).initializer === node + ) { return true; } @@ -2470,7 +2501,8 @@ export function makeImport(defaultImport: Identifier | undefined, namedImports: ? factory.createImportClause(!!isTypeOnly, defaultImport, namedImports && namedImports.length ? factory.createNamedImports(namedImports) : undefined) : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier, - /*assertClause*/ undefined); + /*assertClause*/ undefined, + ); } /** @internal */ @@ -2479,7 +2511,10 @@ export function makeStringLiteral(text: string, quotePreference: QuotePreference } /** @internal */ -export const enum QuotePreference { Single, Double } +export const enum QuotePreference { + Single, + Double, +} /** @internal */ export function quotePreferenceFromString(str: StringLiteral, sourceFile: SourceFile): QuotePreference { @@ -2502,9 +2537,12 @@ export function getQuotePreference(sourceFile: SourceFile, preferences: UserPref /** @internal */ export function getQuoteFromPreference(qp: QuotePreference): string { switch (qp) { - case QuotePreference.Single: return "'"; - case QuotePreference.Double: return '"'; - default: return Debug.assertNever(qp); + case QuotePreference.Single: + return "'"; + case QuotePreference.Double: + return '"'; + default: + return Debug.assertNever(qp); } } @@ -2532,11 +2570,12 @@ export function isModuleSpecifierLike(node: Node): node is StringLiteralLike { isExternalModuleReference(node.parent) || isImportDeclaration(node.parent) || isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) && node.parent.arguments[0] === node || - isImportCall(node.parent) && node.parent.arguments[0] === node); + isImportCall(node.parent) && node.parent.arguments[0] === node + ); } /** @internal */ -export type ObjectBindingElementWithoutPropertyName = BindingElement & { name: Identifier }; +export type ObjectBindingElementWithoutPropertyName = BindingElement & { name: Identifier; }; /** @internal */ export function isObjectBindingElementWithoutPropertyName(bindingElement: Node): bindingElement is ObjectBindingElementWithoutPropertyName { @@ -2593,7 +2632,7 @@ export function insertImports(changes: textChanges.ChangeTracker, sourceFile: So if (insertionIndex === 0) { // If the first import is top-of-file, insert after the leading comment which is likely the header. const options = existingImportStatements[0] === sourceFile.statements[0] ? - { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude } : {}; + { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude } : {}; changes.insertNodeBefore(sourceFile, existingImportStatements[0], newImport, /*blankLineBetween*/ false, options); } else { @@ -2684,7 +2723,7 @@ export function getMappedDocumentSpan(documentSpan: DocumentSpan, sourceMapper: originalFileName: documentSpan.fileName, originalTextSpan: documentSpan.textSpan, contextSpan: getMappedContextSpan(documentSpan, sourceMapper, fileExists), - originalContextSpan: documentSpan.contextSpan + originalContextSpan: documentSpan.contextSpan, }; } @@ -2693,12 +2732,12 @@ export function getMappedContextSpan(documentSpan: DocumentSpan, sourceMapper: S const contextSpanStart = documentSpan.contextSpan && getMappedLocation( { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, sourceMapper, - fileExists + fileExists, ); const contextSpanEnd = documentSpan.contextSpan && getMappedLocation( { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start + documentSpan.contextSpan.length }, sourceMapper, - fileExists + fileExists, ); return contextSpanStart && contextSpanEnd ? { start: contextSpanStart.pos, length: contextSpanEnd.pos - contextSpanStart.pos } : @@ -2712,8 +2751,7 @@ export function getMappedContextSpan(documentSpan: DocumentSpan, sourceMapper: S /** @internal */ export function isFirstDeclarationOfSymbolParameter(symbol: Symbol) { const declaration = symbol.declarations ? firstOrUndefined(symbol.declarations) : undefined; - return !!findAncestor(declaration, n => - isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); + return !!findAncestor(declaration, n => isParameter(n) ? true : isBindingElement(n) || isObjectBindingPattern(n) || isArrayBindingPattern(n) ? false : "quit"); } const displayPartWriter = getDisplayPartWriter(); @@ -2759,8 +2797,12 @@ function getDisplayPartWriter(): DisplayPartsSymbolWriter { hasTrailingComment: () => false, rawWrite: notImplemented, getIndent: () => indent, - increaseIndent: () => { indent++; }, - decreaseIndent: () => { indent--; }, + increaseIndent: () => { + indent++; + }, + decreaseIndent: () => { + indent--; + }, clear: resetWriter, }; @@ -3099,7 +3141,7 @@ export function getSynthesizedDeepClone(node: T, inc export function getSynthesizedDeepCloneWithReplacements( node: T, includeTrivia: boolean, - replaceNode: (node: Node) => Node | undefined + replaceNode: (node: Node) => Node | undefined, ): T { let clone = replaceNode(node); if (clone) { @@ -3120,15 +3162,13 @@ function getSynthesizedDeepCloneWorker(node: T, replaceNode?: (n const nodesClone: (ns: NodeArray | undefined) => NodeArray | undefined = replaceNode ? ns => ns && getSynthesizedDeepClonesWithReplacements(ns, /*includeTrivia*/ true, replaceNode) : ns => ns && getSynthesizedDeepClones(ns); - const visited = - visitEachChild(node, nodeClone, nullTransformationContext, nodesClone, nodeClone); + const visited = visitEachChild(node, nodeClone, nullTransformationContext, nodesClone, nodeClone); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - const clone = - isStringLiteral(node) ? setOriginalNode(factory.createStringLiteralFromNode(node), node) as Node as T : - isNumericLiteral(node) ? setOriginalNode(factory.createNumericLiteral(node.text, node.numericLiteralFlags), node) as Node as T : - factory.cloneNode(node); + const clone = isStringLiteral(node) ? setOriginalNode(factory.createStringLiteralFromNode(node), node) as Node as T : + isNumericLiteral(node) ? setOriginalNode(factory.createNumericLiteral(node.text, node.numericLiteralFlags), node) as Node as T : + factory.cloneNode(node); return setTextRange(clone, node); } @@ -3157,7 +3197,7 @@ export function getSynthesizedDeepClones(nodes: NodeArray | u export function getSynthesizedDeepClonesWithReplacements( nodes: NodeArray, includeTrivia: boolean, - replaceNode: (node: Node) => Node | undefined + replaceNode: (node: Node) => Node | undefined, ): NodeArray { return factory.createNodeArray(nodes.map(n => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma); } @@ -3269,7 +3309,6 @@ export function copyLeadingComments(sourceNode: Node, targetNode: Node, sourceFi forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment)); } - /** @internal */ export function copyTrailingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticTrailingComment)); @@ -3399,7 +3438,7 @@ export function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, progra reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, - moduleResolverHost: getModuleSpecifierResolverHost(program, host) + moduleResolverHost: getModuleSpecifierResolverHost(program, host), }); return typeIsAccessible ? res : undefined; } @@ -3448,7 +3487,8 @@ export const syntaxMayBeASICandidate = or( syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, syntaxRequiresTrailingModuleBlockOrSemicolonOrASI, - syntaxRequiresTrailingSemicolonOrASI); + syntaxRequiresTrailingSemicolonOrASI, +); function nodeIsASICandidate(node: Node, sourceFile: SourceFileLike): boolean { const lastToken = node.getLastToken(sourceFile); @@ -3608,7 +3648,7 @@ export function findPackageJson(directory: string, host: LanguageServiceHost): s let packageJson: string | undefined; forEachAncestorDirectory(directory, ancestor => { if (ancestor === "node_modules") return true; - packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + packageJson = findConfigFile(ancestor, f => tryFileExists(host, f), "package.json"); if (packageJson) { return true; // break out } @@ -3637,7 +3677,7 @@ export function getPackageJsonsVisibleToFile(fileName: string, host: LanguageSer } /** @internal */ -export function createPackageJsonInfo(fileName: string, host: { readFile?(fileName: string): string | undefined }): ProjectPackageJsonInfo | undefined { +export function createPackageJsonInfo(fileName: string, host: { readFile?(fileName: string): string | undefined; }): ProjectPackageJsonInfo | undefined { if (!host.readFile) { return undefined; } @@ -3706,7 +3746,7 @@ export interface PackageJsonImportFilter { export function createPackageJsonImportFilter(fromFile: SourceFile, preferences: UserPreferences, host: LanguageServiceHost): PackageJsonImportFilter { const packageJsons = ( (host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || getPackageJsonsVisibleToFile(fromFile.fileName, host) - ).filter(p => p.parseable); + ).filter(p => p.parseable); let usesNodeCoreModules: boolean | undefined; let ambientModuleCache: Map | undefined; @@ -3755,8 +3795,7 @@ export function createPackageJsonImportFilter(fromFile: SourceFile, preferences: return true; } - const result = - moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) || + const result = moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); ambientModuleCache.set(moduleSymbol, result); return result; @@ -4004,12 +4043,15 @@ function getSymbolParentOrFail(symbol: Symbol) { return Debug.checkDefined( symbol.parent, `Symbol parent was undefined. Flags: ${Debug.formatSymbolFlags(symbol.flags)}. ` + - `Declarations: ${symbol.declarations?.map(d => { - const kind = Debug.formatSyntaxKind(d.kind); - const inJS = isInJSFile(d); - const { expression } = d as any; - return (inJS ? "[JS]" : "") + kind + (expression ? ` (expression: ${Debug.formatSyntaxKind(expression.kind)})` : ""); - }).join(", ")}.`); + `Declarations: ${ + symbol.declarations?.map(d => { + const kind = Debug.formatSyntaxKind(d.kind); + const inJS = isInJSFile(d); + const { expression } = d as any; + return (inJS ? "[JS]" : "") + kind + (expression ? ` (expression: ${Debug.formatSyntaxKind(expression.kind)})` : ""); + }).join(", ") + }.`, + ); } /** diff --git a/src/testRunner/compilerRunner.ts b/src/testRunner/compilerRunner.ts index c11c2645b02b4..e4479bb390133 100644 --- a/src/testRunner/compilerRunner.ts +++ b/src/testRunner/compilerRunner.ts @@ -263,7 +263,7 @@ class CompilerTest { this.harnessSettings, /*options*/ tsConfigOptions, /*currentDirectory*/ this.harnessSettings.currentDirectory, - testCaseContent.symlinks + testCaseContent.symlinks, ); this.options = this.result.options; @@ -283,13 +283,13 @@ class CompilerTest { this.configuredName, this.tsConfigFiles.concat(this.toBeCompiled, this.otherFiles), this.result.diagnostics, - !!this.options.pretty); + !!this.options.pretty, + ); } public verifyModuleResolution() { if (this.options.traceResolution) { - Baseline.runBaseline(this.configuredName.replace(/\.tsx?$/, ".trace.json"), - JSON.stringify(this.result.traces.map(Utils.sanitizeTraceResolutionLogEntry), undefined, 4)); + Baseline.runBaseline(this.configuredName.replace(/\.tsx?$/, ".trace.json"), JSON.stringify(this.result.traces.map(Utils.sanitizeTraceResolutionLogEntry), undefined, 4)); } } @@ -314,7 +314,8 @@ class CompilerTest { this.tsConfigFiles, this.toBeCompiled, this.otherFiles, - this.harnessSettings); + this.harnessSettings, + ); } } @@ -323,7 +324,8 @@ class CompilerTest { this.configuredName, this.options, this.result, - this.harnessSettings); + this.harnessSettings, + ); } public verifyTypesAndSymbols() { @@ -331,8 +333,7 @@ class CompilerTest { return; } - const noTypesAndSymbols = - this.harnessSettings.noTypesAndSymbols && + const noTypesAndSymbols = this.harnessSettings.noTypesAndSymbols && this.harnessSettings.noTypesAndSymbols.toLowerCase() === "true"; if (noTypesAndSymbols) { return; @@ -347,7 +348,7 @@ class CompilerTest { /*multifile*/ undefined, /*skipTypeBaselines*/ undefined, /*skipSymbolBaselines*/ undefined, - !!ts.length(this.result.diagnostics) + !!ts.length(this.result.diagnostics), ); } @@ -355,7 +356,7 @@ class CompilerTest { return { unitName: unit.name, content: unit.content, - fileOptions: unit.fileOptions + fileOptions: unit.fileOptions, }; } } diff --git a/src/testRunner/parallel/host.ts b/src/testRunner/parallel/host.ts index b803324184558..126e06cff4e4a 100644 --- a/src/testRunner/parallel/host.ts +++ b/src/testRunner/parallel/host.ts @@ -79,7 +79,7 @@ export function start() { interface Worker { process: import("child_process").ChildProcess; accumulatedOutput: string; - currentTasks?: { file: string }[]; + currentTasks?: { file: string; }[]; timer?: any; } @@ -118,7 +118,7 @@ export function start() { incomplete, close, width, - noColors: options.noColors || false + noColors: options.noColors || false, }; this._progressBars = []; @@ -200,7 +200,7 @@ export function start() { return `${perfdataFileNameFragment}${target ? `.${target}` : ""}.json`; } - function readSavedPerfData(target?: string): { [testHash: string]: number } | undefined { + function readSavedPerfData(target?: string): { [testHash: string]: number; } | undefined { const perfDataContents = IO.readFile(perfdataFileName(target)); if (perfDataContents) { return JSON.parse(perfDataContents); @@ -212,7 +212,7 @@ export function start() { return `tsrunner-${runner}://${test}`; } - function startDelayed(perfData: { [testHash: string]: number } | undefined, totalCost: number) { + function startDelayed(perfData: { [testHash: string]: number; } | undefined, totalCost: number) { console.log(`Discovered ${tasks.length} unittest suites` + (newTasks.length ? ` and ${newTasks.length} new suites.` : ".")); console.log("Discovering runner-based tests..."); const discoverStart = +(new Date()); @@ -262,7 +262,7 @@ export function start() { let passingFiles = 0; let failingFiles = 0; let errorResults: ErrorInfo[] = []; - let passingResults: { name: string[] }[] = []; + let passingResults: { name: string[]; }[] = []; let totalPassing = 0; const startDate = new Date(); @@ -270,7 +270,7 @@ export function start() { const progressUpdateInterval = 1 / progressBars._options.width; let nextProgress = progressUpdateInterval; - const newPerfData: { [testHash: string]: number } = {}; + const newPerfData: { [testHash: string]: number; } = {}; const workers: Worker[] = []; let closedWorkers = 0; @@ -283,7 +283,7 @@ export function start() { process: fork(process.argv[1], [`--config="${configPath}"`], { stdio: ["pipe", "pipe", "pipe", "ipc"] }), accumulatedOutput: "", currentTasks: undefined, - timer: undefined + timer: undefined, }; const appendOutput = (d: Buffer) => { worker.accumulatedOutput += d.toString(); @@ -385,10 +385,11 @@ export function start() { // It's only really worth doing an initial batching if there are a ton of files to go through (and they have estimates) if (totalFiles > 1000 && batchSize > 0) { console.log("Batching initial test lists..."); - const batches: { runner: TestRunnerKind | "unittest", file: string, size: number }[][] = new Array(batchCount); + const batches: { runner: TestRunnerKind | "unittest"; file: string; size: number; }[][] = new Array(batchCount); const doneBatching = new Array(batchCount); let scheduledTotal = 0; - batcher: while (true) { + batcher: + while (true) { for (let i = 0; i < batchCount; i++) { if (tasks.length <= workerCount) { // Keep a small reserve even in the suboptimally packed case console.log(`Suboptimal packing detected: no tests remain to be stolen. Reduce packing fraction from ${packfraction} to fix.`); @@ -477,7 +478,7 @@ export function start() { percentComplete, progressColor, title, - titleColor + titleColor, ); } @@ -485,20 +486,29 @@ export function start() { function patchStats(stats: Mocha.Stats) { Object.defineProperties(stats, { start: { - configurable: true, enumerable: true, - get() { return startDate; }, - set(_: Date) { /*do nothing*/ } + configurable: true, + enumerable: true, + get() { + return startDate; + }, + set(_: Date) {/*do nothing*/}, }, end: { - configurable: true, enumerable: true, - get() { return endDate; }, - set(_: Date) { /*do nothing*/ } + configurable: true, + enumerable: true, + get() { + return endDate; + }, + set(_: Date) {/*do nothing*/}, }, duration: { - configurable: true, enumerable: true, - get() { return duration; }, - set(_: number) { /*do nothing*/ } - } + configurable: true, + enumerable: true, + get() { + return duration; + }, + set(_: number) {/*do nothing*/}, + }, }); } @@ -563,8 +573,8 @@ export function start() { xunitReporter = new Mocha.reporters.XUnit(replayRunner, { reporterOptions: { suiteName: "Tests", - output: "./TEST-results.xml" - } + output: "./TEST-results.xml", + }, }); patchStats(xunitReporter.stats); xunitReporter.write(`\n`); @@ -574,7 +584,7 @@ export function start() { reporterOptions: { file: path.resolve(".failed-tests"), keepFailed, - } + }, }); } diff --git a/src/testRunner/parallel/shared.ts b/src/testRunner/parallel/shared.ts index f645d2bc6024a..880f92f0c8e61 100644 --- a/src/testRunner/parallel/shared.ts +++ b/src/testRunner/parallel/shared.ts @@ -1,4 +1,6 @@ -import { TestRunnerKind } from "../_namespaces/Harness"; +import { + TestRunnerKind, +} from "../_namespaces/Harness"; import * as ts from "../_namespaces/ts"; export interface RunnerTask { @@ -55,7 +57,7 @@ export type ParallelHostMessage = ParallelTestMessage | ParallelCloseMessage | P export interface ParallelErrorMessage { type: "error"; - payload: { error: string, stack: string, name?: string[] }; + payload: { error: string; stack: string; name?: string[]; }; } export interface ParallelResultMessage { @@ -80,10 +82,10 @@ export function shimNoopTestInterface(global: Mocha.MochaGlobals) { global.after = ts.noop; global.beforeEach = ts.noop; global.afterEach = ts.noop; - global.describe = global.context = ((_: any, __: any) => { /*empty*/ }) as Mocha.SuiteFunction; + global.describe = global.context = ((_: any, __: any) => {/*empty*/}) as Mocha.SuiteFunction; global.describe.skip = global.xdescribe = global.xcontext = ts.noop as Mocha.PendingSuiteFunction; global.describe.only = ts.noop as Mocha.ExclusiveSuiteFunction; - global.it = global.specify = ((_: any, __: any) => { /*empty*/ }) as Mocha.TestFunction; + global.it = global.specify = ((_: any, __: any) => {/*empty*/}) as Mocha.TestFunction; global.it.skip = global.xit = global.xspecify = ts.noop as Mocha.PendingTestFunction; global.it.only = ts.noop as Mocha.ExclusiveTestFunction; } diff --git a/src/testRunner/parallel/worker.ts b/src/testRunner/parallel/worker.ts index e65020391f158..3637721240732 100644 --- a/src/testRunner/parallel/worker.ts +++ b/src/testRunner/parallel/worker.ts @@ -252,10 +252,14 @@ export function start() { */ function validateHostMessage(message: ParallelHostMessage) { switch (message.type) { - case "test": return validateTest(message.payload); - case "batch": return validateBatch(message.payload); - case "close": return true; - default: return false; + case "test": + return validateTest(message.payload); + case "batch": + return validateBatch(message.payload); + case "close": + return true; + default: + return false; } } @@ -280,9 +284,12 @@ export function start() { } switch (message.type) { - case "test": return processTest(message.payload, /*last*/ true); - case "batch": return processBatch(message.payload); - case "close": return process.exit(0); + case "test": + return processTest(message.payload, /*last*/ true); + case "batch": + return processBatch(message.payload); + case "close": + return process.exit(0); } } diff --git a/src/testRunner/projectsRunner.ts b/src/testRunner/projectsRunner.ts index bae70f81f6590..dd2a2f40f6ead 100644 --- a/src/testRunner/projectsRunner.ts +++ b/src/testRunner/projectsRunner.ts @@ -109,11 +109,13 @@ class ProjectParseConfigHost extends fakes.ParseConfigHost { public override readDirectory(path: string, extensions: string[], excludes: string[], includes: string[], depth: number): string[] { const result = super.readDirectory(path, extensions, excludes, includes, depth); const projectRoot = vpath.resolve(vfs.srcFolder, this._testCase.projectRoot); - return result.map(item => vpath.relative( - projectRoot, - vpath.resolve(projectRoot, item), - this.vfs.ignoreCase - )); + return result.map(item => + vpath.relative( + projectRoot, + vpath.resolve(projectRoot, item), + this.vfs.ignoreCase, + ) + ); } } @@ -208,7 +210,7 @@ class ProjectTestCase { return [ { name: `@module: commonjs`, payload: { testCase, moduleKind: ts.ModuleKind.CommonJS, vfs: fs } }, - { name: `@module: amd`, payload: { testCase, moduleKind: ts.ModuleKind.AMD, vfs: fs } } + { name: `@module: amd`, payload: { testCase, moduleKind: ts.ModuleKind.AMD, vfs: fs } }, ]; } @@ -219,8 +221,9 @@ class ProjectTestCase { 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) : - vpath.isAbsolute(input) ? vpath.relative(cwd, input, ignoreCase) : - input); + vpath.isAbsolute(input) ? vpath.relative(cwd, input, ignoreCase) : + input + ); resolutionInfo.emittedFiles = this.compilerResult.outputFiles! .map(output => output.meta.get("fileName") || output.file) @@ -318,11 +321,7 @@ class ProjectTestCase { return url; } - private compileProjectFiles(moduleKind: ts.ModuleKind, configFileSourceFiles: readonly ts.SourceFile[], - getInputFiles: () => readonly string[], - compilerHost: ts.CompilerHost, - compilerOptions: ts.CompilerOptions): CompileProjectFilesResult { - + private compileProjectFiles(moduleKind: ts.ModuleKind, configFileSourceFiles: readonly ts.SourceFile[], getInputFiles: () => readonly string[], compilerHost: ts.CompilerHost, compilerOptions: ts.CompilerOptions): CompileProjectFilesResult { const program = ts.createProgram(getInputFiles(), compilerOptions, compilerHost); const errors = ts.getPreEmitDiagnostics(program); @@ -334,7 +333,7 @@ class ProjectTestCase { data.sourceMap = { ...data.sourceMap, sources: data.sourceMap.sources.map(source => this.cleanProjectUrl(source)), - sourceRoot: data.sourceMap.sourceRoot && this.cleanProjectUrl(data.sourceMap.sourceRoot) + sourceRoot: data.sourceMap.sourceRoot && this.cleanProjectUrl(data.sourceMap.sourceRoot), }; } } @@ -344,7 +343,7 @@ class ProjectTestCase { moduleKind, program, errors: ts.concatenate(errors, emitDiagnostics), - sourceMapData + sourceMapData, }; } @@ -393,7 +392,7 @@ class ProjectTestCase { const _vfs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: allInputFiles, - cwd: vpath.combine(vfs.srcFolder, this.testCase.projectRoot) + cwd: vpath.combine(vfs.srcFolder, this.testCase.projectRoot), }); // Dont allow config files since we are compiling existing source options @@ -425,7 +424,7 @@ function getErrorsBaseline(compilerResult: CompileProjectFilesResult) { unitName: ts.isRootedDiskPath(sourceFile.fileName) ? Harness.RunnerBase.removeFullPaths(sourceFile.fileName) : sourceFile.fileName, - content: sourceFile.text + content: sourceFile.text, })); return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors); @@ -445,7 +444,7 @@ function createCompilerOptions(testCase: ProjectRunnerTestCase & ts.CompilerOpti sourceRoot: testCase.resolveSourceRoot && testCase.sourceRoot ? vpath.resolve(vfs.srcFolder, testCase.sourceRoot) - : testCase.sourceRoot + : testCase.sourceRoot, }; // Set the values specified using json diff --git a/src/testRunner/runner.ts b/src/testRunner/runner.ts index 3331be003e784..396c9da080b5b 100644 --- a/src/testRunner/runner.ts +++ b/src/testRunner/runner.ts @@ -81,12 +81,11 @@ const mytestconfigFileName = "mytest.config"; const testconfigFileName = "test.config"; const customConfig = tryGetConfig(IO.args()); -const testConfigContent = - customConfig && IO.fileExists(customConfig) - ? IO.readFile(customConfig)! - : IO.fileExists(mytestconfigFileName) - ? IO.readFile(mytestconfigFileName)! - : IO.fileExists(testconfigFileName) ? IO.readFile(testconfigFileName)! : ""; +const testConfigContent = customConfig && IO.fileExists(customConfig) + ? IO.readFile(customConfig)! + : IO.fileExists(mytestconfigFileName) + ? IO.readFile(mytestconfigFileName)! + : IO.fileExists(testconfigFileName) ? IO.readFile(testconfigFileName)! : ""; export let taskConfigsFolder: string; export let workerCount: number; @@ -232,7 +231,7 @@ function beginTests() { ts.Debug.loggingHost = { log(_level, s) { console.log(s || ""); - } + }, }; if (ts.Debug.isDebugging) { diff --git a/src/testRunner/unittests/asserts.ts b/src/testRunner/unittests/asserts.ts index 23d8e20a0df95..0656156e852c0 100644 --- a/src/testRunner/unittests/asserts.ts +++ b/src/testRunner/unittests/asserts.ts @@ -7,6 +7,6 @@ describe("unittests:: assert", () => { assert.deepEqual(ts.factory.createNodeArray([ts.factory.createIdentifier("A")], /*hasTrailingComma*/ true), ts.factory.createNodeArray([ts.factory.createIdentifier("A")], /*hasTrailingComma*/ true)); }); it("assertNever on string has correct error", () => { - assert.throws(() => ts.Debug.assertNever("hi" as never), "Debug Failure. Illegal value: \"hi\""); + assert.throws(() => ts.Debug.assertNever("hi" as never), 'Debug Failure. Illegal value: "hi"'); }); }); diff --git a/src/testRunner/unittests/builder.ts b/src/testRunner/unittests/builder.ts index 2c965e45323e0..65ad35bfd6c6c 100644 --- a/src/testRunner/unittests/builder.ts +++ b/src/testRunner/unittests/builder.ts @@ -81,7 +81,7 @@ describe("unittests:: builder", () => { }); function makeAssertChanges(getProgram: () => ts.Program): (fileNames: readonly string[]) => void { - const host: ts.BuilderProgramHost = { }; + const host: ts.BuilderProgramHost = {}; let builderProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram | undefined; return fileNames => { const program = getProgram(); @@ -95,7 +95,7 @@ function makeAssertChanges(getProgram: () => ts.Program): (fileNames: readonly s } function makeAssertChangesWithCancellationToken(getProgram: () => ts.Program): (fileNames: readonly string[], cancelAfterEmitLength?: number) => void { - const host: ts.BuilderProgramHost = { }; + const host: ts.BuilderProgramHost = {}; let builderProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram | undefined; let cancel = false; const cancellationToken: ts.CancellationToken = { @@ -118,7 +118,8 @@ function makeAssertChangesWithCancellationToken(getProgram: () => ts.Program): ( if (outputFileNames.length === cancelAfterEmitLength) { cancel = true; } - } while (builderProgram.emitNextAffectedFile(fileName => outputFileNames.push(fileName), cancellationToken)); + } + while (builderProgram.emitNextAffectedFile(fileName => outputFileNames.push(fileName), cancellationToken)); } catch (e) { assert.isFalse(operationWasCancelled); diff --git a/src/testRunner/unittests/canWatch.ts b/src/testRunner/unittests/canWatch.ts index cf6d005e097a4..1c0738e7aec94 100644 --- a/src/testRunner/unittests/canWatch.ts +++ b/src/testRunner/unittests/canWatch.ts @@ -1,5 +1,6 @@ - -import { Baseline } from "../_namespaces/Harness"; +import { + Baseline, +} from "../_namespaces/Harness"; import * as ts from "../_namespaces/ts"; describe("unittests:: canWatch::", () => { baselineCanWatch( @@ -195,4 +196,4 @@ describe("unittests:: canWatch::", () => { baseline.push(result); if (divider) baseline.push(divider); } -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 33a6ad5c24db9..cb40ec6527ac4 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -67,7 +67,7 @@ describe("unittests:: config:: commandLineParsing:: parseCommandLine", () => { describe("parses command line null for tsconfig only option", () => { interface VerifyNull { - subScenario: string, + subScenario: string; optionName: string; nonNullValue?: string; workerDiagnostic?: () => ts.ParseCommandLineWorkerDiagnostics; @@ -77,32 +77,32 @@ describe("unittests:: config:: commandLineParsing:: parseCommandLine", () => { assertParseResult( `${subScenario} allows setting it to null`, [`--${optionName}`, "null", "0.ts"], - workerDiagnostic + workerDiagnostic, ); if (nonNullValue) { assertParseResult( `${subScenario} errors if non null value is passed`, [`--${optionName}`, nonNullValue, "0.ts"], - workerDiagnostic + workerDiagnostic, ); } assertParseResult( `${subScenario} errors if its followed by another option`, ["0.ts", "--strictNullChecks", `--${optionName}`], - workerDiagnostic + workerDiagnostic, ); assertParseResult( `${subScenario} errors if its last option`, ["0.ts", `--${optionName}`], - workerDiagnostic + workerDiagnostic, ); }); } interface VerifyNullNonIncludedOption { - subScenario: string, + subScenario: string; type: () => "string" | "number" | Map; nonNullValue?: string; } @@ -121,14 +121,14 @@ describe("unittests:: config:: commandLineParsing:: parseCommandLine", () => { category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Enable_project_compilation, defaultValueDescription: undefined, - } + }, ]; return { ...ts.compilerOptionsDidYouMeanDiagnostics, optionDeclarations, - getOptionsNameMap: () => ts.createOptionNameMap(optionDeclarations) + getOptionsNameMap: () => ts.createOptionNameMap(optionDeclarations), }; - } + }, }); } @@ -158,22 +158,23 @@ describe("unittests:: config:: commandLineParsing:: parseCommandLine", () => { verifyNullNonIncludedOption({ subScenario: "option of type string", type: () => "string", - nonNullValue: "hello" + nonNullValue: "hello", }); verifyNullNonIncludedOption({ subScenario: "option of type number", type: () => "number", - nonNullValue: "10" + nonNullValue: "10", }); verifyNullNonIncludedOption({ subScenario: "option of type custom map", - type: () => new Map(Object.entries({ - node: ts.ModuleResolutionKind.Node10, - classic: ts.ModuleResolutionKind.Classic, - })), - nonNullValue: "node" + type: () => + new Map(Object.entries({ + node: ts.ModuleResolutionKind.Node10, + classic: ts.ModuleResolutionKind.Classic, + })), + nonNullValue: "node", }); }); diff --git a/src/testRunner/unittests/config/configurationExtension.ts b/src/testRunner/unittests/config/configurationExtension.ts index 6fe4159834589..96bfc206db8ca 100644 --- a/src/testRunner/unittests/config/configurationExtension.ts +++ b/src/testRunner/unittests/config/configurationExtension.ts @@ -2,7 +2,10 @@ import * as fakes from "../../_namespaces/fakes"; import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; import * as vfs from "../../_namespaces/vfs"; -import { baselineParseConfig, baselineParseConfigHost } from "./helpers"; +import { + baselineParseConfig, + baselineParseConfigHost, +} from "./helpers"; function createFileSystem(ignoreCase: boolean, cwd: string, root: string) { return new vfs.FileSystem(ignoreCase, { @@ -13,58 +16,58 @@ function createFileSystem(ignoreCase: boolean, cwd: string, root: string) { name: "@foo/tsconfig", version: "1.0.0", exports: { - ".": "./src/tsconfig.json" - } + ".": "./src/tsconfig.json", + }, }), "dev/node_modules/@foo/tsconfig/src/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true, - } + }, }), "dev/tsconfig.extendsFoo.json": JSON.stringify({ extends: "@foo/tsconfig", files: [ "main.ts", - ] + ], }), "dev/node_modules/config-box/package.json": JSON.stringify({ name: "config-box", version: "1.0.0", - tsconfig: "./strict.json" + tsconfig: "./strict.json", }), "dev/node_modules/config-box/strict.json": JSON.stringify({ compilerOptions: { strict: true, - } + }, }), "dev/node_modules/config-box/unstrict.json": JSON.stringify({ compilerOptions: { strict: false, - } + }, }), "dev/tsconfig.extendsBox.json": JSON.stringify({ extends: "config-box", files: [ "main.ts", - ] + ], }), "dev/tsconfig.extendsStrict.json": JSON.stringify({ extends: "config-box/strict", files: [ "main.ts", - ] + ], }), "dev/tsconfig.extendsUnStrict.json": JSON.stringify({ extends: "config-box/unstrict", files: [ "main.ts", - ] + ], }), "dev/tsconfig.extendsStrictExtension.json": JSON.stringify({ extends: "config-box/strict.json", files: [ "main.ts", - ] + ], }), "dev/node_modules/config-box-implied/package.json": JSON.stringify({ name: "config-box-implied", @@ -73,131 +76,131 @@ function createFileSystem(ignoreCase: boolean, cwd: string, root: string) { "dev/node_modules/config-box-implied/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true, - } + }, }), "dev/node_modules/config-box-implied/unstrict/tsconfig.json": JSON.stringify({ compilerOptions: { strict: false, - } + }, }), "dev/tsconfig.extendsBoxImplied.json": JSON.stringify({ extends: "config-box-implied", files: [ "main.ts", - ] + ], }), "dev/tsconfig.extendsBoxImpliedUnstrict.json": JSON.stringify({ extends: "config-box-implied/unstrict", files: [ "main.ts", - ] + ], }), "dev/tsconfig.extendsBoxImpliedUnstrictExtension.json": JSON.stringify({ extends: "config-box-implied/unstrict/tsconfig", files: [ "main.ts", - ] + ], }), "dev/tsconfig.extendsBoxImpliedPath.json": JSON.stringify({ extends: "config-box-implied/tsconfig.json", files: [ "main.ts", - ] + ], }), "dev/tsconfig.json": JSON.stringify({ extends: "./configs/base", files: [ "main.ts", - "supplemental.ts" - ] + "supplemental.ts", + ], }), "dev/tsconfig.nostrictnull.json": JSON.stringify({ extends: "./tsconfig", compilerOptions: { - strictNullChecks: false - } + strictNullChecks: false, + }, }), "dev/configs/base.json": JSON.stringify({ compilerOptions: { allowJs: true, noImplicitAny: true, - strictNullChecks: true - } + strictNullChecks: true, + }, }), "dev/configs/tests.json": JSON.stringify({ compilerOptions: { preserveConstEnums: true, removeComments: false, - sourceMap: true + sourceMap: true, }, exclude: [ "../tests/baselines", - "../tests/scenarios" + "../tests/scenarios", ], include: [ - "../tests/**/*.ts" - ] + "../tests/**/*.ts", + ], }), "dev/circular.json": JSON.stringify({ extends: "./circular2", compilerOptions: { - module: "amd" - } + module: "amd", + }, }), "dev/circular2.json": JSON.stringify({ extends: "./circular", compilerOptions: { - module: "commonjs" - } + module: "commonjs", + }, }), "dev/missing.json": JSON.stringify({ extends: "./missing2", compilerOptions: { - types: [] - } + types: [], + }, }), "dev/failure.json": JSON.stringify({ extends: "./failure2.json", compilerOptions: { - typeRoots: [] - } + typeRoots: [], + }, }), "dev/failure2.json": JSON.stringify({ - excludes: ["*.js"] + excludes: ["*.js"], }), "dev/configs/first.json": JSON.stringify({ extends: "./base", compilerOptions: { - module: "commonjs" + module: "commonjs", }, - files: ["../main.ts"] + files: ["../main.ts"], }), "dev/configs/second.json": JSON.stringify({ extends: "./base", compilerOptions: { - module: "amd" + module: "amd", }, - include: ["../supplemental.*"] + include: ["../supplemental.*"], }), "dev/configs/third.json": JSON.stringify({ extends: "./second", compilerOptions: { - module: null // eslint-disable-line no-null/no-null + module: null, // eslint-disable-line no-null/no-null }, - include: ["../supplemental.*"] + include: ["../supplemental.*"], }), "dev/configs/fourth.json": JSON.stringify({ extends: "./third", compilerOptions: { - module: "system" + module: "system", }, include: null, // eslint-disable-line no-null/no-null - files: ["../main.ts"] + files: ["../main.ts"], }), "dev/configs/fifth.json": JSON.stringify({ extends: "./fourth", include: ["../tests/utils.ts"], - files: [] + files: [], }), "dev/extends.json": JSON.stringify({ extends: 42 }), "dev/extends2.json": JSON.stringify({ extends: "configs/base" }), @@ -213,30 +216,30 @@ function createFileSystem(ignoreCase: boolean, cwd: string, root: string) { compilerOptions: { allowJs: true, noImplicitAny: true, - strictNullChecks: true - } + strictNullChecks: true, + }, }), "dev/configs/extendsArraySecond.json": JSON.stringify({ compilerOptions: { - module: "amd" + module: "amd", }, - include: ["../supplemental.*"] + include: ["../supplemental.*"], }), "dev/configs/extendsArrayThird.json": JSON.stringify({ compilerOptions: { module: null, // eslint-disable-line no-null/no-null - noImplicitAny: false + noImplicitAny: false, }, extends: "./extendsArrayFirst", - include: ["../supplemental.*"] + include: ["../supplemental.*"], }), "dev/configs/extendsArrayFourth.json": JSON.stringify({ compilerOptions: { module: "system", - strictNullChecks: false + strictNullChecks: false, }, include: null, // eslint-disable-line no-null/no-null - files: ["../main.ts"] + files: ["../main.ts"], }), "dev/configs/extendsArrayFifth.json": JSON.stringify({ extends: ["./extendsArrayFirst", "./extendsArraySecond", "./extendsArrayThird", "./extendsArrayFourth"], @@ -245,12 +248,12 @@ function createFileSystem(ignoreCase: boolean, cwd: string, root: string) { "dev/extendsArrayFails.json": JSON.stringify({ extends: ["./missingFile"], compilerOptions: { - types: [] - } + types: [], + }, }), "dev/extendsArrayFails2.json": JSON.stringify({ extends: [42] }), - } - } + }, + }, }); } @@ -263,7 +266,7 @@ const caseSensitiveHost = new fakes.ParseConfigHost(createFileSystem(/*ignoreCas describe("unittests:: config:: configurationExtension", () => { ts.forEach<[string, string, fakes.ParseConfigHost], void>([ ["under a case insensitive host", caseInsensitiveBasePath, caseInsensitiveHost], - ["under a case sensitive host", caseSensitiveBasePath, caseSensitiveHost] + ["under a case sensitive host", caseSensitiveBasePath, caseSensitiveHost], ], ([testName, basePath, host]) => { const nameAndEntry: [name: string, entry: string][] = []; function baselineParsedCommandLine(name: string, entry: string) { @@ -301,20 +304,21 @@ describe("unittests:: config:: configurationExtension", () => { baselineParseConfig({ scenario: "configurationExtension", subScenario: testName, - input: () => nameAndEntry.map(([name, entry]) => ({ - createHost: baseline => { - baseline.push(name); - return host; - }, - jsonText: host.readFile(entry)!, - configFileName: entry, - baselineParsed: (baseline, parsed) => { - baseline.push("CompilerOptions::"); - baseline.push(JSON.stringify(parsed.options, undefined, " ")); - baseline.push("FileNames::"); - baseline.push(parsed.fileNames.join()); - }, - })), + input: () => + nameAndEntry.map(([name, entry]) => ({ + createHost: baseline => { + baseline.push(name); + return host; + }, + jsonText: host.readFile(entry)!, + configFileName: entry, + baselineParsed: (baseline, parsed) => { + baseline.push("CompilerOptions::"); + baseline.push(JSON.stringify(parsed.options, undefined, " ")); + baseline.push("FileNames::"); + baseline.push(parsed.fileNames.join()); + }, + })), skipFs: true, header: baseline => baselineParseConfigHost(baseline, host), }); @@ -324,7 +328,7 @@ describe("unittests:: config:: configurationExtension", () => { const baseline: string[] = []; baselineParseConfigHost(baseline, host); baseline.push(`configFileName:: ${name}`); - const sourceFile = ts.readJsonConfigFile(entry, (path) => host.readFile(path)); + const sourceFile = ts.readJsonConfigFile(entry, path => host.readFile(path)); const dir = ts.combinePaths(basePath, "configs"); ts.parseJsonSourceFileConfigFileContent(sourceFile, host, dir, {}, ts.getBaseFileName(entry)); baseline.push("ExtendedSourceFiles::", ...sourceFile.extendedSourceFiles!); diff --git a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts index d636d07c4e449..aa0f4eb239d88 100644 --- a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts @@ -1,6 +1,8 @@ import * as fakes from "../../_namespaces/fakes"; import * as vfs from "../../_namespaces/vfs"; -import { baselineParseConfig } from "./helpers"; +import { + baselineParseConfig, +} from "./helpers"; describe("unittests:: config:: convertCompilerOptionsFromJson", () => { function baselineCompilerOptions(subScenario: string, json: any, configFileName: string) { @@ -17,17 +19,20 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { scenario: "convertCompilerOptionsFromJson", subScenario, input: () => [{ - createHost: () => new fakes.ParseConfigHost(new vfs.FileSystem( - /*ignoreCase*/ false, - { - cwd: "/apath/", - files: { - [`/apath/${configFileName}`]: jsonText, - "/apath/a.ts": "", - "/apath/b.js": "", - } - }, - )), + createHost: () => + new fakes.ParseConfigHost( + new vfs.FileSystem( + /*ignoreCase*/ false, + { + cwd: "/apath/", + files: { + [`/apath/${configFileName}`]: jsonText, + "/apath/a.ts": "", + "/apath/b.js": "", + }, + }, + ), + ), jsonText, configFileName, basePath: "/apath", @@ -44,8 +49,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - lib: ["es5", "es2015.core", "es2015.symbol"] - } + lib: ["es5", "es2015.core", "es2015.symbol"], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert correctly format tsconfig.json with allowJs is false to compiler-options", { @@ -55,8 +60,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { noImplicitAny: false, sourceMap: false, allowJs: false, - lib: ["es5", "es2015.core", "es2015.symbol"] - } + lib: ["es5", "es2015.core", "es2015.symbol"], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert incorrect option of jsx to compiler-options", { @@ -65,8 +70,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - jsx: "" - } + jsx: "", + }, }, "tsconfig.json"); baselineCompilerOptions("Convert incorrect option of module to compiler-options", { @@ -75,7 +80,7 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - } + }, }, "tsconfig.json"); baselineCompilerOptions("Convert incorrect option of newLine to compiler-options", { @@ -84,7 +89,7 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - } + }, }, "tsconfig.json"); baselineCompilerOptions("Convert incorrect option of target to compiler-options", { @@ -92,7 +97,7 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "", noImplicitAny: false, sourceMap: false, - } + }, }, "tsconfig.json"); baselineCompilerOptions("Convert incorrect option of module-resolution to compiler-options", { @@ -100,7 +105,7 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { moduleResolution: "", noImplicitAny: false, sourceMap: false, - } + }, }, "tsconfig.json"); baselineCompilerOptions("Convert incorrect option of libs to compiler-options", { @@ -109,8 +114,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - lib: ["es5", "es2015.core", "incorrectLib"] - } + lib: ["es5", "es2015.core", "incorrectLib"], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert empty string option of libs to compiler-options", { @@ -119,8 +124,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - lib: ["es5", ""] - } + lib: ["es5", ""], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert empty string option of libs array to compiler-options", { @@ -129,8 +134,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - lib: [""] - } + lib: [""], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert trailing-whitespace string option of libs to compiler-options", { @@ -139,8 +144,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - lib: [" "] - } + lib: [" "], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert empty option of libs to compiler-options", { @@ -149,38 +154,38 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - lib: [] - } + lib: [], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert empty string option of moduleSuffixes to compiler-options", { compilerOptions: { - moduleSuffixes: [".ios", ""] - } + moduleSuffixes: [".ios", ""], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert empty string option of moduleSuffixes single to compiler-options", { compilerOptions: { - moduleSuffixes: [""] - } + moduleSuffixes: [""], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert trailing-whitespace string option of moduleSuffixes to compiler-options", { compilerOptions: { - moduleSuffixes: [" "] - } + moduleSuffixes: [" "], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert empty option of moduleSuffixes to compiler-options", { compilerOptions: { - moduleSuffixes: [] - } + moduleSuffixes: [], + }, }, "tsconfig.json"); baselineCompilerOptions("Convert incorrectly format tsconfig.json to compiler-options", { compilerOptions: { modu: "commonjs", - } + }, }, "tsconfig.json"); baselineCompilerOptions("Convert default tsconfig.json to compiler-options", {}, "tsconfig.json"); @@ -188,8 +193,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { baselineCompilerOptions("Convert negative numbers in tsconfig.json", { compilerOptions: { allowJs: true, - maxNodeModuleJsDepth: -1 - } + maxNodeModuleJsDepth: -1, + }, }, "tsconfig.json"); // jsconfig.json @@ -199,8 +204,8 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { target: "es5", noImplicitAny: false, sourceMap: false, - lib: ["es5", "es2015.core", "es2015.symbol"] - } + lib: ["es5", "es2015.core", "es2015.symbol"], + }, }, "jsconfig.json"); baselineCompilerOptions("Convert correctly format jsconfig.json with allowJs is false to compiler-options", { @@ -210,19 +215,21 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { noImplicitAny: false, sourceMap: false, allowJs: false, - lib: ["es5", "es2015.core", "es2015.symbol"] - } + lib: ["es5", "es2015.core", "es2015.symbol"], + }, }, "jsconfig.json"); baselineCompilerOptions("Convert incorrectly format jsconfig.json to compiler-options", { compilerOptions: { modu: "commonjs", - } + }, }, "jsconfig.json"); baselineCompilerOptions("Convert default jsconfig.json to compiler-options", {}, "jsconfig.json"); - baselineCompilerOptionsJsonText("Convert tsconfig options when there are multiple invalid strings", `{ + baselineCompilerOptionsJsonText( + "Convert tsconfig options when there are multiple invalid strings", + `{ "compilerOptions": { "target": "<%- options.useTsWithBabel ? 'esnext' : 'es5' %>", "module": "esnext", @@ -242,41 +249,57 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { } } `, - "tsconfig.json"); + "tsconfig.json", + ); - baselineCompilerOptionsJsonText("Convert a tsconfig file with stray trailing characters", + baselineCompilerOptionsJsonText( + "Convert a tsconfig file with stray trailing characters", `{ "compilerOptions": { "target": "esnext" } - } blah`, "tsconfig.json"); + } blah`, + "tsconfig.json", + ); - baselineCompilerOptionsJsonText("Convert a tsconfig file with stray leading characters", + baselineCompilerOptionsJsonText( + "Convert a tsconfig file with stray leading characters", `blah { "compilerOptions": { "target": "esnext" } - }`, "tsconfig.json"); + }`, + "tsconfig.json", + ); - baselineCompilerOptionsJsonText("Convert a tsconfig file as an array", + baselineCompilerOptionsJsonText( + "Convert a tsconfig file as an array", `[{ "compilerOptions": { "target": "esnext" } - }]`, "tsconfig.json"); + }]`, + "tsconfig.json", + ); - baselineCompilerOptionsJsonText("raises an error if you've set a compiler flag in the root without including compilerOptions", + baselineCompilerOptionsJsonText( + "raises an error if you've set a compiler flag in the root without including compilerOptions", `{ "module": "esnext", - }`, "tsconfig.json"); + }`, + "tsconfig.json", + ); - baselineCompilerOptionsJsonText("does not raise an error if you've set a compiler flag in the root when you have included 'compilerOptions'", + baselineCompilerOptionsJsonText( + "does not raise an error if you've set a compiler flag in the root when you have included 'compilerOptions'", `{ "target": "esnext", "compilerOptions": { "module": "esnext" } - }`, "tsconfig.json"); + }`, + "tsconfig.json", + ); baselineCompilerOptionsJsonText("Don't crash when root expression is not object at all", `42`, "tsconfig.json"); diff --git a/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts b/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts index f506eab089061..a24e5f61b75d0 100644 --- a/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts +++ b/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts @@ -1,6 +1,8 @@ import * as fakes from "../../_namespaces/fakes"; import * as vfs from "../../_namespaces/vfs"; -import { baselineParseConfig } from "./helpers"; +import { + baselineParseConfig, +} from "./helpers"; describe("unittests:: config:: convertTypeAcquisitionFromJson", () => { function baselineTypeAcquisition(subScenario: string, json: any, configFileName: string) { @@ -10,17 +12,20 @@ describe("unittests:: config:: convertTypeAcquisitionFromJson", () => { input: () => { const jsonText = JSON.stringify(json, undefined, " "); return [{ - createHost: () => new fakes.ParseConfigHost(new vfs.FileSystem( - /*ignoreCase*/ false, - { - cwd: "/apath/", - files: { - [`/apath/${configFileName}`]: jsonText, - "/apath/a.ts": "", - "/apath/b.js": "", - } - }, - )), + createHost: () => + new fakes.ParseConfigHost( + new vfs.FileSystem( + /*ignoreCase*/ false, + { + cwd: "/apath/", + files: { + [`/apath/${configFileName}`]: jsonText, + "/apath/a.ts": "", + "/apath/b.js": "", + }, + }, + ), + ), jsonText, configFileName, basePath: "/apath", @@ -30,67 +35,48 @@ describe("unittests:: config:: convertTypeAcquisitionFromJson", () => { }); } - baselineTypeAcquisition("Convert correctly format tsconfig.json to typeAcquisition ", - { - typeAcquisition: - { - enable: true, - include: ["0.d.ts", "1.d.ts"], - exclude: ["0.js", "1.js"] - } + baselineTypeAcquisition("Convert correctly format tsconfig.json to typeAcquisition ", { + typeAcquisition: { + enable: true, + include: ["0.d.ts", "1.d.ts"], + exclude: ["0.js", "1.js"], }, - "tsconfig.json" - ); + }, "tsconfig.json"); - baselineTypeAcquisition("Convert incorrect format tsconfig.json to typeAcquisition ", - { - typeAcquisition: - { - enableAutoDiscovy: true, - } - }, "tsconfig.json", - ); + baselineTypeAcquisition("Convert incorrect format tsconfig.json to typeAcquisition ", { + typeAcquisition: { + enableAutoDiscovy: true, + }, + }, "tsconfig.json"); baselineTypeAcquisition("Convert default tsconfig.json to typeAcquisition ", {}, "tsconfig.json"); - baselineTypeAcquisition("Convert tsconfig.json with only enable property to typeAcquisition ", - { - typeAcquisition: - { - enable: true - } - }, "tsconfig.json", - ); + baselineTypeAcquisition("Convert tsconfig.json with only enable property to typeAcquisition ", { + typeAcquisition: { + enable: true, + }, + }, "tsconfig.json"); // jsconfig.json - baselineTypeAcquisition("Convert jsconfig.json to typeAcquisition ", - { - typeAcquisition: - { - enable: false, - include: ["0.d.ts"], - exclude: ["0.js"] - } - }, "jsconfig.json", - ); + baselineTypeAcquisition("Convert jsconfig.json to typeAcquisition ", { + typeAcquisition: { + enable: false, + include: ["0.d.ts"], + exclude: ["0.js"], + }, + }, "jsconfig.json"); baselineTypeAcquisition("Convert default jsconfig.json to typeAcquisition ", {}, "jsconfig.json"); - baselineTypeAcquisition("Convert incorrect format jsconfig.json to typeAcquisition ", - { - typeAcquisition: - { - enableAutoDiscovy: true, - } - }, "jsconfig.json", - ); + baselineTypeAcquisition("Convert incorrect format jsconfig.json to typeAcquisition ", { + typeAcquisition: { + enableAutoDiscovy: true, + }, + }, "jsconfig.json"); - baselineTypeAcquisition("Convert jsconfig.json with only enable property to typeAcquisition ", - { - typeAcquisition: - { - enable: false - } - }, "jsconfig.json", - ); + baselineTypeAcquisition("Convert jsconfig.json with only enable property to typeAcquisition ", { + typeAcquisition: { + enable: false, + }, + }, "jsconfig.json"); }); diff --git a/src/testRunner/unittests/config/helpers.ts b/src/testRunner/unittests/config/helpers.ts index 8c754e92e63a0..17cac54e7931a 100644 --- a/src/testRunner/unittests/config/helpers.ts +++ b/src/testRunner/unittests/config/helpers.ts @@ -51,7 +51,7 @@ export interface ParseConfigInput { createHost: (baseline: string[]) => fakes.ParseConfigHost; jsonText: string; configFileName: string; - basePath?: string, + basePath?: string; existingOptions?: ts.CompilerOptions; existingWatchOptions?: ts.WatchOptions; baselineParsed(baseline: string[], parsed: ts.ParsedCommandLine): void; @@ -102,4 +102,4 @@ function baselineParseConfigWith( Harness.Baseline.runBaseline(`config/${scenario}/${subScenario} ${jsonTest}.js`, baseline.join("\n")); }); }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/config/matchFiles.ts b/src/testRunner/unittests/config/matchFiles.ts index 33c21ff241011..172bf5f687351 100644 --- a/src/testRunner/unittests/config/matchFiles.ts +++ b/src/testRunner/unittests/config/matchFiles.ts @@ -1,108 +1,145 @@ import * as fakes from "../../_namespaces/fakes"; import * as ts from "../../_namespaces/ts"; import * as vfs from "../../_namespaces/vfs"; -import { baselineParseConfig } from "./helpers"; +import { + baselineParseConfig, +} from "./helpers"; const caseInsensitiveBasePath = "c:/dev/"; const caseInsensitiveTsconfigPath = "c:/dev/tsconfig.json"; -const caseInsensitiveHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: caseInsensitiveBasePath, files: { - "c:/dev/a.ts": "", - "c:/dev/a.d.ts": "", - "c:/dev/a.js": "", - "c:/dev/b.ts": "", - "c:/dev/b.js": "", - "c:/dev/c.d.ts": "", - "c:/dev/z/a.ts": "", - "c:/dev/z/abz.ts": "", - "c:/dev/z/aba.ts": "", - "c:/dev/z/b.ts": "", - "c:/dev/z/bbz.ts": "", - "c:/dev/z/bba.ts": "", - "c:/dev/x/a.ts": "", - "c:/dev/x/aa.ts": "", - "c:/dev/x/b.ts": "", - "c:/dev/x/y/a.ts": "", - "c:/dev/x/y/b.ts": "", - "c:/dev/js/a.js": "", - "c:/dev/js/b.js": "", - "c:/dev/js/d.min.js": "", - "c:/dev/js/ab.min.js": "", - "c:/ext/ext.ts": "", - "c:/ext/b/a..b.ts": "", -}})); +const caseInsensitiveHost = new fakes.ParseConfigHost( + new vfs.FileSystem(/*ignoreCase*/ true, { + cwd: caseInsensitiveBasePath, + files: { + "c:/dev/a.ts": "", + "c:/dev/a.d.ts": "", + "c:/dev/a.js": "", + "c:/dev/b.ts": "", + "c:/dev/b.js": "", + "c:/dev/c.d.ts": "", + "c:/dev/z/a.ts": "", + "c:/dev/z/abz.ts": "", + "c:/dev/z/aba.ts": "", + "c:/dev/z/b.ts": "", + "c:/dev/z/bbz.ts": "", + "c:/dev/z/bba.ts": "", + "c:/dev/x/a.ts": "", + "c:/dev/x/aa.ts": "", + "c:/dev/x/b.ts": "", + "c:/dev/x/y/a.ts": "", + "c:/dev/x/y/b.ts": "", + "c:/dev/js/a.js": "", + "c:/dev/js/b.js": "", + "c:/dev/js/d.min.js": "", + "c:/dev/js/ab.min.js": "", + "c:/ext/ext.ts": "", + "c:/ext/b/a..b.ts": "", + }, + }), +); const caseSensitiveBasePath = "/dev/"; -const caseSensitiveHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { cwd: caseSensitiveBasePath, files: { - "/dev/a.ts": "", - "/dev/a.d.ts": "", - "/dev/a.js": "", - "/dev/b.ts": "", - "/dev/b.js": "", - "/dev/A.ts": "", - "/dev/B.ts": "", - "/dev/c.d.ts": "", - "/dev/z/a.ts": "", - "/dev/z/abz.ts": "", - "/dev/z/aba.ts": "", - "/dev/z/b.ts": "", - "/dev/z/bbz.ts": "", - "/dev/z/bba.ts": "", - "/dev/x/a.ts": "", - "/dev/x/b.ts": "", - "/dev/x/y/a.ts": "", - "/dev/x/y/b.ts": "", - "/dev/q/a/c/b/d.ts": "", - "/dev/js/a.js": "", - "/dev/js/b.js": "", -}})); +const caseSensitiveHost = new fakes.ParseConfigHost( + new vfs.FileSystem(/*ignoreCase*/ false, { + cwd: caseSensitiveBasePath, + files: { + "/dev/a.ts": "", + "/dev/a.d.ts": "", + "/dev/a.js": "", + "/dev/b.ts": "", + "/dev/b.js": "", + "/dev/A.ts": "", + "/dev/B.ts": "", + "/dev/c.d.ts": "", + "/dev/z/a.ts": "", + "/dev/z/abz.ts": "", + "/dev/z/aba.ts": "", + "/dev/z/b.ts": "", + "/dev/z/bbz.ts": "", + "/dev/z/bba.ts": "", + "/dev/x/a.ts": "", + "/dev/x/b.ts": "", + "/dev/x/y/a.ts": "", + "/dev/x/y/b.ts": "", + "/dev/q/a/c/b/d.ts": "", + "/dev/js/a.js": "", + "/dev/js/b.js": "", + }, + }), +); -const caseInsensitiveMixedExtensionHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: caseInsensitiveBasePath, files: { - "c:/dev/a.ts": "", - "c:/dev/a.d.ts": "", - "c:/dev/a.js": "", - "c:/dev/b.tsx": "", - "c:/dev/b.d.ts": "", - "c:/dev/b.jsx": "", - "c:/dev/c.tsx": "", - "c:/dev/c.js": "", - "c:/dev/d.js": "", - "c:/dev/e.jsx": "", - "c:/dev/f.other": "", -}})); +const caseInsensitiveMixedExtensionHost = new fakes.ParseConfigHost( + new vfs.FileSystem(/*ignoreCase*/ true, { + cwd: caseInsensitiveBasePath, + files: { + "c:/dev/a.ts": "", + "c:/dev/a.d.ts": "", + "c:/dev/a.js": "", + "c:/dev/b.tsx": "", + "c:/dev/b.d.ts": "", + "c:/dev/b.jsx": "", + "c:/dev/c.tsx": "", + "c:/dev/c.js": "", + "c:/dev/d.js": "", + "c:/dev/e.jsx": "", + "c:/dev/f.other": "", + }, + }), +); -const caseInsensitiveCommonFoldersHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: caseInsensitiveBasePath, files: { - "c:/dev/a.ts": "", - "c:/dev/a.d.ts": "", - "c:/dev/a.js": "", - "c:/dev/b.ts": "", - "c:/dev/x/a.ts": "", - "c:/dev/node_modules/a.ts": "", - "c:/dev/bower_components/a.ts": "", - "c:/dev/jspm_packages/a.ts": "", -}})); +const caseInsensitiveCommonFoldersHost = new fakes.ParseConfigHost( + new vfs.FileSystem(/*ignoreCase*/ true, { + cwd: caseInsensitiveBasePath, + files: { + "c:/dev/a.ts": "", + "c:/dev/a.d.ts": "", + "c:/dev/a.js": "", + "c:/dev/b.ts": "", + "c:/dev/x/a.ts": "", + "c:/dev/node_modules/a.ts": "", + "c:/dev/bower_components/a.ts": "", + "c:/dev/jspm_packages/a.ts": "", + }, + }), +); -const caseInsensitiveDottedFoldersHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: caseInsensitiveBasePath, files: { - "c:/dev/x/d.ts": "", - "c:/dev/x/y/d.ts": "", - "c:/dev/x/y/.e.ts": "", - "c:/dev/x/.y/a.ts": "", - "c:/dev/.z/.b.ts": "", - "c:/dev/.z/c.ts": "", - "c:/dev/w/.u/e.ts": "", - "c:/dev/g.min.js/.g/g.ts": "", -}})); +const caseInsensitiveDottedFoldersHost = new fakes.ParseConfigHost( + new vfs.FileSystem(/*ignoreCase*/ true, { + cwd: caseInsensitiveBasePath, + files: { + "c:/dev/x/d.ts": "", + "c:/dev/x/y/d.ts": "", + "c:/dev/x/y/.e.ts": "", + "c:/dev/x/.y/a.ts": "", + "c:/dev/.z/.b.ts": "", + "c:/dev/.z/c.ts": "", + "c:/dev/w/.u/e.ts": "", + "c:/dev/g.min.js/.g/g.ts": "", + }, + }), +); -const caseInsensitiveOrderingDiffersWithCaseHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: caseInsensitiveBasePath, files: { - "c:/dev/xylophone.ts": "", - "c:/dev/Yosemite.ts": "", - "c:/dev/zebra.ts": "", -}})); +const caseInsensitiveOrderingDiffersWithCaseHost = new fakes.ParseConfigHost( + new vfs.FileSystem(/*ignoreCase*/ true, { + cwd: caseInsensitiveBasePath, + files: { + "c:/dev/xylophone.ts": "", + "c:/dev/Yosemite.ts": "", + "c:/dev/zebra.ts": "", + }, + }), +); -const caseSensitiveOrderingDiffersWithCaseHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { cwd: caseSensitiveBasePath, files: { - "/dev/xylophone.ts": "", - "/dev/Yosemite.ts": "", - "/dev/zebra.ts": "", -}})); +const caseSensitiveOrderingDiffersWithCaseHost = new fakes.ParseConfigHost( + new vfs.FileSystem(/*ignoreCase*/ false, { + cwd: caseSensitiveBasePath, + files: { + "/dev/xylophone.ts": "", + "/dev/Yosemite.ts": "", + "/dev/zebra.ts": "", + }, + }), +); function baselineMatches(subScenario: string, json: any, host: fakes.ParseConfigHost, basePath: string) { const jsonText = JSON.stringify(json, undefined, " "); @@ -117,12 +154,19 @@ function baselineMatches(subScenario: string, json: any, host: fakes.ParseConfig baselineParsed: (baseline, parsed) => { const wildcardDirectories = parsed.wildcardDirectories ? {} as ts.MapLike : undefined; if (parsed.wildcardDirectories) ts.getOwnKeys(parsed.wildcardDirectories).forEach(dir => wildcardDirectories![dir] = `WatchDirectoryFlags.${(ts as any).WatchDirectoryFlags[parsed.wildcardDirectories![dir]]}`); - baseline.push("Result", JSON.stringify({ - ...parsed, - errors: undefined, - wildcardDirectories, - }, undefined, " ")); - } + baseline.push( + "Result", + JSON.stringify( + { + ...parsed, + errors: undefined, + wildcardDirectories, + }, + undefined, + " ", + ), + ); + }, }], header: baseline => baseline.push("config:", jsonText), }); @@ -131,455 +175,755 @@ function baselineMatches(subScenario: string, json: any, host: fakes.ParseConfig describe("unittests:: config:: matchFiles", () => { baselineMatches("with defaults", {}, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); describe("with literal file list", () => { - baselineMatches("without exclusions with literal file list", { - files: [ - "a.ts", - "b.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("missing files are still present", { - files: [ - "z.ts", - "x.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("are not removed due to excludes", { - files: [ - "a.ts", - "b.ts" - ], - exclude: [ - "b.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); + baselineMatches( + "without exclusions with literal file list", + { + files: [ + "a.ts", + "b.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "missing files are still present", + { + files: [ + "z.ts", + "x.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "are not removed due to excludes", + { + files: [ + "a.ts", + "b.ts", + ], + exclude: [ + "b.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); }); describe("with literal include list", () => { - baselineMatches("without exclusions with literal include list", { - include: [ - "a.ts", - "b.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with non .ts file extensions are excluded", { - include: [ - "a.js", - "b.js" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with missing files are excluded with literal include list", { - include: [ - "z.ts", - "x.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with literal excludes", { - include: [ - "a.ts", - "b.ts" - ], - exclude: [ - "b.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with wildcard excludes", { - include: [ - "a.ts", - "b.ts", - "z/a.ts", - "z/abz.ts", - "z/aba.ts", - "x/b.ts" - ], - exclude: [ - "*.ts", - "z/??z.ts", - "*/b.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with recursive excludes", { - include: [ - "a.ts", - "b.ts", - "x/a.ts", - "x/b.ts", - "x/y/a.ts", - "x/y/b.ts" - ], - exclude: [ - "**/b.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with case sensitive exclude", { - include: [ - "B.ts" - ], - exclude: [ - "**/b.ts" - ] - }, caseSensitiveHost, caseSensitiveBasePath); - baselineMatches("with common package folders and no exclusions", { - include: [ - "a.ts", - "b.ts", - "node_modules/a.ts", - "bower_components/a.ts", - "jspm_packages/a.ts" - ] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - baselineMatches("with common package folders and exclusions", { - include: [ - "a.ts", - "b.ts", - "node_modules/a.ts", - "bower_components/a.ts", - "jspm_packages/a.ts" - ], - exclude: [ - "a.ts", - "b.ts" - ] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - baselineMatches("with common package folders and empty exclude", { - include: [ - "a.ts", - "b.ts", - "node_modules/a.ts", - "bower_components/a.ts", - "jspm_packages/a.ts" - ] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); + baselineMatches( + "without exclusions with literal include list", + { + include: [ + "a.ts", + "b.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with non .ts file extensions are excluded", + { + include: [ + "a.js", + "b.js", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with missing files are excluded with literal include list", + { + include: [ + "z.ts", + "x.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with literal excludes", + { + include: [ + "a.ts", + "b.ts", + ], + exclude: [ + "b.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with wildcard excludes", + { + include: [ + "a.ts", + "b.ts", + "z/a.ts", + "z/abz.ts", + "z/aba.ts", + "x/b.ts", + ], + exclude: [ + "*.ts", + "z/??z.ts", + "*/b.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with recursive excludes", + { + include: [ + "a.ts", + "b.ts", + "x/a.ts", + "x/b.ts", + "x/y/a.ts", + "x/y/b.ts", + ], + exclude: [ + "**/b.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with case sensitive exclude", + { + include: [ + "B.ts", + ], + exclude: [ + "**/b.ts", + ], + }, + caseSensitiveHost, + caseSensitiveBasePath, + ); + baselineMatches( + "with common package folders and no exclusions", + { + include: [ + "a.ts", + "b.ts", + "node_modules/a.ts", + "bower_components/a.ts", + "jspm_packages/a.ts", + ], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with common package folders and exclusions", + { + include: [ + "a.ts", + "b.ts", + "node_modules/a.ts", + "bower_components/a.ts", + "jspm_packages/a.ts", + ], + exclude: [ + "a.ts", + "b.ts", + ], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with common package folders and empty exclude", + { + include: [ + "a.ts", + "b.ts", + "node_modules/a.ts", + "bower_components/a.ts", + "jspm_packages/a.ts", + ], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); }); describe("with wildcard include list", () => { - baselineMatches("is sorted in include order, then in alphabetical order", { - include: [ - "z/*.ts", - "x/*.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("same named declarations are excluded", { - include: [ - "*.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("star matches only ts files", { - include: [ - "*" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("question matches only a single character", { - include: [ - "x/?.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with recursive directory", { - include: [ - "**/a.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with multiple recursive directories", { - include: [ - "x/y/**/a.ts", - "x/**/a.ts", - "z/**/a.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("case sensitive", { - include: [ - "**/A.ts" - ] - }, caseSensitiveHost, caseSensitiveBasePath); - baselineMatches("with missing files are excluded with wildcard include list", { - include: [ - "*/z.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("always include literal files", { - files: [ - "a.ts" - ], - include: [ - "*/z.ts" - ], - exclude: [ - "**/a.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("exclude folders", { - include: [ - "**/*" - ], - exclude: [ - "z", - "x" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - describe("with common package folders", () => { - baselineMatches("and no exclusions", { + baselineMatches( + "is sorted in include order, then in alphabetical order", + { include: [ - "**/a.ts" - ] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - baselineMatches("and exclusions", { + "z/*.ts", + "x/*.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "same named declarations are excluded", + { include: [ - "**/?.ts" + "*.ts", ], - exclude: [ - "a.ts" - ] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - baselineMatches("and empty exclude", { + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "star matches only ts files", + { include: [ - "**/a.ts" + "*", ], - exclude: [] as string[] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - baselineMatches("and explicit recursive include", { + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "question matches only a single character", + { + include: [ + "x/?.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with recursive directory", + { include: [ "**/a.ts", - "**/node_modules/a.ts" - ] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - baselineMatches("and wildcard include", { - include: [ - "*/a.ts" - ] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - baselineMatches("and explicit wildcard include", { - include: [ - "*/a.ts", - "node_modules/a.ts" - ] - }, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); - }); - baselineMatches("exclude .js files when allowJs=false", { - compilerOptions: { - allowJs: false - }, - include: [ - "js/*" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("include .js files when allowJs=true", { - compilerOptions: { - allowJs: true - }, - include: [ - "js/*" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("include explicitly listed .min.js files when allowJs=true", { - compilerOptions: { - allowJs: true - }, - include: [ - "js/*.min.js" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("include paths outside of the project", { - include: [ - "*", - "c:/ext/*" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("include paths outside of the project using relative paths", { - include: [ - "*", - "../ext/*" - ], - exclude: [ - "**" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("exclude paths outside of the project using relative paths", { - include: [ - "c:/**/*" - ], - exclude: [ - "../**" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("include files with .. in their name", { - include: [ - "c:/ext/b/a..b.ts" - ], - exclude: [ - "**" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("exclude files with .. in their name", { - include: [ - "c:/ext/**/*" - ], - exclude: [ - "c:/ext/b/a..b.ts" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("with jsx=none, allowJs=false", { - compilerOptions: { - allowJs: false - } - }, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - baselineMatches("with jsx=preserve, allowJs=false", { - compilerOptions: { - jsx: "preserve", - allowJs: false - } - }, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - baselineMatches("with jsx=react-native, allowJs=false", { - compilerOptions: { - jsx: "react-native", - allowJs: false - } - }, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - baselineMatches("with jsx=none, allowJs=true", { - compilerOptions: { - allowJs: true - } - }, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - baselineMatches("with jsx=preserve, allowJs=true", { - compilerOptions: { - jsx: "preserve", - allowJs: true - } - }, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - baselineMatches("with jsx=react-native, allowJs=true", { - compilerOptions: { - jsx: "react-native", - allowJs: true - } - }, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); - baselineMatches("exclude .min.js files using wildcards", { - compilerOptions: { - allowJs: true - }, - include: [ - "js/*.min.js" - ], - exclude: [ - "js/a*" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - - describe("with trailing recursive directory", () => { - baselineMatches("in includes with trailing recursive directory", { + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with multiple recursive directories", + { + include: [ + "x/y/**/a.ts", + "x/**/a.ts", + "z/**/a.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "case sensitive", + { include: [ - "**" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - baselineMatches("in excludes with trailing recursive directory", { + "**/A.ts", + ], + }, + caseSensitiveHost, + caseSensitiveBasePath, + ); + baselineMatches( + "with missing files are excluded with wildcard include list", + { include: [ - "**/*" + "*/z.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "always include literal files", + { + files: [ + "a.ts", + ], + include: [ + "*/z.ts", ], exclude: [ - "**" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - }); - describe("with multiple recursive directory patterns", () => { - baselineMatches("in includes with multiple recursive directory patterns", { + "**/a.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "exclude folders", + { include: [ - "**/x/**/*" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); + "**/*", + ], + exclude: [ + "z", + "x", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + describe("with common package folders", () => { + baselineMatches( + "and no exclusions", + { + include: [ + "**/a.ts", + ], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "and exclusions", + { + include: [ + "**/?.ts", + ], + exclude: [ + "a.ts", + ], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "and empty exclude", + { + include: [ + "**/a.ts", + ], + exclude: [] as string[], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "and explicit recursive include", + { + include: [ + "**/a.ts", + "**/node_modules/a.ts", + ], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "and wildcard include", + { + include: [ + "*/a.ts", + ], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "and explicit wildcard include", + { + include: [ + "*/a.ts", + "node_modules/a.ts", + ], + }, + caseInsensitiveCommonFoldersHost, + caseInsensitiveBasePath, + ); }); - baselineMatches("in excludes", { - include: [ - "**/a.ts" - ], - exclude: [ - "**/x/**" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - - describe("with parent directory symbols after a recursive directory pattern", () => { - baselineMatches("in includes immediately after", { + baselineMatches( + "exclude .js files when allowJs=false", + { + compilerOptions: { + allowJs: false, + }, include: [ - "**/../*" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - - baselineMatches("in includes after a subdirectory", { + "js/*", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "include .js files when allowJs=true", + { + compilerOptions: { + allowJs: true, + }, include: [ - "**/y/../*" - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); - - baselineMatches("in excludes immediately after", { + "js/*", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "include explicitly listed .min.js files when allowJs=true", + { + compilerOptions: { + allowJs: true, + }, + include: [ + "js/*.min.js", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "include paths outside of the project", + { + include: [ + "*", + "c:/ext/*", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "include paths outside of the project using relative paths", + { + include: [ + "*", + "../ext/*", + ], + exclude: [ + "**", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "exclude paths outside of the project using relative paths", + { include: [ - "**/a.ts" + "c:/**/*", ], exclude: [ - "**/.." - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); + "../**", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "include files with .. in their name", + { + include: [ + "c:/ext/b/a..b.ts", + ], + exclude: [ + "**", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "exclude files with .. in their name", + { + include: [ + "c:/ext/**/*", + ], + exclude: [ + "c:/ext/b/a..b.ts", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with jsx=none, allowJs=false", + { + compilerOptions: { + allowJs: false, + }, + }, + caseInsensitiveMixedExtensionHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with jsx=preserve, allowJs=false", + { + compilerOptions: { + jsx: "preserve", + allowJs: false, + }, + }, + caseInsensitiveMixedExtensionHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with jsx=react-native, allowJs=false", + { + compilerOptions: { + jsx: "react-native", + allowJs: false, + }, + }, + caseInsensitiveMixedExtensionHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with jsx=none, allowJs=true", + { + compilerOptions: { + allowJs: true, + }, + }, + caseInsensitiveMixedExtensionHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with jsx=preserve, allowJs=true", + { + compilerOptions: { + jsx: "preserve", + allowJs: true, + }, + }, + caseInsensitiveMixedExtensionHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with jsx=react-native, allowJs=true", + { + compilerOptions: { + jsx: "react-native", + allowJs: true, + }, + }, + caseInsensitiveMixedExtensionHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "exclude .min.js files using wildcards", + { + compilerOptions: { + allowJs: true, + }, + include: [ + "js/*.min.js", + ], + exclude: [ + "js/a*", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); - baselineMatches("in excludes after a subdirectory", { + describe("with trailing recursive directory", () => { + baselineMatches( + "in includes with trailing recursive directory", + { + include: [ + "**", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "in excludes with trailing recursive directory", + { + include: [ + "**/*", + ], + exclude: [ + "**", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + }); + describe("with multiple recursive directory patterns", () => { + baselineMatches( + "in includes with multiple recursive directory patterns", + { + include: [ + "**/x/**/*", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + }); + baselineMatches( + "in excludes", + { include: [ - "**/a.ts" + "**/a.ts", ], exclude: [ - "**/y/.." - ] - }, caseInsensitiveHost, caseInsensitiveBasePath); + "**/x/**", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + + describe("with parent directory symbols after a recursive directory pattern", () => { + baselineMatches( + "in includes immediately after", + { + include: [ + "**/../*", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + + baselineMatches( + "in includes after a subdirectory", + { + include: [ + "**/y/../*", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + + baselineMatches( + "in excludes immediately after", + { + include: [ + "**/a.ts", + ], + exclude: [ + "**/..", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); + + baselineMatches( + "in excludes after a subdirectory", + { + include: [ + "**/a.ts", + ], + exclude: [ + "**/y/..", + ], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); }); describe("with implicit globbification", () => { - baselineMatches("Expands z to z/starstart/star", { - include: ["z"] - }, caseInsensitiveHost, caseInsensitiveBasePath); + baselineMatches( + "Expands z to z/starstart/star", + { + include: ["z"], + }, + caseInsensitiveHost, + caseInsensitiveBasePath, + ); }); }); describe("with files or folders that begin with a .", () => { - baselineMatches("that are not explicitly included", { - include: [ - "x/**/*", - "w/*/*" - ] - }, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - describe("that are explicitly included", () => { - baselineMatches("without wildcards", { + baselineMatches( + "that are not explicitly included", + { include: [ - "x/.y/a.ts", - "c:/dev/.z/.b.ts" - ] - }, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - baselineMatches("with recursive wildcards that match directories", { - include: [ - "**/.*/*" - ] - }, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - baselineMatches("with recursive wildcards that match nothing", { - include: [ - "x/**/.y/*", - ".z/**/.*" - ] - }, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); - baselineMatches("with wildcard excludes that implicitly exclude dotted files", { - include: [ - "**/.*/*" + "x/**/*", + "w/*/*", ], - exclude: [ - "**/*" - ] - }, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); + }, + caseInsensitiveDottedFoldersHost, + caseInsensitiveBasePath, + ); + describe("that are explicitly included", () => { + baselineMatches( + "without wildcards", + { + include: [ + "x/.y/a.ts", + "c:/dev/.z/.b.ts", + ], + }, + caseInsensitiveDottedFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with recursive wildcards that match directories", + { + include: [ + "**/.*/*", + ], + }, + caseInsensitiveDottedFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with recursive wildcards that match nothing", + { + include: [ + "x/**/.y/*", + ".z/**/.*", + ], + }, + caseInsensitiveDottedFoldersHost, + caseInsensitiveBasePath, + ); + baselineMatches( + "with wildcard excludes that implicitly exclude dotted files", + { + include: [ + "**/.*/*", + ], + exclude: [ + "**/*", + ], + }, + caseInsensitiveDottedFoldersHost, + caseInsensitiveBasePath, + ); }); }); describe("exclude or include patterns which start with **", () => { - baselineMatches("can exclude dirs whose pattern starts with starstar", { - exclude: [ - "**/x" - ] - }, caseSensitiveHost, caseSensitiveBasePath); - baselineMatches("can include dirs whose pattern starts with starstart", { - include: [ - "**/x", - "**/a/**/b" - ] - }, caseSensitiveHost, caseSensitiveBasePath); + baselineMatches( + "can exclude dirs whose pattern starts with starstar", + { + exclude: [ + "**/x", + ], + }, + caseSensitiveHost, + caseSensitiveBasePath, + ); + baselineMatches( + "can include dirs whose pattern starts with starstart", + { + include: [ + "**/x", + "**/a/**/b", + ], + }, + caseSensitiveHost, + caseSensitiveBasePath, + ); }); baselineMatches("can include files in the same order on multiple platforms case sensitive", {}, caseSensitiveOrderingDiffersWithCaseHost, caseSensitiveBasePath); @@ -587,9 +931,10 @@ describe("unittests:: config:: matchFiles", () => { describe("when recursive symlinked directories are present", () => { const fs = new vfs.FileSystem(/*ignoreCase*/ true, { - cwd: caseInsensitiveBasePath, files: { - "c:/dev/index.ts": "" - } + cwd: caseInsensitiveBasePath, + files: { + "c:/dev/index.ts": "", + }, }); fs.mkdirpSync("c:/dev/a/b/c"); fs.symlinkSync("c:/dev/A", "c:/dev/a/self"); diff --git a/src/testRunner/unittests/config/showConfig.ts b/src/testRunner/unittests/config/showConfig.ts index 5b5a7bc12c4bc..f870707801cd3 100644 --- a/src/testRunner/unittests/config/showConfig.ts +++ b/src/testRunner/unittests/config/showConfig.ts @@ -11,16 +11,18 @@ describe("unittests:: config:: showConfig", () => { const configPath = ts.combinePaths(cwd, "tsconfig.json"); const configContents = configJson ? JSON.stringify(configJson) : undefined; const configParseHost: ts.ParseConfigFileHost = { - fileExists: path => - ts.comparePaths(ts.getNormalizedAbsolutePath(path, cwd), configPath) === ts.Comparison.EqualTo ? true : false, - getCurrentDirectory() { return cwd; }, + fileExists: path => ts.comparePaths(ts.getNormalizedAbsolutePath(path, cwd), configPath) === ts.Comparison.EqualTo ? true : false, + getCurrentDirectory() { + return cwd; + }, useCaseSensitiveFileNames: true, onUnRecoverableConfigFileDiagnostic: d => { throw new Error(ts.flattenDiagnosticMessageText(d.messageText, "\n")); }, - readDirectory() { return []; }, - readFile: path => - ts.comparePaths(ts.getNormalizedAbsolutePath(path, cwd), configPath) === ts.Comparison.EqualTo ? configContents : undefined, + readDirectory() { + return []; + }, + readFile: path => ts.comparePaths(ts.getNormalizedAbsolutePath(path, cwd), configPath) === ts.Comparison.EqualTo ? configContents : undefined, }; let commandLine = ts.parseCommandLine(commandLinesArgs); if (commandLine.options.project) { @@ -64,14 +66,14 @@ describe("unittests:: config:: showConfig", () => { }, compileOnSave: true, exclude: [ - "dist" + "dist", ], files: [], include: [ - "src/*" + "src/*", ], references: [ - { path: "./test" } + { path: "./test" }, ], }); @@ -92,25 +94,25 @@ describe("unittests:: config:: showConfig", () => { "@common/*": ["src/common/*"], "*": [ "node_modules/*", - "src/types/*" - ] + "src/types/*", + ], }, experimentalDecorators: true, emitDecoratorMetadata: true, - resolveJsonModule: true + resolveJsonModule: true, }, include: [ - "./src/**/*" - ] + "./src/**/*", + ], }); showTSConfigCorrectly("Show TSConfig with watch options", ["-p", "tsconfig.json"], { watchOptions: { - watchFile: "DynamicPriorityPolling" + watchFile: "DynamicPriorityPolling", }, include: [ - "./src/**/*" - ] + "./src/**/*", + ], }); // Bulk validation of all option declarations diff --git a/src/testRunner/unittests/config/tsconfigParsing.ts b/src/testRunner/unittests/config/tsconfigParsing.ts index ee32fe5b58d26..e0121594605c6 100644 --- a/src/testRunner/unittests/config/tsconfigParsing.ts +++ b/src/testRunner/unittests/config/tsconfigParsing.ts @@ -2,7 +2,9 @@ import * as fakes from "../../_namespaces/fakes"; import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; import * as vfs from "../../_namespaces/vfs"; -import { baselineParseConfig } from "./helpers"; +import { + baselineParseConfig, +} from "./helpers"; describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () => { function formatErrors(errors: readonly ts.Diagnostic[]) { @@ -38,26 +40,30 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () baselineParseConfig({ scenario: "tsconfigParsing", subScenario, - input: () => scenario().map(({ jsonText, configFileName, basePath, allFileList }) => ({ - createHost: () => { - const files = allFileList.reduce((files, value) => (files[value] = "", files), {} as vfs.FileSet); - files[ts.combinePaths(basePath, configFileName)] = jsonText; - return new fakes.ParseConfigHost(new vfs.FileSystem( - /*ignoreCase*/ false, - { - cwd: basePath, - files: { "/": {}, ...files } - })); - }, - jsonText, - configFileName, - basePath, - baselineParsed: (baseline, parsed) => { - baseline.push("FileNames::"); - baseline.push(parsed.fileNames.join()); - }, - })), - skipJson + input: () => + scenario().map(({ jsonText, configFileName, basePath, allFileList }) => ({ + createHost: () => { + const files = allFileList.reduce((files, value) => (files[value] = "", files), {} as vfs.FileSet); + files[ts.combinePaths(basePath, configFileName)] = jsonText; + return new fakes.ParseConfigHost( + new vfs.FileSystem( + /*ignoreCase*/ false, + { + cwd: basePath, + files: { "/": {}, ...files }, + }, + ), + ); + }, + jsonText, + configFileName, + basePath, + baselineParsed: (baseline, parsed) => { + baseline.push("FileNames::"); + baseline.push(parsed.fileNames.join()); + }, + })), + skipJson, }); } @@ -72,7 +78,7 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () ]); baselineParseResult("returns empty config when config is empty object", () => [ - "{}" + "{}", ]); baselineParseResult("returns config object without comments", () => [ @@ -166,14 +172,12 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () }]); baselinedParsed("exclude outDir unless overridden", () => { - const tsconfigWithoutExclude = - `{ + const tsconfigWithoutExclude = `{ "compilerOptions": { "outDir": "bin" } }`; - const tsconfigWithExclude = - `{ + const tsconfigWithExclude = `{ "compilerOptions": { "outDir": "bin" }, @@ -188,14 +192,12 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () }); baselinedParsed("exclude declarationDir unless overridden", () => { - const tsconfigWithoutExclude = - `{ + const tsconfigWithoutExclude = `{ "compilerOptions": { "declarationDir": "declarations" } }`; - const tsconfigWithExclude = - `{ + const tsconfigWithExclude = `{ "compilerOptions": { "declarationDir": "declarations" }, @@ -322,9 +324,9 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () files: [{ compilerOptions: { experimentalDecorators: true, - allowJs: true - } - }] + allowJs: true, + }, + }], }), configFileName: "/apath/tsconfig.json", basePath: "tests/cases/unittests", @@ -334,8 +336,8 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () baselinedParsed("generates errors when include is not string", () => [{ jsonText: JSON.stringify({ include: [ - ["./**/*.ts"] - ] + ["./**/*.ts"], + ], }), configFileName: "/apath/tsconfig.json", basePath: "tests/cases/unittests", @@ -346,32 +348,34 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () jsonText: JSON.stringify({ compilerOptions: { help: true, - } + }, }), configFileName: "/apath/tsconfig.json", basePath: "tests/cases/unittests", allFileList: ["/apath/a.ts"], }]); - function baselineWildcards(subScenario: string, scenario: () => { configFileName: string, jsonText: string, basePath: string }[]) { + function baselineWildcards(subScenario: string, scenario: () => { configFileName: string; jsonText: string; basePath: string; }[]) { baselineParseConfig({ scenario: "tsconfigParsing", subScenario, - input: () => scenario().map(({ jsonText, configFileName, basePath }) => ({ - createHost: () => new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ false, { - cwd: basePath, - files: { [configFileName]: jsonText } + input: () => + scenario().map(({ jsonText, configFileName, basePath }) => ({ + createHost: () => + new fakes.ParseConfigHost( + new vfs.FileSystem(/*ignoreCase*/ false, { + cwd: basePath, + files: { [configFileName]: jsonText }, + }), + ), + jsonText, + configFileName, + basePath, + baselineParsed: (baseline, parsed) => { + baseline.push("Wildcards::"); + ts.getOwnKeys(parsed.wildcardDirectories!).forEach(dir => baseline.push(`${dir}: WatchDirectoryFlags.${(ts as any).WatchDirectoryFlags[parsed.wildcardDirectories![dir]]}`)); + }, })), - jsonText, - configFileName, - basePath, - baselineParsed: (baseline, parsed) => { - baseline.push("Wildcards::"); - ts.getOwnKeys(parsed.wildcardDirectories!).forEach(dir => - baseline.push(`${dir}: WatchDirectoryFlags.${(ts as any).WatchDirectoryFlags[parsed.wildcardDirectories![dir]]}`) - ); - }, - })), skipErrors: true, }); } @@ -379,7 +383,7 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () baselineWildcards("parses wildcard directories even when parent directories have dots", () => [{ configFileName: "/foo.bar/tsconfig.json", jsonText: JSON.stringify({ - include: ["src"] + include: ["src"], }), basePath: "/foo.bar", }]); @@ -387,7 +391,7 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () baselineWildcards("correctly parses wild card directories from implicit glob when two keys differ only in directory seperator", () => [{ configFileName: "/foo.bar/tsconfig.json", jsonText: JSON.stringify({ - include: ["./", "./**/*.json"] + include: ["./", "./**/*.json"], }), basePath: "/foo", }]); diff --git a/src/testRunner/unittests/config/tsconfigParsingWatchOptions.ts b/src/testRunner/unittests/config/tsconfigParsingWatchOptions.ts index e87053dd5f546..10a6cf35c379d 100644 --- a/src/testRunner/unittests/config/tsconfigParsingWatchOptions.ts +++ b/src/testRunner/unittests/config/tsconfigParsingWatchOptions.ts @@ -1,7 +1,9 @@ import * as fakes from "../../_namespaces/fakes"; import * as ts from "../../_namespaces/ts"; import * as vfs from "../../_namespaces/vfs"; -import { baselineParseConfig } from "./helpers"; +import { + baselineParseConfig, +} from "./helpers"; describe("unittests:: config:: tsconfigParsingWatchOptions:: parseConfigFileTextToJson", () => { interface VerifyWatchOptions { @@ -14,31 +16,33 @@ describe("unittests:: config:: tsconfigParsingWatchOptions:: parseConfigFileText baselineParseConfig({ scenario: "tsconfigParsingWatchOptions", subScenario, - input: () => scenario().map(({ json, additionalFiles, existingWatchOptions }) => { - const jsonText = JSON.stringify(json, undefined, " "); - return { - createHost: () => new fakes.ParseConfigHost( - new vfs.FileSystem( - /*ignoreCase*/ false, - { - cwd: "/", - files: { - "/a.ts": "", - ...additionalFiles, - "/tsconfig.json": jsonText, - } - } - ) - ), - jsonText, - configFileName: "tsconfig.json", - existingWatchOptions, - baselineParsed: (baseline, parsed) => { - baseline.push(`Result: WatchOptions::`); - baseline.push(JSON.stringify(parsed.watchOptions, undefined, " ")); - }, - }; - }), + input: () => + scenario().map(({ json, additionalFiles, existingWatchOptions }) => { + const jsonText = JSON.stringify(json, undefined, " "); + return { + createHost: () => + new fakes.ParseConfigHost( + new vfs.FileSystem( + /*ignoreCase*/ false, + { + cwd: "/", + files: { + "/a.ts": "", + ...additionalFiles, + "/tsconfig.json": jsonText, + }, + }, + ), + ), + jsonText, + configFileName: "tsconfig.json", + existingWatchOptions, + baselineParsed: (baseline, parsed) => { + baseline.push(`Result: WatchOptions::`); + baseline.push(JSON.stringify(parsed.watchOptions, undefined, " ")); + }, + }; + }), }); } @@ -54,14 +58,14 @@ describe("unittests:: config:: tsconfigParsingWatchOptions:: parseConfigFileText { json: { extends: "./base.json", - watchOptions: { watchFile: "UseFsEvents" } + watchOptions: { watchFile: "UseFsEvents" }, }, - additionalFiles: { "/base.json": "{}" } + additionalFiles: { "/base.json": "{}" }, }, { - json: { extends: "./base.json", }, - additionalFiles: { "/base.json": "{}" } - } + json: { extends: "./base.json" }, + additionalFiles: { "/base.json": "{}" }, + }, ]); verifyWatchOptions("when extending config file with watchOptions", () => [ @@ -70,16 +74,16 @@ describe("unittests:: config:: tsconfigParsingWatchOptions:: parseConfigFileText extends: "./base.json", watchOptions: { watchFile: "UseFsEvents", - } + }, }, additionalFiles: { "/base.json": JSON.stringify({ watchOptions: { watchFile: "UseFsEventsOnParentDirectory", - watchDirectory: "FixedPollingInterval" - } - }) - } + watchDirectory: "FixedPollingInterval", + }, + }), + }, }, { json: { @@ -89,11 +93,11 @@ describe("unittests:: config:: tsconfigParsingWatchOptions:: parseConfigFileText "/base.json": JSON.stringify({ watchOptions: { watchFile: "UseFsEventsOnParentDirectory", - watchDirectory: "FixedPollingInterval" - } - }) - } - } + watchDirectory: "FixedPollingInterval", + }, + }), + }, + }, ]); verifyWatchOptions("different options", () => [ diff --git a/src/testRunner/unittests/customTransforms.ts b/src/testRunner/unittests/customTransforms.ts index c6cbf4391ed06..c401275203d63 100644 --- a/src/testRunner/unittests/customTransforms.ts +++ b/src/testRunner/unittests/customTransforms.ts @@ -2,21 +2,21 @@ import * as Harness from "../_namespaces/Harness"; import * as ts from "../_namespaces/ts"; describe("unittests:: customTransforms", () => { - function emitsCorrectly(name: string, sources: { file: string, text: string }[], customTransformers: ts.CustomTransformers, options: ts.CompilerOptions = {}) { + function emitsCorrectly(name: string, sources: { file: string; text: string; }[], customTransformers: ts.CustomTransformers, options: ts.CompilerOptions = {}) { it(name, () => { const roots = sources.map(source => ts.createSourceFile(source.file, source.text, ts.ScriptTarget.ES2015)); const fileMap = ts.arrayToMap(roots, file => file.fileName); const outputs = new Map(); const host: ts.CompilerHost = { - getSourceFile: (fileName) => fileMap.get(fileName), + getSourceFile: fileName => fileMap.get(fileName), getDefaultLibFileName: () => "lib.d.ts", getCurrentDirectory: () => "", getDirectories: () => [], - getCanonicalFileName: (fileName) => fileName, + getCanonicalFileName: fileName => fileName, useCaseSensitiveFileNames: () => true, getNewLine: () => "\n", - fileExists: (fileName) => fileMap.has(fileName), - readFile: (fileName) => fileMap.has(fileName) ? fileMap.get(fileName)!.text : undefined, + fileExists: fileName => fileMap.has(fileName), + readFile: fileName => fileMap.has(fileName) ? fileMap.get(fileName)!.text : undefined, writeFile: (fileName, text) => outputs.set(fileName, text), }; @@ -40,7 +40,7 @@ describe("unittests:: customTransforms", () => { enum e { } // leading function f2() { } // trailing - ` + `, }]; const before: ts.TransformerFactory = context => { @@ -86,84 +86,82 @@ describe("unittests:: customTransforms", () => { class B {} @dec export class C { constructor(b: B) { } } 'change' - ` - }], {before: [ - context => node => ts.visitNode(node, function visitor(node: ts.Node): ts.Node { - if (ts.isStringLiteral(node) && node.text === "change") return ts.factory.createStringLiteral("changed"); - return ts.visitEachChild(node, visitor, context); - }, ts.isSourceFile) - ]}, { + `, + }], { + before: [ + context => node => + ts.visitNode(node, function visitor(node: ts.Node): ts.Node { + if (ts.isStringLiteral(node) && node.text === "change") return ts.factory.createStringLiteral("changed"); + return ts.visitEachChild(node, visitor, context); + }, ts.isSourceFile), + ], + }, { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.ES2015, emitDecoratorMetadata: true, - experimentalDecorators: true + experimentalDecorators: true, }); - emitsCorrectly("sourceMapExternalSourceFiles", - [ - { - file: "source.ts", - // The text of length 'changed' is made to be on two lines so we know the line map change - text: `\`multi - line\` -'change'` - }, - ], + emitsCorrectly("sourceMapExternalSourceFiles", [ { - before: [ - context => node => ts.visitNode(node, function visitor(node: ts.Node): ts.Node { + file: "source.ts", + // The text of length 'changed' is made to be on two lines so we know the line map change + text: `\`multi + line\` +'change'`, + }, + ], { + before: [ + context => node => + ts.visitNode(node, function visitor(node: ts.Node): ts.Node { if (ts.isStringLiteral(node) && node.text === "change") { const text = "'changed'"; const lineMap = ts.computeLineStarts(text); ts.setSourceMapRange(node, { - pos: 0, end: text.length, source: { + pos: 0, + end: text.length, + source: { text, fileName: "another.html", lineMap, - getLineAndCharacterOfPosition: pos => ts.computeLineAndCharacterOfPosition(lineMap, pos) - } + getLineAndCharacterOfPosition: pos => ts.computeLineAndCharacterOfPosition(lineMap, pos), + }, }); return node; } return ts.visitEachChild(node, visitor, context); - }, ts.isSourceFile) - ] - }, - { sourceMap: true } - ); - - emitsCorrectly("skipTriviaExternalSourceFiles", - [ - { - file: "source.ts", - // The source file contains preceding trivia (e.g. whitespace) to try to confuse the `skipSourceTrivia` function. - text: " original;" - }, + }, ts.isSourceFile), ], + }, { sourceMap: true }); + + emitsCorrectly("skipTriviaExternalSourceFiles", [ { - before: [ - context => { - const transformSourceFile: ts.Transformer = node => ts.visitNode(node, function visitor(node: ts.Node): ts.Node { + file: "source.ts", + // The source file contains preceding trivia (e.g. whitespace) to try to confuse the `skipSourceTrivia` function. + text: " original;", + }, + ], { + before: [ + context => { + const transformSourceFile: ts.Transformer = node => + ts.visitNode(node, function visitor(node: ts.Node): ts.Node { if (ts.isIdentifier(node) && node.text === "original") { const newNode = ts.factory.createIdentifier("changed"); ts.setSourceMapRange(newNode, { pos: 0, end: 7, // Do not provide a custom skipTrivia function for `source`. - source: ts.createSourceMapSource("another.html", "changed;") + source: ts.createSourceMapSource("another.html", "changed;"), }); return newNode; } return ts.visitEachChild(node, visitor, context); }, ts.isSourceFile); - return { - transformSourceFile, - transformBundle: node => ts.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends), - }; - } - ] - }, - { sourceMap: true, outFile: "source.js" } - ); - + return { + transformSourceFile, + transformBundle: node => ts.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends), + }; + }, + ], + }, { sourceMap: true, outFile: "source.js" }); }); diff --git a/src/testRunner/unittests/debugDeprecation.ts b/src/testRunner/unittests/debugDeprecation.ts index 9dd3b0fee319f..c40943be0d37b 100644 --- a/src/testRunner/unittests/debugDeprecation.ts +++ b/src/testRunner/unittests/debugDeprecation.ts @@ -1,4 +1,6 @@ -import { deprecate } from "../../deprecatedCompat/deprecate"; +import { + deprecate, +} from "../../deprecatedCompat/deprecate"; import * as ts from "../_namespaces/ts"; describe("unittests:: debugDeprecation", () => { @@ -14,13 +16,13 @@ describe("unittests:: debugDeprecation", () => { it("silent deprecation", () => { const deprecation = deprecate(ts.noop, { warnAfter: "3.9", - typeScriptVersion: "3.8" + typeScriptVersion: "3.8", }); let logWritten = false; ts.Debug.loggingHost = { log() { logWritten = true; - } + }, }; deprecation(); assert.isFalse(logWritten); @@ -28,39 +30,39 @@ describe("unittests:: debugDeprecation", () => { it("warning deprecation with warnAfter", () => { const deprecation = deprecate(ts.noop, { warnAfter: "3.9", - typeScriptVersion: "3.9" + typeScriptVersion: "3.9", }); let logWritten = false; ts.Debug.loggingHost = { log() { logWritten = true; - } + }, }; deprecation(); assert.isTrue(logWritten); }); it("warning deprecation without warnAfter", () => { const deprecation = deprecate(ts.noop, { - typeScriptVersion: "3.9" + typeScriptVersion: "3.9", }); let logWritten = false; ts.Debug.loggingHost = { log() { logWritten = true; - } + }, }; deprecation(); assert.isTrue(logWritten); }); it("warning deprecation writes once", () => { const deprecation = deprecate(ts.noop, { - typeScriptVersion: "3.9" + typeScriptVersion: "3.9", }); let logWrites = 0; ts.Debug.loggingHost = { log() { logWrites++; - } + }, }; deprecation(); deprecation(); @@ -70,13 +72,13 @@ describe("unittests:: debugDeprecation", () => { const deprecation = deprecate(ts.noop, { warnAfter: "3.8", errorAfter: "3.9", - typeScriptVersion: "3.9" + typeScriptVersion: "3.9", }); let logWritten = false; ts.Debug.loggingHost = { log() { logWritten = true; - } + }, }; expect(deprecation).throws(); assert.isFalse(logWritten); @@ -89,7 +91,7 @@ describe("unittests:: debugDeprecation", () => { ts.Debug.loggingHost = { log() { logWritten = true; - } + }, }; expect(deprecation).throws(); assert.isFalse(logWritten); diff --git a/src/testRunner/unittests/evaluation/arraySpread.ts b/src/testRunner/unittests/evaluation/arraySpread.ts index e8f37ba755dde..cc871a76a2f46 100644 --- a/src/testRunner/unittests/evaluation/arraySpread.ts +++ b/src/testRunner/unittests/evaluation/arraySpread.ts @@ -35,7 +35,7 @@ describe("unittests:: evaluation:: arraySpread", () => { const o = f(3, ...k, 4); export const output = o; `); - assert.deepEqual(result.output, [3, 1, undefined, 2,4]); + assert.deepEqual(result.output, [3, 1, undefined, 2, 4]); assert.hasAllKeys(result.output, ["0", "1", "2", "3", "4"]); }); }); diff --git a/src/testRunner/unittests/evaluation/asyncGenerator.ts b/src/testRunner/unittests/evaluation/asyncGenerator.ts index d901223c86e46..a912a143ae537 100644 --- a/src/testRunner/unittests/evaluation/asyncGenerator.ts +++ b/src/testRunner/unittests/evaluation/asyncGenerator.ts @@ -13,25 +13,29 @@ describe("unittests:: evaluation:: asyncGeneratorEvaluation", () => { }`); await result.main(); assert.deepEqual(result.output, [ - { value: 0, done: true } + { value: 0, done: true }, ]); }); it("return (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` async function * g() { return Promise.resolve(0); } export const output: any[] = []; export async function main() { output.push(await g().next()); - }`, { target: ts.ScriptTarget.ES2015 }); + }`, + { target: ts.ScriptTarget.ES2015 }, + ); await result.main(); assert.deepEqual(result.output, [ - { value: 0, done: true } + { value: 0, done: true }, ]); }); it("yields in finally block with async delegator (es2017)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` async function* g1() { try { yield 1; @@ -48,12 +52,14 @@ describe("unittests:: evaluation:: asyncGeneratorEvaluation", () => { output.push(await it.next()); output.push(await it.return()); output.push(await it.next()); - }`, { target: ts.ScriptTarget.ES2017 }); + }`, + { target: ts.ScriptTarget.ES2017 }, + ); await result.main(); assert.deepEqual(result.output, [ { done: false, value: 1 }, { done: false, value: 2 }, - { done: true, value: undefined } + { done: true, value: undefined }, ]); }); }); diff --git a/src/testRunner/unittests/evaluation/autoAccessors.ts b/src/testRunner/unittests/evaluation/autoAccessors.ts index 0e73daf54f4b1..6f4d37587a3f7 100644 --- a/src/testRunner/unittests/evaluation/autoAccessors.ts +++ b/src/testRunner/unittests/evaluation/autoAccessors.ts @@ -9,11 +9,14 @@ describe("unittests:: evaluation:: autoAccessors", () => { for (const { name, target } of editions) { describe(name, () => { it("generates accessor pair", async () => { - const { C } = evaluator.evaluateTypeScript(` + const { C } = evaluator.evaluateTypeScript( + ` export class C { accessor x; } - `, { target }); + `, + { target }, + ); const desc = Object.getOwnPropertyDescriptor(C.prototype, "x"); assert.isDefined(desc); @@ -22,11 +25,14 @@ describe("unittests:: evaluation:: autoAccessors", () => { }); it("storage is private", async () => { - const { C } = evaluator.evaluateTypeScript(` + const { C } = evaluator.evaluateTypeScript( + ` export class C { accessor x; } - `, { target }); + `, + { target }, + ); const desc = Object.getOwnPropertyDescriptor(C.prototype, "x"); const obj = Object.create(C.prototype); @@ -34,11 +40,14 @@ describe("unittests:: evaluation:: autoAccessors", () => { }); it("getter and setter wrap same field", async () => { - const { C } = evaluator.evaluateTypeScript(` + const { C } = evaluator.evaluateTypeScript( + ` export class C { accessor x; } - `, { target }); + `, + { target }, + ); const obj = new C(); obj.x = 1; assert.equal(obj.x, 1); @@ -48,17 +57,21 @@ describe("unittests:: evaluation:: autoAccessors", () => { }); it("supports initializer", async () => { - const { C } = evaluator.evaluateTypeScript(` + const { C } = evaluator.evaluateTypeScript( + ` export class C { accessor x = 1; } - `, { target }); + `, + { target }, + ); const obj = new C(); assert.equal(obj.x, 1); }); it("legacy decorator can intercept getter/setter", async () => { - const { actions, C } = evaluator.evaluateTypeScript(` + const { actions, C } = evaluator.evaluateTypeScript( + ` function dec(target, key, descriptor) { const { get, set } = descriptor; actions.push({ kind: "decorate", target, key }); @@ -76,10 +89,12 @@ describe("unittests:: evaluation:: autoAccessors", () => { @dec accessor x; } - `, { target, experimentalDecorators: true }); + `, + { target, experimentalDecorators: true }, + ); assert.deepEqual(actions, [ - { kind: "decorate", target: C.prototype, key: "x" } + { kind: "decorate", target: C.prototype, key: "x" }, ]); const obj = new C(); obj.x = 1; @@ -92,7 +107,8 @@ describe("unittests:: evaluation:: autoAccessors", () => { }); it("legacy decorator cannot intercept initializer", async () => { - const { actions, C } = evaluator.evaluateTypeScript(` + const { actions, C } = evaluator.evaluateTypeScript( + ` function dec(target, key, descriptor) { const { get, set } = descriptor; descriptor.set = function(value) { @@ -105,7 +121,9 @@ describe("unittests:: evaluation:: autoAccessors", () => { @dec accessor x = 1; } - `, { target, experimentalDecorators: true }); + `, + { target, experimentalDecorators: true }, + ); const obj = new C(); assert.equal(obj.x, 1); @@ -113,4 +131,4 @@ describe("unittests:: evaluation:: autoAccessors", () => { }); }); } -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/evaluation/awaitUsingDeclarations.ts b/src/testRunner/unittests/evaluation/awaitUsingDeclarations.ts index c3e5c7e999637..aced8512f138f 100644 --- a/src/testRunner/unittests/evaluation/awaitUsingDeclarations.ts +++ b/src/testRunner/unittests/evaluation/awaitUsingDeclarations.ts @@ -7,7 +7,8 @@ function FakeSuppressedError(error: any, suppressed: any) { describe("unittests:: evaluation:: awaitUsingDeclarations", () => { it("'await using' in Block, normal completion (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -30,7 +31,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -40,12 +43,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "exit block", "disposed", - "after block" + "after block", ]); }); it("'await using' in Block, 'throw' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -72,7 +76,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -82,12 +88,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "disposed", "error", - "after try" + "after try", ]); }); it("'await using' in Block, 'throw' in dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -114,7 +121,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -125,12 +134,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "exit try", "disposed", "error", - "after try" + "after try", ]); }); it("'await using' in Block, 'throw' in body and dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -158,7 +168,10 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); await main(); @@ -169,14 +182,15 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "disposed", { error: "dispose error", - suppressed: "body error" + suppressed: "body error", }, - "after try" + "after try", ]); }); it("'await using' in Block, 'throw' in body and dispose, no global SuppressedError (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -204,7 +218,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -212,18 +228,20 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "before try", "enter try", "body", - "disposed"]); + "disposed", + ]); assert.instanceOf(output[4], Error); assert.strictEqual(output[4].name, "SuppressedError"); assert.strictEqual(output[4].error, "dispose error"); assert.strictEqual(output[4].suppressed, "body error"); assert.deepEqual(output.slice(5), [ - "after try" + "after try", ]); }); it("'await using' in Block, 'return' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -246,7 +264,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -254,12 +274,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "before block", "enter block", "body", - "disposed" + "disposed", ]); }); it("'await using' in Block, 'break' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -282,7 +303,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -291,12 +314,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter block", "body", "disposed", - "after block" + "after block", ]); }); it("'await using' in Block, 'continue' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -319,7 +343,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -331,12 +357,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter block", "body", "disposed", - "after block" + "after block", ]); }); it("'await using' in head of 'for', normal completion (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -359,7 +386,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -372,12 +401,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "exit loop", "disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for', 'throw' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -405,7 +435,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -415,12 +447,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "disposed", "error", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for', 'throw' in dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -448,7 +481,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -462,12 +497,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "exit loop", "disposed", "error", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for', 'throw' in body and dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -496,7 +532,10 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); await main(); @@ -507,14 +546,15 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "disposed", { error: "dispose error", - suppressed: "body error" + suppressed: "body error", }, - "after loop" + "after loop", ]); }); it("'await using' in head of 'for', 'return' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -537,7 +577,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -545,12 +587,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "before loop", "enter loop", "body", - "disposed" + "disposed", ]); }); it("'await using' in head of 'for', 'break' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -573,7 +616,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -582,12 +627,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter loop", "body", "disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for', 'continue' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -610,7 +656,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -621,12 +669,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter loop", "body", "disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for', multiple iterations (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -649,7 +698,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -662,12 +713,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "exit loop", "disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for-of', normal completion (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -696,7 +748,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -710,12 +764,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "exit loop", "b disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for-of', 'throw' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -750,7 +805,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -765,7 +822,8 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { }); it("'await using' in head of 'for-of', 'throw' in dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -800,7 +858,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -816,7 +876,8 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { }); it("'await using' in head of 'for-of', 'throw' in body and dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -852,7 +913,10 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); await main(); @@ -863,14 +927,15 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "a disposed", { error: "dispose error", - suppressed: "body error" + suppressed: "body error", }, "after loop", ]); }); it("'await using' in head of 'for-of', 'return' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -899,7 +964,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -912,7 +979,8 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { }); it("'await using' in head of 'for-of', 'break' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -941,7 +1009,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -950,12 +1020,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter loop", "body", "a disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for-of', 'continue' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -984,7 +1055,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -996,12 +1069,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter loop", "body", "b disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for-await-of', normal completion (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1030,7 +1104,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1044,12 +1120,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "exit loop", "b disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for-await-of', 'throw' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1084,7 +1161,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1099,7 +1178,8 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { }); it("'await using' in head of 'for-await-of', 'throw' in dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1134,7 +1214,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1150,7 +1232,8 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { }); it("'await using' in head of 'for-await-of', 'throw' in body and dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1186,7 +1269,10 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); await main(); @@ -1197,14 +1283,15 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "a disposed", { error: "dispose error", - suppressed: "body error" + suppressed: "body error", }, "after loop", ]); }); it("'await using' in head of 'for-await-of', 'return' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1233,7 +1320,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1246,7 +1335,8 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { }); it("'await using' in head of 'for-await-of', 'break' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1275,7 +1365,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1284,12 +1376,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter loop", "body", "a disposed", - "after loop" + "after loop", ]); }); it("'await using' in head of 'for-await-of', 'continue' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1318,7 +1411,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1330,12 +1425,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter loop", "body", "b disposed", - "after loop" + "after loop", ]); }); it("'await using' at top level of module (System)", async () => { - const { output, x, y } = await evaluator.evaluateTypeScript(` + const { output, x, y } = await evaluator.evaluateTypeScript( + ` export const output: any[] = []; output.push("before export x"); export const x = 1; @@ -1348,7 +1444,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { output.push("after using"); export const y = 2; output.push("after export y"); - `, { target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.System }); + `, + { target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.System }, + ); assert.strictEqual(x, 1); assert.strictEqual(y, 2); @@ -1357,12 +1455,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "before using", "after using", "after export y", - "disposed" + "disposed", ]); }); it("'await using' for 'null' value", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function body() { @@ -1379,7 +1478,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1388,12 +1489,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter block", "body", "exit block", - "after block" + "after block", ]); }); it("'await using' for 'undefined' value", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function body() { @@ -1410,7 +1512,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1419,12 +1523,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "enter block", "body", "exit block", - "after block" + "after block", ]); }); it("'await using' for sync disposable value", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -1447,7 +1552,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1457,12 +1564,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "exit block", "disposed", - "after block" + "after block", ]); }); it("'await using' for non-disposable value", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function body() { @@ -1479,7 +1587,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); try { await main(); @@ -1496,7 +1606,8 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { }); it("'await using' disposes in reverse order", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable_1 = { @@ -1524,7 +1635,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1535,12 +1648,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "exit block", "disposed_2", "disposed_1", - "after block" + "after block", ]); }); it("'await using' + 'using' disposes in reverse order", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable_1 = { @@ -1570,7 +1684,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1581,12 +1697,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "exit block", "disposed_2", "disposed_1", - "after block" + "after block", ]); }); it("'await using' forces await if null and evaluated", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function body() { @@ -1614,7 +1731,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { await p; } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1624,12 +1743,13 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { "body", "exit block", "interleave", - "after block" + "after block", ]); }); it("'await using' does not force await if null and not evaluated", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function body() { @@ -1658,7 +1778,9 @@ describe("unittests:: evaluation:: awaitUsingDeclarations", () => { await p; } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); diff --git a/src/testRunner/unittests/evaluation/destructuring.ts b/src/testRunner/unittests/evaluation/destructuring.ts index c52c4d4b0a61a..6a36f92fab830 100644 --- a/src/testRunner/unittests/evaluation/destructuring.ts +++ b/src/testRunner/unittests/evaluation/destructuring.ts @@ -5,63 +5,84 @@ describe("unittests:: evaluation:: destructuring", () => { // https://github.com/microsoft/TypeScript/issues/39205 describe("correct order for array destructuring evaluation and initializers", () => { it("when element is undefined", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const order = (n: any): any => output.push(n); let [{ [order(1)]: x } = order(0)] = []; - `, { target: ts.ScriptTarget.ES5 }); + `, + { target: ts.ScriptTarget.ES5 }, + ); assert.deepEqual(result.output, [0, 1]); }); it("when element is defined", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const order = (n: any): any => output.push(n); let [{ [order(1)]: x } = order(0)] = [{}]; - `, { target: ts.ScriptTarget.ES5 }); + `, + { target: ts.ScriptTarget.ES5 }, + ); assert.deepEqual(result.output, [1]); }); }); describe("correct order for array destructuring evaluation and initializers with spread", () => { it("ES5", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const order = (n: any): any => output.push(n); let { [order(0)]: { [order(2)]: z } = order(1), ...w } = {} as any; - `, { target: ts.ScriptTarget.ES5 }); + `, + { target: ts.ScriptTarget.ES5 }, + ); assert.deepEqual(result.output, [0, 1, 2]); }); it("ES2015", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const order = (n: any): any => output.push(n); let { [order(0)]: { [order(2)]: z } = order(1), ...w } = {} as any; - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.deepEqual(result.output, [0, 1, 2]); }); }); describe("correct evaluation for nested rest assignment in destructured object", () => { it("ES5", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let a: any, b: any, c: any = { x: { a: 1, y: 2 } }, d: any; ({ x: { a, ...b } = d } = c); export const output = { a, b }; - `, { target: ts.ScriptTarget.ES5 }); + `, + { target: ts.ScriptTarget.ES5 }, + ); assert.deepEqual(result.output, { a: 1, b: { y: 2 } }); }); it("ES2015", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let a: any, b: any, c: any = { x: { a: 1, y: 2 } }, d: any; ({ x: { a, ...b } = d } = c); export const output = { a, b }; - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.deepEqual(result.output, { a: 1, b: { y: 2 } }); }); it("ES2018", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let a: any, b: any, c: any = { x: { a: 1, y: 2 } }, d: any; ({ x: { a, ...b } = d } = c); export const output = { a, b }; - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); assert.deepEqual(result.output, { a: 1, b: { y: 2 } }); }); }); diff --git a/src/testRunner/unittests/evaluation/esDecorators.ts b/src/testRunner/unittests/evaluation/esDecorators.ts index 35be87f5a5c41..a4c12a2d7dad8 100644 --- a/src/testRunner/unittests/evaluation/esDecorators.ts +++ b/src/testRunner/unittests/evaluation/esDecorators.ts @@ -1,6 +1,8 @@ import * as evaluator from "../../_namespaces/evaluator"; import * as ts from "../../_namespaces/ts"; -import { ScriptTarget } from "../../_namespaces/ts"; +import { + ScriptTarget, +} from "../../_namespaces/ts"; describe("unittests:: evaluation:: esDecorators", () => { const options: ts.CompilerOptions = { target: ts.ScriptTarget.ES2021 }; @@ -739,7 +741,7 @@ describe("unittests:: evaluation:: esDecorators", () => { `; assert.isTrue(context.access.has(C)); assert.isTrue(context.access.has({ method() {} })); - assert.isFalse(context.access.has({ })); + assert.isFalse(context.access.has({})); }); it("test private element presence via .has", () => { const { context, C, D } = exec` @@ -754,7 +756,7 @@ describe("unittests:: evaluation:: esDecorators", () => { `; assert.isTrue(context.access.has(C)); assert.isFalse(context.access.has(D)); - assert.isFalse(context.access.has({ })); + assert.isFalse(context.access.has({})); }); it("read public element of argument", () => { const { context, C } = exec` @@ -809,9 +811,11 @@ describe("unittests:: evaluation:: esDecorators", () => { `; assert.isTrue(context.access.has(C)); assert.isTrue(context.access.has({ - get x() { return 2; } + get x() { + return 2; + }, })); - assert.isFalse(context.access.has({ })); + assert.isFalse(context.access.has({})); }); it("test private element presence via .has", () => { const { context, C, D } = exec` @@ -826,7 +830,7 @@ describe("unittests:: evaluation:: esDecorators", () => { `; assert.isTrue(context.access.has(C)); assert.isFalse(context.access.has(D)); - assert.isFalse(context.access.has({ })); + assert.isFalse(context.access.has({})); }); it("read public element of argument", () => { const { context, C } = exec` @@ -879,7 +883,7 @@ describe("unittests:: evaluation:: esDecorators", () => { `; assert.isTrue(context.access.has(C)); assert.isTrue(context.access.has({ x: 2 })); - assert.isFalse(context.access.has({ })); + assert.isFalse(context.access.has({})); }); it("test private element presence via .has", () => { const { context, C, D } = exec` @@ -953,7 +957,7 @@ describe("unittests:: evaluation:: esDecorators", () => { `; assert.isTrue(context.access.has(C)); assert.isTrue(context.access.has({ x: 2 })); - assert.isFalse(context.access.has({ })); + assert.isFalse(context.access.has({})); }); it("test private element presence via .has", () => { const { context, C, D } = exec` @@ -1036,7 +1040,7 @@ describe("unittests:: evaluation:: esDecorators", () => { `; assert.isTrue(context.access.has(C)); assert.isTrue(context.access.has({ x: 2 })); - assert.isFalse(context.access.has({ })); + assert.isFalse(context.access.has({})); }); it("test private element presence via .has", () => { const { context, C, D } = exec` @@ -1136,7 +1140,7 @@ describe("unittests:: evaluation:: esDecorators", () => { @((t, c) => { context = c; }) class C { } `; - assert.throws(() => context.addInitializer(() => { })); + assert.throws(() => context.addInitializer(() => {})); }); }); describe("for: method", () => { @@ -1186,7 +1190,7 @@ describe("unittests:: evaluation:: esDecorators", () => { static method() {} } `; - assert.throws(() => context.addInitializer(() => { })); + assert.throws(() => context.addInitializer(() => {})); }); describe("when: static", () => { it("extra initializers run once", () => { @@ -1267,7 +1271,7 @@ describe("unittests:: evaluation:: esDecorators", () => { static get x() { return 1; } } `; - assert.throws(() => context.addInitializer(() => { })); + assert.throws(() => context.addInitializer(() => {})); }); describe("when: static", () => { it("extra initializers run once", () => { @@ -1348,7 +1352,7 @@ describe("unittests:: evaluation:: esDecorators", () => { static set x(v: number) {} } `; - assert.throws(() => context.addInitializer(() => { })); + assert.throws(() => context.addInitializer(() => {})); }); describe("when: static", () => { it("extra initializers run once", () => { @@ -1429,7 +1433,7 @@ describe("unittests:: evaluation:: esDecorators", () => { static x: number; } `; - assert.throws(() => context.addInitializer(() => { })); + assert.throws(() => context.addInitializer(() => {})); }); describe("when: static", () => { it("extra initializers run once", () => { @@ -1510,7 +1514,7 @@ describe("unittests:: evaluation:: esDecorators", () => { static accessor x: number; } `; - assert.throws(() => context.addInitializer(() => { })); + assert.throws(() => context.addInitializer(() => {})); }); describe("when: static", () => { it("extra initializers run once", () => { @@ -2249,7 +2253,7 @@ describe("unittests:: evaluation:: esDecorators", () => { "post-super constructor evaluation", // and now evaluation has completed: - "done" + "done", ]); }); diff --git a/src/testRunner/unittests/evaluation/esDecoratorsMetadata.ts b/src/testRunner/unittests/evaluation/esDecoratorsMetadata.ts index 3a5a979d4895d..1c14cdcab233f 100644 --- a/src/testRunner/unittests/evaluation/esDecoratorsMetadata.ts +++ b/src/testRunner/unittests/evaluation/esDecoratorsMetadata.ts @@ -1,6 +1,8 @@ import * as evaluator from "../../_namespaces/evaluator"; import * as ts from "../../_namespaces/ts"; -import { ScriptTarget } from "../../_namespaces/ts"; +import { + ScriptTarget, +} from "../../_namespaces/ts"; describe("unittests:: evaluation:: esDecoratorsMetadata", () => { const nodeVersion = new ts.Version(process.versions.node); diff --git a/src/testRunner/unittests/evaluation/externalModules.ts b/src/testRunner/unittests/evaluation/externalModules.ts index 04a0b55abbf34..f6719764870bb 100644 --- a/src/testRunner/unittests/evaluation/externalModules.ts +++ b/src/testRunner/unittests/evaluation/externalModules.ts @@ -32,10 +32,10 @@ describe("unittests:: evaluation:: externalModules", () => { // 3 other.f(other); - ` + `, }, rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" + main: "/.src/main.ts", }); assert.equal(result.output[0], true); // `f(undefined)` inside module. Existing behavior is correct. assert.equal(result.output[1], true); // `f(undefined)` from import. New behavior to match first case. @@ -73,14 +73,14 @@ describe("unittests:: evaluation:: externalModules", () => { // 3 other.f(other); - ` + `, }, rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" + main: "/.src/main.ts", }); assert.equal(result.output[0], true); // `f(undefined)` inside module. Existing behavior is incorrect. assert.equal(result.output[1], true); // `f(undefined)` from import. New behavior to match first case. assert.equal(result.output[2], true); // `f.call(obj, obj)`. Behavior of `.call` (or `.apply`, etc.) should not be affected. assert.equal(result.output[3], true); // `other.f(other)`. `this` is still namespace because it is left of `.`. }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/evaluation/forAwaitOf.ts b/src/testRunner/unittests/evaluation/forAwaitOf.ts index ad5aba9c295f9..76b1f931c5540 100644 --- a/src/testRunner/unittests/evaluation/forAwaitOf.ts +++ b/src/testRunner/unittests/evaluation/forAwaitOf.ts @@ -3,7 +3,8 @@ import * as ts from "../../_namespaces/ts"; describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { it("sync (es5)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let i = 0; const iterator: IterableIterator = { [Symbol.iterator]() { return this; }, @@ -21,7 +22,9 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { for await (const item of iterator) { output.push(item); } - }`, { downlevelIteration: true }); + }`, + { downlevelIteration: true }, + ); await result.main(); assert.strictEqual(result.output[0], 1); assert.strictEqual(result.output[1], 2); @@ -29,7 +32,8 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { }); it("sync (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let i = 0; const iterator: IterableIterator = { [Symbol.iterator]() { return this; }, @@ -47,7 +51,9 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { for await (const item of iterator) { output.push(item); } - }`, { target: ts.ScriptTarget.ES2015 }); + }`, + { target: ts.ScriptTarget.ES2015 }, + ); await result.main(); assert.strictEqual(result.output[0], 1); assert.strictEqual(result.output[1], 2); @@ -55,7 +61,8 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { }); it("async (es5)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let i = 0; const iterator = { [Symbol.asyncIterator](): AsyncIterableIterator { return this; }, @@ -73,7 +80,9 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { for await (const item of iterator) { output.push(item); } - }`, { downlevelIteration: true }); + }`, + { downlevelIteration: true }, + ); await result.main(); assert.strictEqual(result.output[0], 1); assert.instanceOf(result.output[1], Promise); @@ -81,7 +90,8 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { }); it("async (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let i = 0; const iterator = { [Symbol.asyncIterator](): AsyncIterableIterator { return this; }, @@ -99,7 +109,9 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { for await (const item of iterator) { output.push(item); } - }`, { target: ts.ScriptTarget.ES2015 }); + }`, + { target: ts.ScriptTarget.ES2015 }, + ); await result.main(); assert.strictEqual(result.output[0], 1); assert.instanceOf(result.output[1], Promise); @@ -107,7 +119,8 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { }); it("call return when user code return (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let returnCalled = false; async function f() { const iterator = { @@ -127,12 +140,15 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { try { await f(); } catch { } return returnCalled; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.isTrue(await result.main()); }); it("call return when user code break (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let returnCalled = false; async function f() { const iterator = { @@ -152,12 +168,15 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { try { await f(); } catch { } return returnCalled; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.isTrue(await result.main()); }); it("call return when user code throws (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let returnCalled = false; async function f() { const iterator = { @@ -177,12 +196,15 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { try { await f(); } catch { } return returnCalled; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.isTrue(await result.main()); }); it("don't call return when non-user code throws (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let returnCalled = false; async function f() { let i = 0; @@ -204,12 +226,15 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { try { await f(); } catch { } return returnCalled; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.isFalse(await result.main()); }); it("don't call return when user code continue (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let returnCalled = false; async function f() { let i = 0; @@ -232,12 +257,15 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { try { await f(); } catch { } return returnCalled; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.isFalse(await result.main()); }); it("don't call return when user code continue to local label (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let returnCalled = false; async function f() { let i = 0; @@ -264,12 +292,15 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { try { await f(); } catch { } return returnCalled; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.isFalse(await result.main()); }); it("call return when user code continue to non-local label (es2015)", async () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` let returnCalled = false; async function f() { let i = 0; @@ -296,7 +327,9 @@ describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { try { await f(); } catch { } return returnCalled; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); assert.isTrue(await result.main()); }); }); diff --git a/src/testRunner/unittests/evaluation/forOf.ts b/src/testRunner/unittests/evaluation/forOf.ts index 5afe159495f54..8b2fd226770e8 100644 --- a/src/testRunner/unittests/evaluation/forOf.ts +++ b/src/testRunner/unittests/evaluation/forOf.ts @@ -3,7 +3,8 @@ import * as ts from "../../_namespaces/ts"; describe("unittests:: evaluation:: forOfEvaluation", () => { it("es5 over a array with no Symbol", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` Symbol = undefined; export var output = []; export function main() { @@ -13,18 +14,20 @@ describe("unittests:: evaluation:: forOfEvaluation", () => { output.push(value); } } - `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + `, + { downlevelIteration: true, target: ts.ScriptTarget.ES5 }, + ); result.main(); assert.strictEqual(result.output[0], 1); assert.strictEqual(result.output[1], 2); assert.strictEqual(result.output[2], 3); - }); it("es5 over a string with no Symbol", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` Symbol = undefined; export var output = []; export function main() { @@ -34,7 +37,9 @@ describe("unittests:: evaluation:: forOfEvaluation", () => { output.push(value); } } - `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + `, + { downlevelIteration: true, target: ts.ScriptTarget.ES5 }, + ); result.main(); @@ -46,7 +51,8 @@ describe("unittests:: evaluation:: forOfEvaluation", () => { }); it("es5 over undefined with no Symbol", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` Symbol = undefined; export function main() { let x = undefined; @@ -54,26 +60,32 @@ describe("unittests:: evaluation:: forOfEvaluation", () => { for (let value of x) { } } - `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + `, + { downlevelIteration: true, target: ts.ScriptTarget.ES5 }, + ); assert.throws(() => result.main(), "Symbol.iterator is not defined"); }); it("es5 over undefined with Symbol", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { let x = undefined; for (let value of x) { } } - `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + `, + { downlevelIteration: true, target: ts.ScriptTarget.ES5 }, + ); assert.throws(() => result.main(), /cannot read property.*Symbol\(Symbol\.iterator\).*/i); }); it("es5 over object with no Symbol.iterator with no Symbol", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` Symbol = undefined; export function main() { let x = {} as any; @@ -81,26 +93,32 @@ describe("unittests:: evaluation:: forOfEvaluation", () => { for (let value of x) { } } - `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + `, + { downlevelIteration: true, target: ts.ScriptTarget.ES5 }, + ); assert.throws(() => result.main(), "Symbol.iterator is not defined"); }); it("es5 over object with no Symbol.iterator with Symbol", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { let x = {} as any; for (let value of x) { } } - `, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + `, + { downlevelIteration: true, target: ts.ScriptTarget.ES5 }, + ); assert.throws(() => result.main(), "Object is not iterable"); }); it("es5 over object with Symbol.iterator", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export var output = []; export function main() { let thing : any = {}; @@ -114,9 +132,10 @@ describe("unittests:: evaluation:: forOfEvaluation", () => { output.push(value) } - }`, { downlevelIteration: true, target: ts.ScriptTarget.ES5 }); + }`, + { downlevelIteration: true, target: ts.ScriptTarget.ES5 }, + ); result.main(); }); - -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/evaluation/generator.ts b/src/testRunner/unittests/evaluation/generator.ts index 3d04fe189172c..676b9ff699750 100644 --- a/src/testRunner/unittests/evaluation/generator.ts +++ b/src/testRunner/unittests/evaluation/generator.ts @@ -3,14 +3,17 @@ import * as ts from "../../_namespaces/ts"; describe("unittests:: evaluation:: generatorEvaluation", () => { it("throw before start (es5)", () => { - const { gen, output } = evaluator.evaluateTypeScript(` + const { gen, output } = evaluator.evaluateTypeScript( + ` export const output: string[] = []; export function * gen() { output.push("start"); yield 1; output.push("end"); } - `, { target: ts.ScriptTarget.ES5 }); + `, + { target: ts.ScriptTarget.ES5 }, + ); const g = gen(); const e = new Error(); @@ -19,14 +22,17 @@ describe("unittests:: evaluation:: generatorEvaluation", () => { assert.deepEqual(output, []); }); it("return before start (es5)", () => { - const { gen, output } = evaluator.evaluateTypeScript(` + const { gen, output } = evaluator.evaluateTypeScript( + ` export const output: string[] = []; export function * gen() { output.push("start"); yield 1; output.push("end"); } - `, { target: ts.ScriptTarget.ES5 }); + `, + { target: ts.ScriptTarget.ES5 }, + ); const g = gen(); assert.deepEqual(g.return(2), { value: 2, done: true }); diff --git a/src/testRunner/unittests/evaluation/superInStaticInitializer.ts b/src/testRunner/unittests/evaluation/superInStaticInitializer.ts index b6d858c69e72f..c5e2f84b4eb0b 100644 --- a/src/testRunner/unittests/evaluation/superInStaticInitializer.ts +++ b/src/testRunner/unittests/evaluation/superInStaticInitializer.ts @@ -3,7 +3,8 @@ import * as ts from "../../_namespaces/ts"; describe("unittests:: evaluation:: superInStaticInitializer", () => { it("super-property-get in es2015", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { class Base { static x = 1; @@ -16,13 +17,16 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { Derived ]; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); const [Base, Derived] = result.main(); assert.strictEqual(Base.x, 1); assert.strictEqual(Derived.y, 1); }); it("super-property-set in es2015", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { class Base { static x = 1; @@ -35,14 +39,17 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { Derived ]; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); const [Base, Derived] = result.main(); assert.strictEqual(Base.x, 1); assert.strictEqual(Derived.x, 2); assert.strictEqual(Derived.y, 1); }); it("super-accessor-get in es2015", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { let thisInBase; class Base { @@ -61,14 +68,17 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { thisInBase ]; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); const [Base, Derived, thisInBase] = result.main(); assert.strictEqual(Base._x, 1); assert.strictEqual(Derived.y, 1); assert.strictEqual(thisInBase, Derived); }); it("super-accessor-set in es2015", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { let thisInBaseGet; let thisInBaseSet; @@ -93,7 +103,9 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { thisInBaseSet ]; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); const [Base, Derived, thisInBaseGet, thisInBaseSet] = result.main(); assert.strictEqual(Base._x, 1); assert.strictEqual(Derived._x, 2); @@ -102,7 +114,8 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { assert.strictEqual(thisInBaseSet, Derived); }); it("super-call in es2015", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { let thisInBase; class Base { @@ -119,13 +132,16 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { thisInBase, ]; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); const [Derived, thisInBase] = result.main(); assert.strictEqual(Derived.y, 1); assert.strictEqual(thisInBase, Derived); }); it("super-call in es5", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { let thisInBase; class Base { @@ -142,13 +158,16 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { thisInBase, ]; } - `, { target: ts.ScriptTarget.ES5 }); + `, + { target: ts.ScriptTarget.ES5 }, + ); const [Derived, thisInBase] = result.main(); assert.strictEqual(Derived.y, 1); assert.strictEqual(thisInBase, Derived); }); it("super- and this-call in es2015", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { class Base { static x() { @@ -165,12 +184,15 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { Derived, ]; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); const [Derived] = result.main(); assert.strictEqual(Derived.y, 2); }); it("super- and this-call in es5", () => { - const result = evaluator.evaluateTypeScript(` + const result = evaluator.evaluateTypeScript( + ` export function main() { class Base { static x() { @@ -187,8 +209,10 @@ describe("unittests:: evaluation:: superInStaticInitializer", () => { Derived, ]; } - `, { target: ts.ScriptTarget.ES2015 }); + `, + { target: ts.ScriptTarget.ES2015 }, + ); const [Derived] = result.main(); assert.strictEqual(Derived.y, 2); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/evaluation/updateExpressionInModule.ts b/src/testRunner/unittests/evaluation/updateExpressionInModule.ts index 071a975b78856..dc0eaade1c1eb 100644 --- a/src/testRunner/unittests/evaluation/updateExpressionInModule.ts +++ b/src/testRunner/unittests/evaluation/updateExpressionInModule.ts @@ -12,10 +12,10 @@ describe("unittests:: evaluation:: updateExpressionInModule", () => { let a = 1; export { a }; export const b = ++a; - ` + `, }, rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" + main: "/.src/main.ts", }, { module: ts.ModuleKind.CommonJS }); assert.equal(result.a, 2); assert.equal(result.b, 2); @@ -27,41 +27,49 @@ describe("unittests:: evaluation:: updateExpressionInModule", () => { let a = 1; export { a }; export const b = ++a; - ` + `, }, rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" + main: "/.src/main.ts", }, { module: ts.ModuleKind.System }); assert.equal(result.a, 2); assert.equal(result.b, 2); }); itIfBigInt("pre-increment in commonjs using BigInt", () => { - const result = evaluator.evaluateTypeScript({ - files: { - "/.src/main.ts": ` + const result = evaluator.evaluateTypeScript( + { + files: { + "/.src/main.ts": ` let a = BigInt(1); export { a }; export const b = ++a; - ` + `, + }, + rootFiles: ["/.src/main.ts"], + main: "/.src/main.ts", }, - rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" - }, { module: ts.ModuleKind.CommonJS }, { BigInt }); + { module: ts.ModuleKind.CommonJS }, + { BigInt }, + ); assert.equal(result.a, BigInt(2)); assert.equal(result.b, BigInt(2)); }); itIfBigInt("pre-increment in System using BigInt", () => { - const result = evaluator.evaluateTypeScript({ - files: { - "/.src/main.ts": ` + const result = evaluator.evaluateTypeScript( + { + files: { + "/.src/main.ts": ` let a = BigInt(1); export { a }; export const b = ++a; - ` + `, + }, + rootFiles: ["/.src/main.ts"], + main: "/.src/main.ts", }, - rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" - }, { module: ts.ModuleKind.System }, { BigInt }); + { module: ts.ModuleKind.System }, + { BigInt }, + ); assert.equal(result.a, BigInt(2)); assert.equal(result.b, BigInt(2)); }); @@ -72,10 +80,10 @@ describe("unittests:: evaluation:: updateExpressionInModule", () => { let a = 1; export { a }; export const b = a++; - ` + `, }, rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" + main: "/.src/main.ts", }, { module: ts.ModuleKind.CommonJS }); assert.equal(result.a, 2); assert.equal(result.b, 1); @@ -87,42 +95,50 @@ describe("unittests:: evaluation:: updateExpressionInModule", () => { let a = 1; export { a }; export const b = a++; - ` + `, }, rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" + main: "/.src/main.ts", }, { module: ts.ModuleKind.System }); assert.equal(result.a, 2); assert.equal(result.b, 1); }); itIfBigInt("post-increment in commonjs using BigInt", () => { - const result = evaluator.evaluateTypeScript({ - files: { - "/.src/main.ts": ` + const result = evaluator.evaluateTypeScript( + { + files: { + "/.src/main.ts": ` let a = BigInt(1); export { a }; export const b = a++; - ` + `, + }, + rootFiles: ["/.src/main.ts"], + main: "/.src/main.ts", }, - rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" - }, { module: ts.ModuleKind.CommonJS }, { BigInt }); + { module: ts.ModuleKind.CommonJS }, + { BigInt }, + ); assert.equal(result.a, BigInt(2)); assert.equal(result.b, BigInt(1)); }); itIfBigInt("post-increment in System using BigInt", () => { - const result = evaluator.evaluateTypeScript({ - files: { - "/.src/main.ts": ` + const result = evaluator.evaluateTypeScript( + { + files: { + "/.src/main.ts": ` let a = BigInt(1); export { a }; export const b = a++; - ` + `, + }, + rootFiles: ["/.src/main.ts"], + main: "/.src/main.ts", }, - rootFiles: ["/.src/main.ts"], - main: "/.src/main.ts" - }, { module: ts.ModuleKind.System }, { BigInt }); + { module: ts.ModuleKind.System }, + { BigInt }, + ); assert.equal(result.a, BigInt(2)); assert.equal(result.b, BigInt(1)); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/evaluation/usingDeclarations.ts b/src/testRunner/unittests/evaluation/usingDeclarations.ts index 701daf7208f3c..11adef2fb2b31 100644 --- a/src/testRunner/unittests/evaluation/usingDeclarations.ts +++ b/src/testRunner/unittests/evaluation/usingDeclarations.ts @@ -7,7 +7,8 @@ function FakeSuppressedError(error: any, suppressed: any) { describe("unittests:: evaluation:: usingDeclarations", () => { it("'using' in Block, normal completion (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -30,7 +31,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -40,12 +43,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "body", "exit block", "disposed", - "after block" + "after block", ]); }); it("'using' in Block, 'throw' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -72,7 +76,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -82,12 +88,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "body", "disposed", "error", - "after try" + "after try", ]); }); it("'using' in Block, 'throw' in dispose (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -114,7 +121,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -125,12 +134,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "exit try", "disposed", "error", - "after try" + "after try", ]); }); it("'using' in Block, 'throw' in multiple dispose (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable_1 = { @@ -164,7 +174,10 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); main(); @@ -177,14 +190,15 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "disposed 1", { error: "error 1", - suppressed: "error 2" + suppressed: "error 2", }, - "after try" + "after try", ]); }); it("'using' in Block, 'throw' in body and dispose (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -212,7 +226,10 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); main(); @@ -223,14 +240,15 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "disposed", { error: "dispose error", - suppressed: "body error" + suppressed: "body error", }, - "after try" + "after try", ]); }); it("'using' in Block, 'throw' in body and multiple dispose (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable_1 = { @@ -265,7 +283,10 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); main(); @@ -279,15 +300,16 @@ describe("unittests:: evaluation:: usingDeclarations", () => { error: "dispose error 1", suppressed: { error: "dispose error 2", - suppressed: "body error" - } + suppressed: "body error", + }, }, - "after try" + "after try", ]); }); it("'using' in Block, 'throw' in body and dispose, no global SuppressedError (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -315,7 +337,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after try"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -323,18 +347,20 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "before try", "enter try", "body", - "disposed"]); + "disposed", + ]); assert.instanceOf(output[4], Error); assert.strictEqual(output[4].name, "SuppressedError"); assert.strictEqual(output[4].error, "dispose error"); assert.strictEqual(output[4].suppressed, "body error"); assert.deepEqual(output.slice(5), [ - "after try" + "after try", ]); }); it("'using' in Block, 'return' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -357,7 +383,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -365,12 +393,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "before block", "enter block", "body", - "disposed" + "disposed", ]); }); it("'using' in Block, 'break' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -393,7 +422,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -402,12 +433,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter block", "body", "disposed", - "after block" + "after block", ]); }); it("'using' in Block, 'continue' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -430,7 +462,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -442,12 +476,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter block", "body", "disposed", - "after block" + "after block", ]); }); it("'using' in head of 'for', normal completion (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -470,7 +505,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -483,12 +520,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "body", "exit loop", "disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for', 'throw' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -516,7 +554,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -526,12 +566,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "body", "disposed", "error", - "after loop" + "after loop", ]); }); it("'using' in head of 'for', 'throw' in dispose (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -559,7 +600,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -573,12 +616,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "exit loop", "disposed", "error", - "after loop" + "after loop", ]); }); it("'using' in head of 'for', 'throw' in body and dispose (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -607,7 +651,10 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); main(); @@ -618,14 +665,15 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "disposed", { error: "dispose error", - suppressed: "body error" + suppressed: "body error", }, - "after loop" + "after loop", ]); }); it("'using' in head of 'for', 'return' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -648,7 +696,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -656,12 +706,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "before loop", "enter loop", "body", - "disposed" + "disposed", ]); }); it("'using' in head of 'for', 'break' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -684,7 +735,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -693,12 +746,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter loop", "body", "disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for', 'continue' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -721,7 +775,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -732,12 +788,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter loop", "body", "disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for', multiple iterations (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable = { @@ -760,7 +817,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -773,12 +832,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "body", "exit loop", "disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for-of', normal completion (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -807,7 +867,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -821,12 +883,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "body", "exit loop", "b disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for-of', 'throw' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -861,7 +924,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -876,7 +941,8 @@ describe("unittests:: evaluation:: usingDeclarations", () => { }); it("'using' in head of 'for-of', 'throw' in dispose (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -911,7 +977,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -927,7 +995,8 @@ describe("unittests:: evaluation:: usingDeclarations", () => { }); it("'using' in head of 'for-of', 'throw' in body and dispose (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -963,7 +1032,10 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); main(); @@ -974,14 +1046,15 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "a disposed", { error: "dispose error", - suppressed: "body error" + suppressed: "body error", }, "after loop", ]); }); it("'using' in head of 'for-of', 'return' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1010,7 +1083,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -1023,7 +1098,8 @@ describe("unittests:: evaluation:: usingDeclarations", () => { }); it("'using' in head of 'for-of', 'break' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1052,7 +1128,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -1061,12 +1139,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter loop", "body", "a disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for-of', 'continue' in body (es2018)", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1095,7 +1174,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -1107,12 +1188,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter loop", "body", "b disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for-await-of', normal completion (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1141,7 +1223,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1155,12 +1239,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "body", "exit loop", "b disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for-await-of', 'throw' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1195,7 +1280,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1210,7 +1297,8 @@ describe("unittests:: evaluation:: usingDeclarations", () => { }); it("'using' in head of 'for-await-of', 'throw' in dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1245,7 +1333,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1261,7 +1351,8 @@ describe("unittests:: evaluation:: usingDeclarations", () => { }); it("'using' in head of 'for-await-of', 'throw' in body and dispose (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1297,7 +1388,10 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }, { SuppressedError: FakeSuppressedError }); + `, + { target: ts.ScriptTarget.ES2018 }, + { SuppressedError: FakeSuppressedError }, + ); await main(); @@ -1308,14 +1402,15 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "a disposed", { error: "dispose error", - suppressed: "body error" + suppressed: "body error", }, "after loop", ]); }); it("'using' in head of 'for-await-of', 'return' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1344,7 +1439,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1357,7 +1454,8 @@ describe("unittests:: evaluation:: usingDeclarations", () => { }); it("'using' in head of 'for-await-of', 'break' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1386,7 +1484,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1395,12 +1495,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter loop", "body", "a disposed", - "after loop" + "after loop", ]); }); it("'using' in head of 'for-await-of', 'continue' in body (es2018)", async () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function* g() { @@ -1429,7 +1530,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after loop"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); await main(); @@ -1441,12 +1544,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter loop", "body", "b disposed", - "after loop" + "after loop", ]); }); it("'using' at top level of module (CommonJS)", () => { - const { output, x, y } = evaluator.evaluateTypeScript(` + const { output, x, y } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; output.push("before export x"); export const x = 1; @@ -1459,7 +1563,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { output.push("after using"); export const y = 2; output.push("after export y"); - `, { target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.CommonJS }); + `, + { target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.CommonJS }, + ); assert.strictEqual(x, 1); assert.strictEqual(y, 2); @@ -1468,12 +1574,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "before using", "after using", "after export y", - "disposed" + "disposed", ]); }); it("'using' at top level of module (AMD)", () => { - const { output, x, y } = evaluator.evaluateTypeScript(` + const { output, x, y } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; output.push("before export x"); export const x = 1; @@ -1486,7 +1593,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { output.push("after using"); export const y = 2; output.push("after export y"); - `, { target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.AMD }); + `, + { target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.AMD }, + ); assert.strictEqual(x, 1); assert.strictEqual(y, 2); @@ -1495,12 +1604,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "before using", "after using", "after export y", - "disposed" + "disposed", ]); }); it("'using' at top level of module (System)", () => { - const { output, x, y } = evaluator.evaluateTypeScript(` + const { output, x, y } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; output.push("before export x"); export const x = 1; @@ -1513,7 +1623,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { output.push("after using"); export const y = 2; output.push("after export y"); - `, { target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.System }); + `, + { target: ts.ScriptTarget.ES2018, module: ts.ModuleKind.System }, + ); assert.strictEqual(x, 1); assert.strictEqual(y, 2); @@ -1522,12 +1634,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "before using", "after using", "after export y", - "disposed" + "disposed", ]); }); it("'using' for 'null' value", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function body() { @@ -1544,7 +1657,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -1553,12 +1668,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter block", "body", "exit block", - "after block" + "after block", ]); }); it("'using' for 'undefined' value", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function body() { @@ -1575,7 +1691,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -1584,12 +1702,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "enter block", "body", "exit block", - "after block" + "after block", ]); }); it("'using' for non-disposable value", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function body() { @@ -1606,7 +1725,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); assert.throws(main); assert.deepEqual(output, [ @@ -1616,7 +1737,8 @@ describe("unittests:: evaluation:: usingDeclarations", () => { }); it("'using' disposes in reverse order", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; const disposable_1 = { @@ -1644,7 +1766,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { } output.push("after block"); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); @@ -1655,12 +1779,13 @@ describe("unittests:: evaluation:: usingDeclarations", () => { "exit block", "disposed 2", "disposed 1", - "after block" + "after block", ]); }); it("'using' for 'function' disposable resource ", () => { - const { main, output } = evaluator.evaluateTypeScript(` + const { main, output } = evaluator.evaluateTypeScript( + ` export const output: any[] = []; function disposable() { @@ -1674,7 +1799,9 @@ describe("unittests:: evaluation:: usingDeclarations", () => { run(); } - `, { target: ts.ScriptTarget.ES2018 }); + `, + { target: ts.ScriptTarget.ES2018 }, + ); main(); diff --git a/src/testRunner/unittests/factory.ts b/src/testRunner/unittests/factory.ts index 5740c30c90775..903388588aa69 100644 --- a/src/testRunner/unittests/factory.ts +++ b/src/testRunner/unittests/factory.ts @@ -82,5 +82,4 @@ describe("unittests:: FactoryAPI", () => { checkRhs(ts.SyntaxKind.QuestionQuestionEqualsToken, /*expectParens*/ false); }); }); - }); diff --git a/src/testRunner/unittests/helpers.ts b/src/testRunner/unittests/helpers.ts index 4e5f2046a416a..b01502e93b8f6 100644 --- a/src/testRunner/unittests/helpers.ts +++ b/src/testRunner/unittests/helpers.ts @@ -4,7 +4,7 @@ const enum ChangedPart { none = 0, references = 1 << 0, importsAndExports = 1 << 1, - program = 1 << 2 + program = 1 << 2, } export const newLine = "\r\n"; @@ -31,11 +31,7 @@ export interface TestCompilerHost extends ts.CompilerHost { export class SourceText implements ts.IScriptSnapshot { private fullText: string | undefined; - constructor(private references: string, - private importsAndExports: string, - private program: string, - private changedPart = ChangedPart.none, - private version = 0) { + constructor(private references: string, private importsAndExports: string, private program: string, private changedPart = ChangedPart.none, private version = 0) { } static New(references: string, importsAndExports: string, program: string): SourceText { diff --git a/src/testRunner/unittests/helpers/baseline.ts b/src/testRunner/unittests/helpers/baseline.ts index e3075686be24d..2daac68548942 100644 --- a/src/testRunner/unittests/helpers/baseline.ts +++ b/src/testRunner/unittests/helpers/baseline.ts @@ -1,8 +1,12 @@ import * as fakes from "../../_namespaces/fakes"; import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; -import { TscCompileSystem } from "./tsc"; -import { TestServerHost } from "./virtualFileSystemWithWatch"; +import { + TscCompileSystem, +} from "./tsc"; +import { + TestServerHost, +} from "./virtualFileSystemWithWatch"; export type CommandLineProgram = [ts.Program, ts.BuilderProgram?]; export interface CommandLineCallbacks { @@ -23,9 +27,10 @@ export function commandLineCallbacks( cb: program => { if (isAnyProgram(program)) { baselineBuildInfo(program.getCompilerOptions(), sys, originalReadCall); - (programs || (programs = [])).push(ts.isBuilderProgram(program) ? - [program.getProgram(), program] : - [program] + (programs || (programs = [])).push( + ts.isBuilderProgram(program) ? + [program.getProgram(), program] : + [program], ); } else { @@ -36,7 +41,7 @@ export function commandLineCallbacks( const result = programs || ts.emptyArray; programs = undefined; return result; - } + }, }; } @@ -172,13 +177,9 @@ export type ReadableProgramBuildInfoFileInfo = Omit & { + | [original: ts.ProgramBuildInfoFileId, readable: string] + | [orginal: ts.ProgramBuildInfoRootStartEnd, readable: readonly string[]]; +export type ReadableProgramMultiFileEmitBuildInfo = Omit & { fileNamesList: readonly (readonly string[])[] | undefined; fileInfos: ts.MapLike>; root: readonly ReadableProgramBuildInfoRoot[]; @@ -221,7 +222,7 @@ function generateBuildInfoProgramBaseline(sys: ts.System, buildInfoPath: string, undefined : [ toReadableBuilderFileEmit(ts.toProgramEmitPending(pendingEmit, buildInfo.program.options)), - pendingEmit + pendingEmit, ], }; } @@ -367,4 +368,4 @@ export function baselineBuildInfo( export function tscBaselineName(scenario: string, subScenario: string, commandLineArgs: readonly string[], isWatch?: boolean, suffix?: string) { return `${ts.isBuild(commandLineArgs) ? "tsbuild" : "tsc"}${isWatch ? "Watch" : ""}/${scenario}/${subScenario.split(" ").join("-")}${suffix ? suffix : ""}.js`; -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/helpers/contents.ts b/src/testRunner/unittests/helpers/contents.ts index 4a0bb4918dec9..d31379328ee31 100644 --- a/src/testRunner/unittests/helpers/contents.ts +++ b/src/testRunner/unittests/helpers/contents.ts @@ -1,5 +1,7 @@ import * as ts from "../../_namespaces/ts"; -import { libFile } from "./virtualFileSystemWithWatch"; +import { + libFile, +} from "./virtualFileSystemWithWatch"; export function compilerOptionsToConfigJson(options: ts.CompilerOptions) { return ts.optionMapToObject(ts.serializeCompilerOptions(options)); @@ -22,4 +24,4 @@ interface Symbol { export interface FsContents { [path: string]: string; -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/helpers/extends.ts b/src/testRunner/unittests/helpers/extends.ts index 397d4821047d5..f4eccbe357312 100644 --- a/src/testRunner/unittests/helpers/extends.ts +++ b/src/testRunner/unittests/helpers/extends.ts @@ -1,4 +1,6 @@ -import { dedent } from "../../_namespaces/Utils"; +import { + dedent, +} from "../../_namespaces/Utils"; import { createServerHost, createWatchedSystem, @@ -12,7 +14,7 @@ export function getSymlinkedExtendsSys(forTsserver?: true): TestServerHost { extends: "@something/tsconfig-base/tsconfig.json", compilerOptions: { removeComments: true, - } + }, }), "/users/user/projects/myconfigs/node_modules/@something/tsconfig-base/tsconfig.json": JSON.stringify({ compilerOptions: { composite: true }, @@ -29,4 +31,4 @@ export function getSymlinkedExtendsSys(forTsserver?: true): TestServerHost { }, [libFile.path]: libFile.content, }, { currentDirectory: "/users/user/projects/myproject" }); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/helpers/libraryResolution.ts b/src/testRunner/unittests/helpers/libraryResolution.ts index 11bf63292c10a..d435a4c2892ab 100644 --- a/src/testRunner/unittests/helpers/libraryResolution.ts +++ b/src/testRunner/unittests/helpers/libraryResolution.ts @@ -1,7 +1,17 @@ -import { dedent } from "../../_namespaces/Utils"; -import { FsContents, libContent } from "./contents"; -import { loadProjectFromFiles } from "./vfs"; -import { createServerHost, createWatchedSystem } from "./virtualFileSystemWithWatch"; +import { + dedent, +} from "../../_namespaces/Utils"; +import { + FsContents, + libContent, +} from "./contents"; +import { + loadProjectFromFiles, +} from "./vfs"; +import { + createServerHost, + createWatchedSystem, +} from "./virtualFileSystemWithWatch"; function getFsContentsForLibResolution(libRedirection?: boolean): FsContents { return { @@ -45,7 +55,7 @@ function getFsContentsForLibResolution(libRedirection?: boolean): FsContents { "/home/src/projects/node_modules/@typescript/lib-dom/index.d.ts": "interface DOMInterface { }", "/home/src/projects/node_modules/@typescript/lib-webworker/index.d.ts": "interface WebworkerInterface { }", "/home/src/projects/node_modules/@typescript/lib-scripthost/index.d.ts": "interface ScriptHostInterface { }", - } : undefined + } : undefined, }; } @@ -55,7 +65,7 @@ export function getFsForLibResolution(libRedirection: true | undefined) { { cwd: "/home/src/projects", executingFilePath: "/home/src/lib/tsc.js", - } + }, ); } @@ -65,7 +75,7 @@ export function getSysForLibResolution(libRedirection?: true) { { currentDirectory: "/home/src/projects", executingFilePath: "/home/src/lib/tsc.js", - } + }, ); } @@ -75,7 +85,7 @@ export function getServerHosForLibResolution(libRedirection?: true) { { currentDirectory: "/home/src/projects", executingFilePath: "/home/src/lib/tsc.js", - } + }, ); } diff --git a/src/testRunner/unittests/helpers/node10Result.ts b/src/testRunner/unittests/helpers/node10Result.ts index 5961d211f3f94..7ab2f528b423d 100644 --- a/src/testRunner/unittests/helpers/node10Result.ts +++ b/src/testRunner/unittests/helpers/node10Result.ts @@ -1,35 +1,49 @@ -import { dedent } from "../../_namespaces/Utils"; -import { FsContents } from "./contents"; -import { libFile } from "./virtualFileSystemWithWatch"; +import { + dedent, +} from "../../_namespaces/Utils"; +import { + FsContents, +} from "./contents"; +import { + libFile, +} from "./virtualFileSystemWithWatch"; export function getFsConentsForNode10ResultAtTypesPackageJson(packageName: string, addTypesCondition: boolean) { - return JSON.stringify({ - name: `@types/${packageName}`, - version: "1.0.0", - types: "index.d.ts", - exports: { - ".": { - ...(addTypesCondition ? { types: "./index.d.ts" } : {}), - require: "./index.d.ts" - } - } - }, undefined, " "); + return JSON.stringify( + { + name: `@types/${packageName}`, + version: "1.0.0", + types: "index.d.ts", + exports: { + ".": { + ...(addTypesCondition ? { types: "./index.d.ts" } : {}), + require: "./index.d.ts", + }, + }, + }, + undefined, + " ", + ); } export function getFsContentsForNode10ResultPackageJson(packageName: string, addTypes: boolean, addTypesCondition: boolean) { - return JSON.stringify({ - name: packageName, - version: "1.0.0", - main: "index.js", - ...(addTypes ? { types: "index.d.ts" } : {}), - exports: { - ".": { - ...(addTypesCondition ? { types: "./index.d.ts" } : {}), - import: "./index.mjs", - require: "./index.js" - } - } - }, undefined, " "); + return JSON.stringify( + { + name: packageName, + version: "1.0.0", + main: "index.js", + ...(addTypes ? { types: "index.d.ts" } : {}), + exports: { + ".": { + ...(addTypesCondition ? { types: "./index.d.ts" } : {}), + import: "./index.mjs", + require: "./index.js", + }, + }, + }, + undefined, + " ", + ); } export function getFsContentsForNode10ResultDts(packageName: string) { @@ -78,8 +92,8 @@ export function getFsContentsForNode10Result(): FsContents { strict: true, types: [], }, - files: ["index.mts"] + files: ["index.mts"], }), [libFile.path]: libFile.content, }; -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/helpers/solutionBuilder.ts b/src/testRunner/unittests/helpers/solutionBuilder.ts index 018594d044d6d..da77ca79ed0b3 100644 --- a/src/testRunner/unittests/helpers/solutionBuilder.ts +++ b/src/testRunner/unittests/helpers/solutionBuilder.ts @@ -1,6 +1,8 @@ import * as fakes from "../../_namespaces/fakes"; import * as ts from "../../_namespaces/ts"; -import { commandLineCallbacks } from "./baseline"; +import { + commandLineCallbacks, +} from "./baseline"; import { makeSystemReadyForBaseline, TscCompileSystem, @@ -17,15 +19,11 @@ import { export function createSolutionBuilderHostForBaseline( sys: TscCompileSystem | TestServerHost, versionToWrite?: string, - originalRead?: (TscCompileSystem | TestServerHost)["readFile"] + originalRead?: (TscCompileSystem | TestServerHost)["readFile"], ) { if (sys instanceof fakes.System) makeSystemReadyForBaseline(sys, versionToWrite); const { cb } = commandLineCallbacks(sys, originalRead); - const host = ts.createSolutionBuilderHost(sys, - /*createProgram*/ undefined, - ts.createDiagnosticReporter(sys, /*pretty*/ true), - ts.createBuilderStatusReporter(sys, /*pretty*/ true) - ); + const host = ts.createSolutionBuilderHost(sys, /*createProgram*/ undefined, ts.createDiagnosticReporter(sys, /*pretty*/ true), ts.createBuilderStatusReporter(sys, /*pretty*/ true)); host.afterProgramEmitAndDiagnostics = cb; host.afterEmitBundle = cb; return host; @@ -47,9 +45,13 @@ export function solutionBuildWithBaseline(sys: TestServerHost, solutionRoots: re const originalWrite = sys.write; const originalWriteFile = sys.writeFile; ts.Debug.assert(sys.writtenFiles === undefined); - const solutionBuilder = createSolutionBuilder(changeToHostTrackingWrittenFiles( - fakes.patchHostForBuildInfoReadWrite(sys) - ), solutionRoots, originalRead); + const solutionBuilder = createSolutionBuilder( + changeToHostTrackingWrittenFiles( + fakes.patchHostForBuildInfoReadWrite(sys), + ), + solutionRoots, + originalRead, + ); solutionBuilder.build(); sys.readFile = originalReadFile; sys.write = originalWrite; @@ -60,4 +62,4 @@ export function solutionBuildWithBaseline(sys: TestServerHost, solutionRoots: re export function createSystemWithSolutionBuild(solutionRoots: readonly string[], files: FileOrFolderOrSymLinkMap | readonly FileOrFolderOrSymLink[], params?: TestServerHostCreationParameters) { return solutionBuildWithBaseline(createWatchedSystem(files, params), solutionRoots); -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/helpers/tsc.ts b/src/testRunner/unittests/helpers/tsc.ts index d6681047f9664..29abecfcfc5c7 100644 --- a/src/testRunner/unittests/helpers/tsc.ts +++ b/src/testRunner/unittests/helpers/tsc.ts @@ -30,7 +30,7 @@ export type TscCompileSystem = fakes.System & { export const noChangeRun: TestTscEdit = { caption: "no-change-run", - edit: ts.noop + edit: ts.noop, }; export const noChangeOnlyRuns = [noChangeRun]; @@ -59,10 +59,14 @@ export function testTscCompileLike(input: TestTscCompileLike) { const initialFs = input.fs(); const inputFs = initialFs.shadow(); const { - scenario, subScenario, diffWithInitial, - commandLineArgs, modifyFs, + scenario, + subScenario, + diffWithInitial, + commandLineArgs, + modifyFs, environmentVariables, - compile: worker, additionalBaseline, + compile: worker, + additionalBaseline, } = input; if (modifyFs) modifyFs(inputFs); inputFs.makeReadonly(); @@ -90,7 +94,7 @@ ${baseFsPatch ? vfs.formatPatch(baseFsPatch) : ""} Output:: ${sys.output.join("")} -${patch ? vfs.formatPatch(patch) : ""}` +${patch ? vfs.formatPatch(patch) : ""}`, }; }; return sys; @@ -125,7 +129,7 @@ export function testTscCompile(input: TestTscCompile) { return testTscCompileLike({ ...input, compile: commandLineCompile, - additionalBaseline + additionalBaseline, }); function commandLineCompile(sys: TscCompileSystem) { @@ -221,10 +225,12 @@ export function verifyTscCompileLike(verifier: ( describe(`tsc ${input.commandLineArgs.join(" ")} ${input.scenario}:: ${input.subScenario}`, () => { describe(input.scenario, () => { describe(input.subScenario, () => { - verifyTscBaseline(() => verifier({ - ...input, - fs: () => input.fs().makeReadonly() - })); + verifyTscBaseline(() => + verifier({ + ...input, + fs: () => input.fs().makeReadonly(), + }) + ); }); }); }); @@ -242,9 +248,15 @@ interface VerifyTscEditDiscrepanciesInput { environmentVariables: TestTscCompile["environmentVariables"]; } function verifyTscEditDiscrepancies({ - index, edits, scenario, commandLineArgs, environmentVariables, + index, + edits, + scenario, + commandLineArgs, + environmentVariables, baselines, - modifyFs, baseFs, newSys + modifyFs, + baseFs, + newSys, }: VerifyTscEditDiscrepanciesInput): string[] | undefined { const { caption, discrepancyExplanation } = edits[index]; const sys = testTscCompile({ @@ -280,7 +292,7 @@ function verifyTscEditDiscrepancies({ const { buildInfo: cleanBuildInfo, readableBuildInfo: cleanReadableBuildInfo } = getBuildInfoForIncrementalCorrectnessCheck(cleanBuildText); const dtsSignaures = sys.dtsSignaures?.get(outputFile); verifyTextEqual(incrementalBuildInfo, cleanBuildInfo, `TsBuild info text without affectedFilesPendingEmit:: ${outputFile}::`); - // Verify file info sigantures + // Verify file info sigantures verifyMapLike( incrementalReadableBuildInfo?.program?.fileInfos as ReadableProgramMultiFileEmitBuildInfo["fileInfos"], cleanReadableBuildInfo?.program?.fileInfos as ReadableProgramMultiFileEmitBuildInfo["fileInfos"], @@ -291,11 +303,11 @@ function verifyTscEditDiscrepancies({ `Incremental signature is neither dts signature nor file version for File:: ${key}`, `Incremental:: ${JSON.stringify(incrementalFileInfo, /*replacer*/ undefined, 2)}`, `Clean:: ${JSON.stringify(cleanFileInfo, /*replacer*/ undefined, 2)}`, - `Dts Signature:: $${JSON.stringify(dtsForKey?.signature)}` + `Dts Signature:: $${JSON.stringify(dtsForKey?.signature)}`, ]; } }, - `FileInfos:: File:: ${outputFile}` + `FileInfos:: File:: ${outputFile}`, ); if (!isReadableProgramBundleEmitBuildInfo(incrementalReadableBuildInfo?.program)) { ts.Debug.assert(!isReadableProgramBundleEmitBuildInfo(cleanReadableBuildInfo?.program)); @@ -305,17 +317,19 @@ function verifyTscEditDiscrepancies({ cleanReadableBuildInfo?.program?.exportedModulesMap, (key, incrementalReferenceSet, cleanReferenceSet) => { const dtsForKey = dtsSignaures?.get(key); - if (!ts.arrayIsEqualTo(incrementalReferenceSet, cleanReferenceSet) && - (!dtsForKey || !ts.arrayIsEqualTo(incrementalReferenceSet, dtsForKey.exportedModules))) { + if ( + !ts.arrayIsEqualTo(incrementalReferenceSet, cleanReferenceSet) && + (!dtsForKey || !ts.arrayIsEqualTo(incrementalReferenceSet, dtsForKey.exportedModules)) + ) { return [ `Incremental Reference set is neither from dts nor files reference map for File:: ${key}::`, `Incremental:: ${JSON.stringify(incrementalReferenceSet, /*replacer*/ undefined, 2)}`, `Clean:: ${JSON.stringify(cleanReferenceSet, /*replacer*/ undefined, 2)}`, - `DtsExportsMap:: ${JSON.stringify(dtsForKey?.exportedModules, /*replacer*/ undefined, 2)}` + `DtsExportsMap:: ${JSON.stringify(dtsForKey?.exportedModules, /*replacer*/ undefined, 2)}`, ]; } }, - `exportedModulesMap:: File:: ${outputFile}` + `exportedModulesMap:: File:: ${outputFile}`, ); // Verify that incrementally pending affected file emit are in clean build since clean build can contain more files compared to incremental depending of noEmitOnError option if (incrementalReadableBuildInfo?.program?.affectedFilesPendingEmit) { @@ -323,7 +337,7 @@ function verifyTscEditDiscrepancies({ addBaseline( `Incremental build contains affectedFilesPendingEmit, clean build does not have it: ${outputFile}::`, `Incremental buildInfoText:: ${incrementalBuildText}`, - `Clean buildInfoText:: ${cleanBuildText}` + `Clean buildInfoText:: ${cleanBuildText}`, ); } let expectedIndex = 0; @@ -332,13 +346,13 @@ function verifyTscEditDiscrepancies({ expectedIndex = ts.findIndex( (cleanReadableBuildInfo!.program! as ReadableProgramMultiFileEmitBuildInfo).affectedFilesPendingEmit, ([expectedFileOrArray]) => actualFile === (ts.isString(expectedFileOrArray) ? expectedFileOrArray : expectedFileOrArray[0]), - expectedIndex + expectedIndex, ); if (expectedIndex === -1) { addBaseline( `Incremental build contains ${actualFile} file as pending emit, clean build does not have it: ${outputFile}::`, `Incremental buildInfoText:: ${incrementalBuildText}`, - `Clean buildInfoText:: ${cleanBuildText}` + `Clean buildInfoText:: ${cleanBuildText}`, ); } expectedIndex++; @@ -398,7 +412,7 @@ function verifyTscEditDiscrepancies({ function addBaseline(...text: string[]) { if (!baselines || !headerAdded) { - (baselines ||= []).push(`${index}:: ${caption}`, ...(discrepancyExplanation?.()|| ["*** Needs explanation"])); + (baselines ||= []).push(`${index}:: ${caption}`, ...(discrepancyExplanation?.() || ["*** Needs explanation"])); headerAdded = true; } baselines.push(...text); @@ -422,21 +436,25 @@ function getBuildInfoForIncrementalCorrectnessCheck(text: string | undefined): { } } return { - buildInfo: JSON.stringify({ - ...readableBuildInfo, - program: readableBuildInfo.program && { - ...readableBuildInfo.program, - fileNames: undefined, - fileNamesList: undefined, - fileInfos: sanitizedFileInfos, - // Ignore noEmit since that shouldnt be reason to emit the tsbuild info and presence of it in the buildinfo file does not matter - options: { ...readableBuildInfo.program.options, noEmit: undefined }, - exportedModulesMap: undefined, - affectedFilesPendingEmit: undefined, - latestChangedDtsFile: readableBuildInfo.program.latestChangedDtsFile ? "FakeFileName" : undefined, + buildInfo: JSON.stringify( + { + ...readableBuildInfo, + program: readableBuildInfo.program && { + ...readableBuildInfo.program, + fileNames: undefined, + fileNamesList: undefined, + fileInfos: sanitizedFileInfos, + // Ignore noEmit since that shouldnt be reason to emit the tsbuild info and presence of it in the buildinfo file does not matter + options: { ...readableBuildInfo.program.options, noEmit: undefined }, + exportedModulesMap: undefined, + affectedFilesPendingEmit: undefined, + latestChangedDtsFile: readableBuildInfo.program.latestChangedDtsFile ? "FakeFileName" : undefined, + }, + size: undefined, // Size doesnt need to be equal }, - size: undefined, // Size doesnt need to be equal - }, /*replacer*/ undefined, 2), + /*replacer*/ undefined, + 2, + ), readableBuildInfo, }; } @@ -457,9 +475,16 @@ export interface VerifyTscWithEditsInput extends TestTscCompile { * Verify non watch tsc invokcation after each edit */ export function verifyTsc({ - subScenario, fs, scenario, commandLineArgs, environmentVariables, - baselineSourceMap, modifyFs, baselineReadFileCalls, baselinePrograms, - edits + subScenario, + fs, + scenario, + commandLineArgs, + environmentVariables, + baselineSourceMap, + modifyFs, + baselineReadFileCalls, + baselinePrograms, + edits, }: VerifyTscWithEditsInput) { describe(`tsc ${commandLineArgs.join(" ")} ${scenario}:: ${subScenario}`, () => { let sys: TscCompileSystem; @@ -480,7 +505,7 @@ export function verifyTsc({ }); edits?.forEach(( { edit, caption, commandLineArgs: editCommandLineArgs }, - index + index, ) => { (editsSys || (editsSys = [])).push(testTscCompile({ scenario, @@ -516,7 +541,7 @@ export function verifyTsc({ text: `currentDirectory:: ${sys.getCurrentDirectory()} useCaseSensitiveFileNames: ${sys.useCaseSensitiveFileNames}\r\n` + texts.join("\r\n"), }; - } + }, })); if (edits?.length) { it("tsc invocation after edit and clean build correctness", () => { @@ -536,10 +561,9 @@ export function verifyTsc({ } Harness.Baseline.runBaseline( tscBaselineName(scenario, subScenario, commandLineArgs, /*isWatch*/ undefined, "-discrepancies"), - baselines ? baselines.join("\r\n") : null // eslint-disable-line no-null/no-null + baselines ? baselines.join("\r\n") : null, // eslint-disable-line no-null/no-null ); }); } }); } - diff --git a/src/testRunner/unittests/helpers/tscWatch.ts b/src/testRunner/unittests/helpers/tscWatch.ts index 4b8a3a6076866..e21c7de9f9f36 100644 --- a/src/testRunner/unittests/helpers/tscWatch.ts +++ b/src/testRunner/unittests/helpers/tscWatch.ts @@ -1,5 +1,9 @@ -import { patchHostForBuildInfoReadWrite } from "../../_namespaces/fakes"; -import { Baseline } from "../../_namespaces/Harness"; +import { + patchHostForBuildInfoReadWrite, +} from "../../_namespaces/fakes"; +import { + Baseline, +} from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; import { baselinePrograms, @@ -18,11 +22,11 @@ import { export const commonFile1: File = { path: "/a/b/commonFile1.ts", - content: "let x = 1" + content: "let x = 1", }; export const commonFile2: File = { path: "/a/b/commonFile2.ts", - content: "let y = 1" + content: "let y = 1", }; export type WatchOrSolution = void | ts.SolutionBuilder | ts.WatchOfConfigFile | ts.WatchOfFilesAndCompilerOptions; @@ -32,7 +36,7 @@ export interface TscWatchCompileChange + watchOrSolution: WatchOrSolution, ) => void; } export interface TscWatchCheckOptions { @@ -60,9 +64,12 @@ function tscWatchCompile(input: TscWatchCompile) { it("tsc-watch:: Generates files matching the baseline", () => { const { sys, baseline, oldSnap } = createBaseline(input.sys()); const { - scenario, subScenario, - commandLineArgs, edits, - baselineSourceMap, baselineDependencies + scenario, + subScenario, + commandLineArgs, + edits, + baselineSourceMap, + baselineDependencies, } = input; if (!isWatch(commandLineArgs)) sys.exit = exitCode => sys.exitCode = exitCode; @@ -83,7 +90,7 @@ function tscWatchCompile(input: TscWatchCompile) { baselineSourceMap, baselineDependencies, edits, - watchOrSolution + watchOrSolution, }); }); } @@ -145,24 +152,19 @@ export function createBaseline(system: TestServerHost, modifySystem?: (sys: Test } export function createSolutionBuilderWithWatchHostForBaseline(sys: TestServerHost, cb: ts.ExecuteCommandLineCallbacks) { - const host = ts.createSolutionBuilderWithWatchHost(sys, - /*createProgram*/ undefined, - ts.createDiagnosticReporter(sys, /*pretty*/ true), - ts.createBuilderStatusReporter(sys, /*pretty*/ true), - ts.createWatchStatusReporter(sys, /*pretty*/ true) - ); + const host = ts.createSolutionBuilderWithWatchHost(sys, /*createProgram*/ undefined, ts.createDiagnosticReporter(sys, /*pretty*/ true), ts.createBuilderStatusReporter(sys, /*pretty*/ true), ts.createWatchStatusReporter(sys, /*pretty*/ true)); host.afterProgramEmitAndDiagnostics = cb; host.afterEmitBundle = cb; return host; } interface CreateWatchCompilerHostOfConfigFileForBaseline extends ts.CreateWatchCompilerHostOfConfigFileInput { - system: TestServerHost, + system: TestServerHost; cb: ts.ExecuteCommandLineCallbacks; } export function createWatchCompilerHostOfConfigFileForBaseline( - input: CreateWatchCompilerHostOfConfigFileForBaseline + input: CreateWatchCompilerHostOfConfigFileForBaseline, ) { const host = ts.createWatchCompilerHostOfConfigFile({ ...input, @@ -174,11 +176,11 @@ export function createWatchCompilerHostOfConfigFileForBaseline extends ts.CreateWatchCompilerHostOfFilesAndCompilerOptionsInput { - system: TestServerHost, + system: TestServerHost; cb: ts.ExecuteCommandLineCallbacks; } export function createWatchCompilerHostOfFilesAndCompilerOptionsForBaseline( - input: CreateWatchCompilerHostOfFilesAndCompilerOptionsForBaseline + input: CreateWatchCompilerHostOfFilesAndCompilerOptionsForBaseline, ) { const host = ts.createWatchCompilerHostOfFilesAndCompilerOptions({ ...input, @@ -214,10 +216,17 @@ export interface RunWatchBaseline extends BaselineB watchOrSolution: WatchOrSolution; } export function runWatchBaseline({ - scenario, subScenario, commandLineArgs, - getPrograms, sys, baseline, oldSnap, - baselineSourceMap, baselineDependencies, - edits, watchOrSolution + scenario, + subScenario, + commandLineArgs, + getPrograms, + sys, + baseline, + oldSnap, + baselineSourceMap, + baselineDependencies, + edits, + watchOrSolution, }: RunWatchBaseline) { baseline.push(`${sys.getExecutingFilePath()} ${commandLineArgs.join(" ")}`); let programs = watchBaseline({ diff --git a/src/testRunner/unittests/helpers/tsserver.ts b/src/testRunner/unittests/helpers/tsserver.ts index 3a9b6c1e33505..ba2c9aac2e52b 100644 --- a/src/testRunner/unittests/helpers/tsserver.ts +++ b/src/testRunner/unittests/helpers/tsserver.ts @@ -1,8 +1,14 @@ -import { incrementalVerifier } from "../../../harness/incrementalUtils"; +import { + incrementalVerifier, +} from "../../../harness/incrementalUtils"; import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; -import { ActionWatchTypingLocations } from "../../_namespaces/ts.server"; -import { ensureErrorFreeBuild } from "./solutionBuilder"; +import { + ActionWatchTypingLocations, +} from "../../_namespaces/ts.server"; +import { + ensureErrorFreeBuild, +} from "./solutionBuilder"; import { changeToHostTrackingWrittenFiles, createServerHost, @@ -34,15 +40,14 @@ export const customTypesMap = { "react": "react", "lodash": "lodash" } - }` + }`, }; function replaceAll(source: string, searchValue: string, replaceValue: string): string { - let result: string | undefined = - (source as string & { replaceAll: typeof source.replace }).replaceAll?.(searchValue, replaceValue); + let result: string | undefined = (source as string & { replaceAll: typeof source.replace; }).replaceAll?.(searchValue, replaceValue); if (result !== undefined) { - return result; + return result; } result = ""; @@ -245,7 +250,7 @@ export class TestTypingsInstallerWorker extends ts.server.typingsInstaller.Typin if (log?.isEnabled()) { patchHostTimeouts( changeToHostTrackingWrittenFiles(installTypingHost), - logger + logger, ); (installTypingHost as TestSessionAndServiceHost).baselineHost("TI:: Creating typing installer"); } @@ -267,15 +272,16 @@ export class TestTypingsInstallerWorker extends ts.server.typingsInstaller.Typin installTypingHost.ensureFileOrFolder({ path: getTypesRegistryFileLocation(globalTypingsCacheLocation), content: JSON.stringify( - createTypesRegistryFileContent(typesRegistry ? - ts.isString(typesRegistry) ? - [typesRegistry] : - typesRegistry : - ts.emptyArray + createTypesRegistryFileContent( + typesRegistry ? + ts.isString(typesRegistry) ? + [typesRegistry] : + typesRegistry : + ts.emptyArray, ), undefined, " ", - ) + ), }); if (this.log.isEnabled()) { this.log.writeLine(`TI:: Updated ${typesRegistryPackageName} npm package`); @@ -333,7 +339,7 @@ export class TestTypingsInstallerWorker extends ts.server.typingsInstaller.Typin success: !!out, requestId, packageNames, - callback: cb + callback: cb, }; this.postExecActions.push(action); } @@ -395,7 +401,7 @@ function createTypesRegistryFileContent(list: readonly string[]): TypesRegistryF "ts2.4": "1.3.0", "ts2.5": "1.3.0", "ts2.6": "1.3.0", - "ts2.7": "1.3.0" + "ts2.7": "1.3.0", }; const entries: ts.MapLike> = {}; for (const l of list) { @@ -497,7 +503,7 @@ export class TestSession extends ts.server.Session { ts.Debug.assert(opts.allowNonBaseliningLogger || this.logger.hasLevel(ts.server.LogLevel.verbose), "Use Baselining logger and baseline tsserver log or create using allowNonBaseliningLogger"); this.testhost = patchHostTimeouts( changeToHostTrackingWrittenFiles(this.host as TestServerHost), - this.logger + this.logger, ); } @@ -597,8 +603,7 @@ export interface TestProjectServiceOptions extends ts.server.ProjectServiceOptio export class TestProjectService extends ts.server.ProjectService { public testhost: TestSessionAndServiceHost; - constructor(host: TestServerHost, public override logger: Logger, cancellationToken: ts.HostCancellationToken, useSingleInferredProject: boolean, - typingsInstaller: ts.server.ITypingsInstaller, opts: Partial = {}) { + constructor(host: TestServerHost, public override logger: Logger, cancellationToken: ts.HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ts.server.ITypingsInstaller, opts: Partial = {}) { super({ host, logger, @@ -609,12 +614,12 @@ export class TestProjectService extends ts.server.ProjectService { typingsInstaller, typesMapLocation: customTypesMap.path, incrementalVerifier, - ...opts + ...opts, }); ts.Debug.assert(opts.allowNonBaseliningLogger || this.logger.hasLevel(ts.server.LogLevel.verbose), "Use Baselining logger and baseline tsserver log or create using allowNonBaseliningLogger"); this.testhost = patchHostTimeouts( changeToHostTrackingWrittenFiles(this.host as TestServerHost), - this.logger + this.logger, ); if (logger.hasLevel(ts.server.LogLevel.verbose)) this.testhost.baselineHost("Creating project service"); } @@ -717,25 +722,28 @@ export class TestServerCancellationToken implements ts.server.ServerCancellation } } -export function openFilesForSession(files: readonly (string | File | { - readonly file: File | string, - readonly projectRootPath?: string, - content?: string, - scriptKindName?: ts.server.protocol.ScriptKindName, -})[], session: TestSession): void { +export function openFilesForSession( + files: readonly (string | File | { + readonly file: File | string; + readonly projectRootPath?: string; + content?: string; + scriptKindName?: ts.server.protocol.ScriptKindName; + })[], + session: TestSession, +): void { for (const file of files) { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Open, arguments: ts.isString(file) ? { file } : "file" in file ? // eslint-disable-line local/no-in-operator - { - file: typeof file.file === "string" ? file.file : file.file.path, - projectRootPath: file.projectRootPath, - fileContent: file.content, - scriptKindName: file.scriptKindName, - } : - { file: file.path } + { + file: typeof file.file === "string" ? file.file : file.file.path, + projectRootPath: file.projectRootPath, + fileContent: file.content, + scriptKindName: file.scriptKindName, + } : + { file: file.path }, }); } } @@ -744,7 +752,7 @@ export function closeFilesForSession(files: readonly (File | string)[], session: for (const file of files) { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Close, - arguments: { file: ts.isString(file) ? file : file.path } + arguments: { file: ts.isString(file) ? file : file.path }, }); } } @@ -752,26 +760,26 @@ export function closeFilesForSession(files: readonly (File | string)[], session: export function openExternalProjectForSession(project: ts.server.protocol.ExternalProject, session: TestSession) { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.OpenExternalProject, - arguments: project + arguments: project, }); } export function openExternalProjectsForSession(projects: ts.server.protocol.ExternalProject[], session: TestSession) { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.OpenExternalProjects, - arguments: { projects } + arguments: { projects }, }); } export function setCompilerOptionsForInferredProjectsRequestForSession( options: ts.server.protocol.InferredProjectCompilerOptions | ts.server.protocol.SetCompilerOptionsForInferredProjectsArgs, - session: TestSession + session: TestSession, ) { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompilerOptionsForInferredProjects, arguments: "options" in options ? // eslint-disable-line local/no-in-operator options as ts.server.protocol.SetCompilerOptionsForInferredProjectsArgs : - { options } + { options }, }); } @@ -791,12 +799,15 @@ export function verifyGetErrRequest(request: VerifyGetErrRequest) { const { session, files } = request; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Geterr, - arguments: { delay: 0, files: files.map(filePath) } + arguments: { delay: 0, files: files.map(filePath) }, }); checkAllErrors(request); } -interface SkipErrors { semantic?: true; suggestion?: true } +interface SkipErrors { + semantic?: true; + suggestion?: true; +} export interface CheckAllErrors extends VerifyGetErrRequestBase { files: readonly any[]; skip?: readonly (SkipErrors | undefined)[]; @@ -814,7 +825,7 @@ function filePath(file: string | File) { return ts.isString(file) ? file : file.path; } -function verifyErrorsUsingGeterr({scenario, subScenario, allFiles, openFiles, getErrRequest }: VerifyGetErrScenario) { +function verifyErrorsUsingGeterr({ scenario, subScenario, allFiles, openFiles, getErrRequest }: VerifyGetErrScenario) { it("verifies the errors in open file", () => { const host = createServerHost([...allFiles(), libFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -834,7 +845,7 @@ function verifyErrorsUsingGeterrForProject({ scenario, subScenario, allFiles, op for (const expected of getErrForProjectRequest()) { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GeterrForProject, - arguments: { delay: 0, file: filePath(expected.project) } + arguments: { delay: 0, file: filePath(expected.project) }, }); checkAllErrors({ session, files: expected.files }); } @@ -851,15 +862,15 @@ function verifyErrorsUsingSyncMethods({ scenario, subScenario, allFiles, openFil const reqArgs = { file: filePath(file), projectFileName: project && filePath(project) }; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SyntacticDiagnosticsSync, - arguments: reqArgs + arguments: reqArgs, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: reqArgs + arguments: reqArgs, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SuggestionDiagnosticsSync, - arguments: reqArgs + arguments: reqArgs, }); } baselineTsserverLogs(scenario, `${subScenario} gerErr with sync commands`, session); diff --git a/src/testRunner/unittests/helpers/vfs.ts b/src/testRunner/unittests/helpers/vfs.ts index df8fc06f3c1f3..e0f16f4adc1c8 100644 --- a/src/testRunner/unittests/helpers/vfs.ts +++ b/src/testRunner/unittests/helpers/vfs.ts @@ -1,8 +1,12 @@ import * as Harness from "../../_namespaces/Harness"; -import { getDirectoryPath } from "../../_namespaces/ts"; +import { + getDirectoryPath, +} from "../../_namespaces/ts"; import * as vfs from "../../_namespaces/vfs"; import * as vpath from "../../_namespaces/vpath"; -import { libContent } from "./contents"; +import { + libContent, +} from "./contents"; export interface FsOptions { libContentToAppend?: string; @@ -22,11 +26,11 @@ function valueOfFsOptions(options: FsOptionsOrLibContentsToAppend | undefined, k */ export function loadProjectFromDisk( root: string, - options?: FsOptionsOrLibContentsToAppend + options?: FsOptionsOrLibContentsToAppend, ): vfs.FileSystem { const resolver = vfs.createResolver(Harness.IO); return loadProjectFromFiles({ - ["/src"]: new vfs.Mount(vpath.resolve(Harness.IO.getWorkspaceRoot(), root), resolver) + ["/src"]: new vfs.Mount(vpath.resolve(Harness.IO.getWorkspaceRoot(), root), resolver), }, options); } @@ -84,13 +88,21 @@ export function enableStrict(fs: vfs.FileSystem, path: string) { } export function addTestPrologue(fs: vfs.FileSystem, path: string, prologue: string) { - prependText(fs, path, `${prologue} -`); + prependText( + fs, + path, + `${prologue} +`, + ); } export function addShebang(fs: vfs.FileSystem, project: string, file: string) { - prependText(fs, `src/${project}/${file}.ts`, `#!someshebang ${project} ${file} -`); + prependText( + fs, + `src/${project}/${file}.ts`, + `#!someshebang ${project} ${file} +`, + ); } export function restContent(project: string, file: string) { @@ -121,13 +133,21 @@ export function changeStubToRest(fs: vfs.FileSystem, project: string, file: stri export function addSpread(fs: vfs.FileSystem, project: string, file: string) { const path = `src/${project}/${file}.ts`; const content = fs.readFileSync(path, "utf8"); - fs.writeFileSync(path, `${content} + fs.writeFileSync( + path, + `${content} function ${project}${file}Spread(...b: number[]) { } const ${project}${file}_ar = [20, 30]; -${project}${file}Spread(10, ...${project}${file}_ar);`); +${project}${file}Spread(10, ...${project}${file}_ar);`, + ); - replaceText(fs, `src/${project}/tsconfig.json`, `"strict": false,`, `"strict": false, - "downlevelIteration": true,`); + replaceText( + fs, + `src/${project}/tsconfig.json`, + `"strict": false,`, + `"strict": false, + "downlevelIteration": true,`, + ); } export function getTripleSlashRef(project: string) { @@ -136,7 +156,11 @@ export function getTripleSlashRef(project: string) { export function addTripleSlashRef(fs: vfs.FileSystem, project: string, file: string) { fs.writeFileSync(getTripleSlashRef(project), `declare class ${project}${file} { }`); - prependText(fs, `src/${project}/${file}.ts`, `/// + prependText( + fs, + `src/${project}/${file}.ts`, + `/// const ${file}Const = new ${project}${file}(); -`); +`, + ); } diff --git a/src/testRunner/unittests/helpers/virtualFileSystemWithWatch.ts b/src/testRunner/unittests/helpers/virtualFileSystemWithWatch.ts index 5702e3bca76ee..ce7d6382c761d 100644 --- a/src/testRunner/unittests/helpers/virtualFileSystemWithWatch.ts +++ b/src/testRunner/unittests/helpers/virtualFileSystemWithWatch.ts @@ -44,7 +44,9 @@ import { sys, toPath, } from "../../_namespaces/ts"; -import { timeIncrements } from "../../_namespaces/vfs"; +import { + timeIncrements, +} from "../../_namespaces/vfs"; export const libFile: File = { path: "/a/lib/lib.d.ts", @@ -58,7 +60,7 @@ interface Number { toExponential: any; } interface Object {} interface RegExp {} interface String { charAt: any; } -interface Array { length: number; [n: number]: T; }` +interface Array { length: number; [n: number]: T; }`, }; function getExecutingFilePathFromLibFile(): string { @@ -258,7 +260,7 @@ export enum Tsc_WatchFile { export enum Tsc_WatchDirectory { WatchFile = "RecursiveDirectoryUsingFsWatchFile", NonRecursiveWatchDirectory = "RecursiveDirectoryUsingNonRecursiveWatchDirectory", - DynamicPolling = "RecursiveDirectoryUsingDynamicPriorityPolling" + DynamicPolling = "RecursiveDirectoryUsingDynamicPriorityPolling", } export interface TestServerHostOptions { @@ -303,11 +305,17 @@ export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, constructor( fileOrFolderorSymLinkList: FileOrFolderOrSymLinkMap | readonly FileOrFolderOrSymLink[], { - useCaseSensitiveFileNames, executingFilePath, currentDirectory, - newLine, windowsStyleRoot, environmentVariables, - runWithoutRecursiveWatches, runWithFallbackPolling, + useCaseSensitiveFileNames, + executingFilePath, + currentDirectory, + newLine, + windowsStyleRoot, + environmentVariables, + runWithoutRecursiveWatches, + runWithFallbackPolling, inodeWatching, - }: TestServerHostCreationParameters = {}) { + }: TestServerHostCreationParameters = {}, + ) { this.useCaseSensitiveFileNames = !!useCaseSensitiveFileNames; this.newLine = newLine || "\n"; this.windowsStyleRoot = windowsStyleRoot; @@ -395,10 +403,13 @@ export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, private reloadFS(fileOrFolderOrSymLinkList: FileOrFolderOrSymLinkMap | readonly FileOrFolderOrSymLink[]) { Debug.assert(this.fs.size === 0); if (isArray(fileOrFolderOrSymLinkList)) { - fileOrFolderOrSymLinkList.forEach(f => this.ensureFileOrFolder(!this.windowsStyleRoot ? - f : - { ...f, path: this.getHostSpecificPath(f.path) } - )); + fileOrFolderOrSymLinkList.forEach(f => + this.ensureFileOrFolder( + !this.windowsStyleRoot ? + f : + { ...f, path: this.getHostSpecificPath(f.path) }, + ) + ); } else { for (const key in fileOrFolderOrSymLinkList) { @@ -623,7 +634,7 @@ export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, map.remove(path, callback); this.hasWatchChanges = true; closed = true; - } + }, }; } @@ -631,7 +642,7 @@ export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, return this.createWatcher( this.watchedFiles, this.toFullPath(fileName), - { cb, pollingInterval } + { cb, pollingInterval }, ); } @@ -649,8 +660,8 @@ export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, path, { cb, - inode: this.inodes?.get(path) - } + inode: this.inodes?.get(path), + }, ) as FsWatchWorkerWatcher; result.on = noop; return result; @@ -666,7 +677,7 @@ export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, invokeWatcherCallbacks(map.get(path), ({ cb, inode }) => { // TODO:: if (this.inodeWatching && inode !== undefined && inode !== currentInode) return; - let relativeFileName = (entryFullPath ? this.getRelativePathToDirectory(fullPath, entryFullPath) : ""); + let relativeFileName = entryFullPath ? this.getRelativePathToDirectory(fullPath, entryFullPath) : ""; if (useTildeSuffix) relativeFileName = (relativeFileName ? relativeFileName : getBaseFileName(fullPath)) + "~"; cb(eventName, relativeFileName, modifiedTime); }); @@ -708,7 +719,7 @@ export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, return { path: this.toPath(fullPath), fullPath, - modifiedTime: this.now() + modifiedTime: this.now(), }; } @@ -823,12 +834,12 @@ export class TestServerHost implements server.ServerHost, FormatDiagnosticsHost, } readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] { - return matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, (dir) => { + return matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, dir => { const directories: string[] = []; const files: string[] = []; const folder = this.getRealFolder(this.toPath(dir)); if (folder) { - folder.entries.forEach((entry) => { + folder.entries.forEach(entry => { if (this.isFsFolder(entry)) { directories.push(getBaseFileName(entry.fullPath)); } @@ -1119,7 +1130,7 @@ function diffMap( caption: string, map: Map | undefined, old: Map | undefined, - deleted: boolean + deleted: boolean, ) { let captionAdded = false; let baselineChanged = false; @@ -1184,6 +1195,6 @@ export function getTsBuildProjectFilePath(project: string, file: string) { export function getTsBuildProjectFile(project: string, file: string): File { return { path: getTsBuildProjectFilePath(project, file), - content: Harness.IO.readFile(`${Harness.IO.getWorkspaceRoot()}/tests/projects/${project}/${file}`)! + content: Harness.IO.readFile(`${Harness.IO.getWorkspaceRoot()}/tests/projects/${project}/${file}`)!, }; } diff --git a/src/testRunner/unittests/incrementalParser.ts b/src/testRunner/unittests/incrementalParser.ts index 37feb3778854c..a42044d0a67db 100644 --- a/src/testRunner/unittests/incrementalParser.ts +++ b/src/testRunner/unittests/incrementalParser.ts @@ -549,8 +549,7 @@ describe("unittests:: Incremental Parser", () => { }); it("Modifier added to accessor", () => { - const source = - "class C {\ + const source = "class C {\ set Bar(bar:string) {}\ }\ var o2 = { set Foo(val:number) { } };"; @@ -563,8 +562,7 @@ var o2 = { set Foo(val:number) { } };"; }); it("Insert parameter ahead of parameter", () => { - const source = - "alert(100);\ + const source = "alert(100);\ \ class OverloadedMonster {\ constructor();\ @@ -579,8 +577,7 @@ constructor(name) { }\ }); it("Insert declare modifier before module", () => { - const source = - "module mAmbient {\ + const source = "module mAmbient {\ module m3 { }\ }"; @@ -592,8 +589,7 @@ module m3 { }\ }); it("Insert function above arrow function with comment", () => { - const source = - "\ + const source = "\ () =>\ // do something\ 0;"; @@ -702,7 +698,7 @@ module m3 { }\ }); it("Moving methods from object literal to class in strict mode", () => { - const source = "\"use strict\"; var v = { public A() { } public B() { } public C() { } }"; + const source = '"use strict"; var v = { public A() { } public B() { } public C() { } }'; const oldText = ts.ScriptSnapshot.fromString(source); const newTextAndChange = withChange(oldText, 14, "var v =".length, "class C"); @@ -719,7 +715,7 @@ module m3 { }\ compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); }); - it("Do not move methods called \"constructor\" from object literal to class", () => { + it('Do not move methods called "constructor" from object literal to class', () => { const source = "var v = { public constructor() { } public constructor() { } public constructor() { } }"; const oldText = ts.ScriptSnapshot.fromString(source); @@ -738,7 +734,7 @@ module m3 { }\ }); it("Moving index signatures from class to interface in strict mode", () => { - const source = "\"use strict\"; class C { public [a: number]: string; public [a: number]: string; public [a: number]: string }"; + const source = '"use strict"; class C { public [a: number]: string; public [a: number]: string; public [a: number]: string }'; const oldText = ts.ScriptSnapshot.fromString(source); const newTextAndChange = withChange(oldText, 14, "class".length, "interface"); @@ -755,9 +751,8 @@ module m3 { }\ compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 18); }); - it("Moving index signatures from interface to class in strict mode", () => { - const source = "\"use strict\"; interface C { public [a: number]: string; public [a: number]: string; public [a: number]: string }"; + const source = '"use strict"; interface C { public [a: number]: string; public [a: number]: string; public [a: number]: string }'; const oldText = ts.ScriptSnapshot.fromString(source); const newTextAndChange = withChange(oldText, 14, "interface".length, "class"); @@ -783,9 +778,8 @@ module m3 { }\ compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 4); }); - it("Moving accessors from object literal to class in strict mode", () => { - const source = "\"use strict\"; var v = { public get A() { } public get B() { } public get C() { } }"; + const source = '"use strict"; var v = { public get A() { } public get B() { } public get C() { } }'; const oldText = ts.ScriptSnapshot.fromString(source); const newTextAndChange = withChange(oldText, 14, "var v =".length, "class C"); @@ -834,11 +828,13 @@ module m3 { }\ insertCode(source, index, "Fo"); }); - for (const tsIgnoreComment of [ - "// @ts-ignore", - "/* @ts-ignore */", - "/*\n @ts-ignore */" - ]) { + for ( + const tsIgnoreComment of [ + "// @ts-ignore", + "/* @ts-ignore */", + "/*\n @ts-ignore */", + ] + ) { describe(`${tsIgnoreComment} comment directives`, () => { const textWithIgnoreComment = `const x = 10; function foo() { diff --git a/src/testRunner/unittests/jsDocParsing.ts b/src/testRunner/unittests/jsDocParsing.ts index 7fab2e719987b..56ba3a9cc05eb 100644 --- a/src/testRunner/unittests/jsDocParsing.ts +++ b/src/testRunner/unittests/jsDocParsing.ts @@ -9,8 +9,7 @@ describe("unittests:: JSDocParsing", () => { const typeAndDiagnostics = ts.parseJSDocTypeExpressionForTests(content); assert.isTrue(typeAndDiagnostics && typeAndDiagnostics.diagnostics.length === 0, "no errors issued"); - Harness.Baseline.runBaseline("JSDocParsing/TypeExpressions.parsesCorrectly." + name + ".json", - Utils.sourceFileToJSON(typeAndDiagnostics!.jsDocTypeExpression.type)); + Harness.Baseline.runBaseline("JSDocParsing/TypeExpressions.parsesCorrectly." + name + ".json", Utils.sourceFileToJSON(typeAndDiagnostics!.jsDocTypeExpression.type)); }); } @@ -99,9 +98,7 @@ describe("unittests:: JSDocParsing", () => { ts.Debug.fail("Comment has at least one diagnostic: " + comment.diagnostics[0].messageText); } - Harness.Baseline.runBaseline("JSDocParsing/DocComments.parsesCorrectly." + name + ".json", - JSON.stringify(comment.jsDoc, - (_, v) => v && v.pos !== undefined ? JSON.parse(Utils.sourceFileToJSON(v)) : v, 4)); + Harness.Baseline.runBaseline("JSDocParsing/DocComments.parsesCorrectly." + name + ".json", JSON.stringify(comment.jsDoc, (_, v) => v && v.pos !== undefined ? JSON.parse(Utils.sourceFileToJSON(v)) : v, 4)); }); } @@ -113,240 +110,307 @@ describe("unittests:: JSDocParsing", () => { } describe("parsesIncorrectly", () => { - parsesIncorrectly("multipleTypes", + parsesIncorrectly( + "multipleTypes", `/** * @type {number} * @type {string} - */`); - parsesIncorrectly("multipleReturnTypes", + */`, + ); + parsesIncorrectly( + "multipleReturnTypes", `/** * @return {number} * @return {string} - */`); - parsesIncorrectly("noTypeParameters", + */`, + ); + parsesIncorrectly( + "noTypeParameters", `/** * @template - */`); - parsesIncorrectly("trailingTypeParameterComma", + */`, + ); + parsesIncorrectly( + "trailingTypeParameterComma", `/** * @template T, - */`); - parsesIncorrectly("paramWithoutName", + */`, + ); + parsesIncorrectly( + "paramWithoutName", `/** * @param {number} - */`); - parsesIncorrectly("paramWithoutTypeOrName", + */`, + ); + parsesIncorrectly( + "paramWithoutTypeOrName", `/** * @param - */`); + */`, + ); - parsesIncorrectly("noType", + parsesIncorrectly( + "noType", `/** * @type -*/`); +*/`, + ); - parsesIncorrectly("@augments with no type", + parsesIncorrectly( + "@augments with no type", `/** * @augments - */`); + */`, + ); }); describe("parsesCorrectly", () => { parsesCorrectly("threeAsterisks", "/*** */"); parsesCorrectly("emptyComment", "/***/"); - parsesCorrectly("noLeadingAsterisk", + parsesCorrectly( + "noLeadingAsterisk", `/** @type {number} - */`); + */`, + ); - - parsesCorrectly("noReturnType", + parsesCorrectly( + "noReturnType", `/** * @return - */`); + */`, + ); - parsesCorrectly("leadingAsterisk", + parsesCorrectly( + "leadingAsterisk", `/** * @type {number} - */`); + */`, + ); parsesCorrectly("asteriskAfterPreamble", "/** * @type {number} */"); - parsesCorrectly("typeTag", + parsesCorrectly( + "typeTag", `/** * @type {number} - */`); + */`, + ); - parsesCorrectly("satisfiesTag", + parsesCorrectly( + "satisfiesTag", `/** * @satisfies {number} - */`); + */`, + ); - parsesCorrectly("returnTag1", + parsesCorrectly( + "returnTag1", `/** * @return {number} - */`); - + */`, + ); - parsesCorrectly("returnTag2", + parsesCorrectly( + "returnTag2", `/** * @return {number} Description text follows - */`); - + */`, + ); - parsesCorrectly("returnsTag1", + parsesCorrectly( + "returnsTag1", `/** * @returns {number} - */`); + */`, + ); - - parsesCorrectly("oneParamTag", + parsesCorrectly( + "oneParamTag", `/** * @param {number} name1 - */`); - + */`, + ); - parsesCorrectly("twoParamTag2", + parsesCorrectly( + "twoParamTag2", `/** * @param {number} name1 * @param {number} name2 - */`); + */`, + ); - - parsesCorrectly("paramTag1", + parsesCorrectly( + "paramTag1", `/** * @param {number} name1 Description text follows - */`); - + */`, + ); - parsesCorrectly("paramTagBracketedName1", + parsesCorrectly( + "paramTagBracketedName1", `/** * @param {number} [name1] Description text follows - */`); + */`, + ); - - parsesCorrectly("paramTagBracketedName2", + parsesCorrectly( + "paramTagBracketedName2", `/** * @param {number} [ name1 = 1] Description text follows - */`); - + */`, + ); - parsesCorrectly("twoParamTagOnSameLine", + parsesCorrectly( + "twoParamTagOnSameLine", `/** * @param {number} name1 @param {number} name2 - */`); + */`, + ); - - parsesCorrectly("paramTagNameThenType1", + parsesCorrectly( + "paramTagNameThenType1", `/** * @param name1 {number} - */`); - + */`, + ); - parsesCorrectly("paramTagNameThenType2", + parsesCorrectly( + "paramTagNameThenType2", `/** * @param name1 {number} Description - */`); - + */`, + ); - parsesCorrectly("argSynonymForParamTag", + parsesCorrectly( + "argSynonymForParamTag", `/** * @arg {number} name1 Description - */`); + */`, + ); - - parsesCorrectly("argumentSynonymForParamTag", + parsesCorrectly( + "argumentSynonymForParamTag", `/** * @argument {number} name1 Description - */`); - + */`, + ); - parsesCorrectly("templateTag", + parsesCorrectly( + "templateTag", `/** * @template T - */`); + */`, + ); - - parsesCorrectly("templateTag2", + parsesCorrectly( + "templateTag2", `/** * @template K,V - */`); - + */`, + ); - parsesCorrectly("templateTag3", + parsesCorrectly( + "templateTag3", `/** * @template K ,V - */`); + */`, + ); - - parsesCorrectly("templateTag4", + parsesCorrectly( + "templateTag4", `/** * @template K, V - */`); - + */`, + ); - parsesCorrectly("templateTag5", + parsesCorrectly( + "templateTag5", `/** * @template K , V - */`); + */`, + ); - parsesCorrectly("templateTag6", + parsesCorrectly( + "templateTag6", `/** * @template K , V Description of type parameters. - */`); + */`, + ); - parsesCorrectly("paramWithoutType", + parsesCorrectly( + "paramWithoutType", `/** * @param foo - */`); - parsesCorrectly("throwsTag1", + */`, + ); + parsesCorrectly( + "throwsTag1", `/** * @throws {Error} - */`); + */`, + ); - parsesCorrectly("throwsTag2", + parsesCorrectly( + "throwsTag2", `/** * @throws free-form description - */`); + */`, + ); - parsesCorrectly("throwsTag3", + parsesCorrectly( + "throwsTag3", `/** * @throws {Error} description - */`); + */`, + ); - parsesCorrectly("exceptionTag1", + parsesCorrectly( + "exceptionTag1", `/** * @exception {Error} - */`); + */`, + ); - parsesCorrectly("exceptionTag2", + parsesCorrectly( + "exceptionTag2", `/** * @exception free-form description - */`); + */`, + ); - parsesCorrectly("exceptionTag3", + parsesCorrectly( + "exceptionTag3", `/** * @exception {Error} description - */`); - parsesCorrectly("typedefTagWithChildrenTags", + */`, + ); + parsesCorrectly( + "typedefTagWithChildrenTags", `/** * @typedef People * @type {Object} * @property {number} age * @property {string} name - */`); - parsesCorrectly("less-than and greater-than characters", + */`, + ); + parsesCorrectly( + "less-than and greater-than characters", `/** * @param x hi < > still part of the previous comment - */`); + */`, + ); - parsesCorrectly("Nested @param tags", + parsesCorrectly( + "Nested @param tags", `/** * @param {object} o Doc doc * @param {string} o.f Doc for f -*/`); - parsesCorrectly("@link tags", +*/`, + ); + parsesCorrectly( + "@link tags", `/** * {@link first } * Inside {@link link text} thing @@ -365,8 +429,10 @@ oh.no * nope * }, because of the intermediate asterisks. * @author Alfa Romero See my home page: {@link https://example.com} - */`); - parsesCorrectly("authorTag", + */`, + ); + parsesCorrectly( + "authorTag", `/** * @author John Doe * @author John Doe unexpected comment @@ -385,30 +451,37 @@ oh.no * must be on the same line to parse * @author Long Comment I * want to keep commenting down here, I dunno. - */`); + */`, + ); - parsesCorrectly("consecutive newline tokens", + parsesCorrectly( + "consecutive newline tokens", `/** * @example * Some\n\n * text\r\n * with newlines. - */`); + */`, + ); parsesCorrectly("Chained tags, no leading whitespace", `/**@a @b @c@d*/`); parsesCorrectly("Single trailing whitespace", `/** trailing whitespace */`); parsesCorrectly("Initial star is not a tag", `/***@a*/`); parsesCorrectly("Initial star space is not a tag", `/*** @a*/`); parsesCorrectly("Initial email address is not a tag", `/**bill@example.com*/`); - parsesCorrectly("no space before @ is not a new tag", + parsesCorrectly( + "no space before @ is not a new tag", `/** * @param this (@is@) * @param fine its@fine @zerowidth *@singlestar **@doublestar - */`); - parsesCorrectly("@@ does not start a new tag", + */`, + ); + parsesCorrectly( + "@@ does not start a new tag", `/** * @param this is (@@fine@@and) is one comment - */`); + */`, + ); }); }); describe("getFirstToken", () => { diff --git a/src/testRunner/unittests/jsonParserRecovery.ts b/src/testRunner/unittests/jsonParserRecovery.ts index 41f4c98559542..c68253ab03609 100644 --- a/src/testRunner/unittests/jsonParserRecovery.ts +++ b/src/testRunner/unittests/jsonParserRecovery.ts @@ -10,8 +10,9 @@ describe("unittests:: jsonParserRecovery", () => { `jsonParserRecovery/${name.replace(/[^a-z0-9_-]/ig, "_")}.errors.txt`, Harness.Compiler.getErrorBaseline([{ content: text, - unitName: name - }], file.parseDiagnostics)); + unitName: name, + }], file.parseDiagnostics), + ); // Will throw if parse tree does not cover full input text file.getChildren(); @@ -22,7 +23,9 @@ describe("unittests:: jsonParserRecovery", () => { parsesToValidSourceFileWithErrors("TypeScript code", "interface Foo {} blah"); parsesToValidSourceFileWithErrors("Two comma-separated objects", "{}, {}"); parsesToValidSourceFileWithErrors("Two objects", "{} {}"); - parsesToValidSourceFileWithErrors("JSX", ` + parsesToValidSourceFileWithErrors( + "JSX", + ` interface Test {} const Header = () => ( @@ -36,5 +39,6 @@ describe("unittests:: jsonParserRecovery", () => { \`}
- )`); + )`, + ); }); diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index 560d68b7e954f..332ecb96d22e6 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -41,7 +41,7 @@ function createModuleResolutionHost(baselines: string[], hasDirectoryExists: boo assert.isTrue(directories.has(ts.getDirectoryPath(path)), `'fileExists' '${path}' request in non-existing directory`); return map.has(path); }, - useCaseSensitiveFileNames: true + useCaseSensitiveFileNames: true, }; } else { @@ -161,7 +161,7 @@ describe("unittests:: moduleResolution:: Node module resolution - relative paths describe("unittests:: moduleResolution:: Node module resolution - non-relative paths", () => { it("computes correct commonPrefix for moduleName cache", () => { - const resolutionCache = ts.createModuleResolutionCache("/", (f) => f); + const resolutionCache = ts.createModuleResolutionCache("/", f => f); let cache = resolutionCache.getOrCreateCacheForNonRelativeName("a", /*mode*/ undefined); cache.set("/sub", { resolvedModule: { @@ -334,11 +334,11 @@ describe("unittests:: moduleResolution:: Node module resolution - non-relative p }, { name: "/sub/node_modules/a/package.json", - content: '{"version": "0.0.0", "main": "./index"}' - } + content: '{"version": "0.0.0", "main": "./index"}', + }, ); const compilerOptions: ts.CompilerOptions = { moduleResolution: ts.ModuleResolutionKind.Node10 }; - const cache = ts.createModuleResolutionCache("/", (f) => f); + const cache = ts.createModuleResolutionCache("/", f => f); baselines.push(`Resolving "a" from /sub/dir/foo.ts`); let resolution = ts.resolveModuleName("a", "/sub/dir/foo.ts", compilerOptions, host, cache); baselines.push(`Resolution:: ${JSON.stringify(resolution, /*replacer*/ undefined, 2)}`); @@ -364,7 +364,7 @@ describe("unittests:: moduleResolution:: Node module resolution - non-relative p { name: "/linked/index.d.ts", symlinks: ["/app/node_modules/linked/index.d.ts"] }, { name: "/app/node_modules/linked/package.json", content: '{"version": "0.0.0", "main": "./index"}' }, ); - const cache = ts.createModuleResolutionCache("/", (f) => f); + const cache = ts.createModuleResolutionCache("/", f => f); const compilerOptions: ts.CompilerOptions = { moduleResolution: ts.ModuleResolutionKind.Node10 }; baselineResolution("/app/src/app.ts"); baselineResolution("/app/lib/main.ts"); @@ -425,31 +425,49 @@ describe("unittests:: moduleResolution:: Relative imports", () => { }); } - test("should file all modules", { - "/a/b/c/first/shared.ts": ` + test( + "should file all modules", + { + "/a/b/c/first/shared.ts": ` class A {} export = A`, - "/a/b/c/first/second/class_a.ts": ` + "/a/b/c/first/second/class_a.ts": ` import Shared = require('../shared'); import C = require('../../third/class_c'); class B {} export = B;`, - "/a/b/c/third/class_c.ts": ` + "/a/b/c/third/class_c.ts": ` import Shared = require('../first/shared'); class C {} export = C; - ` - }, "/a/b/c/first/second", ["class_a.ts"], ["../../../c/third/class_c.ts"]); - - test("should find modules in node_modules", { - "/parent/node_modules/mod/index.d.ts": "export var x", - "/parent/app/myapp.ts": `import {x} from "mod"` - }, "/parent/app", ["myapp.ts"], []); - - test("should find file referenced via absolute and relative names", { - "/a/b/c.ts": `/// `, - "/a/b/b.ts": "var x" - }, "/a/b", ["c.ts", "/a/b/b.ts"], []); + `, + }, + "/a/b/c/first/second", + ["class_a.ts"], + ["../../../c/third/class_c.ts"], + ); + + test( + "should find modules in node_modules", + { + "/parent/node_modules/mod/index.d.ts": "export var x", + "/parent/app/myapp.ts": `import {x} from "mod"`, + }, + "/parent/app", + ["myapp.ts"], + [], + ); + + test( + "should find file referenced via absolute and relative names", + { + "/a/b/c.ts": `/// `, + "/a/b/b.ts": "var x", + }, + "/a/b", + ["c.ts", "/a/b/b.ts"], + [], + ); }); describe("unittests:: moduleResolution:: Files with different casing with forceConsistentCasingInFileNames", () => { @@ -512,7 +530,7 @@ describe("unittests:: moduleResolution:: Files with different casing with forceC "same file is referenced using absolute and relative names", { "/a/b/c.ts": `/// `, - "/a/b/d.ts": "var x" + "/a/b/d.ts": "var x", }, { module: ts.ModuleKind.AMD }, "/a/b", @@ -523,7 +541,7 @@ describe("unittests:: moduleResolution:: Files with different casing with forceC "two files used in program differ only in casing (tripleslash references)", { "/a/b/c.ts": `/// `, - "/a/b/d.ts": "var x" + "/a/b/d.ts": "var x", }, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", @@ -534,7 +552,7 @@ describe("unittests:: moduleResolution:: Files with different casing with forceC "two files used in program differ only in casing (imports)", { "/a/b/c.ts": `import {x} from "D"`, - "/a/b/d.ts": "export var x" + "/a/b/d.ts": "export var x", }, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", @@ -545,7 +563,7 @@ describe("unittests:: moduleResolution:: Files with different casing with forceC "two files used in program differ only in casing (imports, relative module names)", { "moduleA.ts": `import {x} from "./ModuleB"`, - "moduleB.ts": "export var x" + "moduleB.ts": "export var x", }, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", @@ -557,7 +575,7 @@ describe("unittests:: moduleResolution:: Files with different casing with forceC { "/a/b/c.ts": `import {x} from "D"`, "/a/b/D.ts": "export var x", - "/a/b/d.ts": "export var y" + "/a/b/d.ts": "export var y", }, { module: ts.ModuleKind.AMD }, "/a/b", @@ -569,7 +587,7 @@ describe("unittests:: moduleResolution:: Files with different casing with forceC { "moduleA.ts": `import a = require("./ModuleC")`, "moduleB.ts": `import a = require("./moduleC")`, - "moduleC.ts": "export var x" + "moduleC.ts": "export var x", }, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", @@ -585,7 +603,7 @@ describe("unittests:: moduleResolution:: Files with different casing with forceC "/a/B/c/moduleD.ts": ` import a = require("./moduleA"); import b = require("./moduleB"); - ` + `, }, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", @@ -601,7 +619,7 @@ import b = require("./moduleB"); "/a/B/c/moduleD.ts": ` import a = require("./moduleA"); import b = require("./moduleB"); - ` + `, }, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", @@ -623,7 +641,6 @@ import b = require("./moduleB"); }); describe("unittests:: moduleResolution:: baseUrl augmented module resolution", () => { - it("module resolution without path mappings/rootDirs", () => { const baselines: string[] = []; test(/*hasDirectoryExists*/ true); @@ -742,15 +759,15 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( paths: { "*": [ "*", - "generated/*" + "generated/*", ], "somefolder/*": [ - "someanotherfolder/*" + "someanotherfolder/*", ], "/rooted/*": [ - "generated/*" - ] - } + "generated/*", + ], + }, }; check("folder1/file1"); check("folder1/file2"); @@ -769,7 +786,7 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( } }); - it ("classic + baseUrl + path mappings", () => { + it("classic + baseUrl + path mappings", () => { const baselines: string[] = []; // classic mode does not use directoryExists test(/*hasDirectoryExists*/ false); @@ -790,15 +807,15 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( paths: { "*": [ "*", - "generated/*" + "generated/*", ], "somefolder/*": [ - "someanotherfolder/*" + "someanotherfolder/*", ], "/rooted/*": [ - "generated/*" - ] - } + "generated/*", + ], + }, }; check("folder1/file1"); check("folder1/file2"); @@ -814,7 +831,7 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( } }); - it ("node + rootDirs", () => { + it("node + rootDirs", () => { const baselines: string[] = []; test(/*hasDirectoryExists*/ true); test(/*hasDirectoryExists*/ false); @@ -830,8 +847,8 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( moduleResolution: ts.ModuleResolutionKind.Node10, rootDirs: [ "/root", - "/root/generated/" - ] + "/root/generated/", + ], }; check("./file2", file1); check("../folder1/file1", file3); @@ -846,7 +863,7 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( } }); - it ("classic + rootDirs", () => { + it("classic + rootDirs", () => { const baselines: string[] = []; test(/*hasDirectoryExists*/ false); runBaseline("classic rootDirs", baselines); @@ -862,8 +879,8 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( jsx: ts.JsxEmit.React, rootDirs: [ "/root", - "/root/generated/" - ] + "/root/generated/", + ], }; check("./file2", file1); check("../folder1/file1", file3); @@ -878,7 +895,7 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( } }); - it ("nested node module", () => { + it("nested node module", () => { const baselines: string[] = []; test(/*hasDirectoryExists*/ true); test(/*hasDirectoryExists*/ false); @@ -893,8 +910,8 @@ describe("unittests:: moduleResolution:: baseUrl augmented module resolution", ( moduleResolution: ts.ModuleResolutionKind.Node10, baseUrl: "/root", paths: { - "libs/guid": [ "src/libs/guid" ] - } + "libs/guid": ["src/libs/guid"], + }, }; baselines.push(`Resolving "libs/guid" from ${app.name}${hasDirectoryExists ? "" : " with host that doesnt have directoryExists"}`); const result = ts.resolveModuleName("libs/guid", app.name, options, host); @@ -909,7 +926,7 @@ describe("unittests:: moduleResolution:: ModuleResolutionHost.directoryExists", const host: ts.ModuleResolutionHost = { readFile: ts.notImplemented, fileExists: ts.notImplemented, - directoryExists: _ => false + directoryExists: _ => false, }; const result = ts.resolveModuleName("someName", "/a/b/c/d", { moduleResolution: ts.ModuleResolutionKind.Node10 }, host); @@ -935,35 +952,35 @@ describe("unittests:: moduleResolution:: Type reference directive resolution: ", { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/types/lib/index.d.ts" }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/types/lib/typings/lib.d.ts" }; const packageFile = { name: "/root/src/types/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2, packageFile); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2, packageFile); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/node_modules/lib/index.d.ts" }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/node_modules/lib/typings/lib.d.ts" }; const packageFile = { name: "/root/src/node_modules/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2, packageFile); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2, packageFile); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/node_modules/@types/lib/index.d.ts" }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/node_modules/@types/lib/typings/lib.d.ts" }; const packageFile = { name: "/root/src/node_modules/@types/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2, packageFile); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2, packageFile); } runBaseline("type reference from primary location", baselines); }); @@ -972,29 +989,29 @@ describe("unittests:: moduleResolution:: Type reference directive resolution: ", { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/lib.d.ts" }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/lib/index.d.ts" }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/lib/typings/lib.d.ts" }; const packageFile = { name: "/root/node_modules/lib/package.json", content: JSON.stringify({ typings: "typings/lib.d.ts" }) }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2, packageFile); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2, packageFile); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/@types/lib/index.d.ts" }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2); } { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/@types/lib/typings/lib.d.ts" }; const packageFile = { name: "/root/node_modules/@types/lib/package.json", content: JSON.stringify({ typings: "typings/lib.d.ts" }) }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2, packageFile); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2, packageFile); } runBaseline("type reference from secondary location", baselines); }); @@ -1003,7 +1020,7 @@ describe("unittests:: moduleResolution:: Type reference directive resolution: ", const f1 = { name: "/root/src/a/b/c/app.ts" }; const f2 = { name: "/root/src/types/lib/index.d.ts" }; const f3 = { name: "/root/src/a/b/node_modules/lib.d.ts" }; - test(baselines, /*typesRoot*/"/root/src/types", /* typeDirective */"lib", f1, f2, f3); + test(baselines, /*typesRoot*/ "/root/src/types", /* typeDirective */ "lib", f1, f2, f3); runBaseline("type reference overrides secondary location", baselines); }); it("Reused program keeps errors", () => { @@ -1053,7 +1070,7 @@ describe("unittests:: moduleResolution:: Type reference directive resolution: ", declare module "fs-client" { import { Stat } from "fs"; export function foo(): Stat; - }` + }`, }; const file = ts.createSourceFile(f.name, f.content, ts.ScriptTarget.ES2015); const compilerHost: ts.CompilerHost = { @@ -1082,7 +1099,7 @@ describe("unittests:: moduleResolution:: Type reference directive resolution: ", declare module "fs-client" { import { Stat } from "fs"; export function foo(): Stat; - }` + }`, }; const file = ts.createSourceFile(f.name, f.content, ts.ScriptTarget.ES2015); const compilerHost: ts.CompilerHost = { @@ -1099,7 +1116,7 @@ describe("unittests:: moduleResolution:: Type reference directive resolution: ", resolveModuleNames(moduleNames: string[], _containingFile: string) { assert.deepEqual(moduleNames, ["fs"]); return [undefined!]; // TODO: GH#18217 - } + }, }; ts.createProgram([f.name], {}, compilerHost); }); diff --git a/src/testRunner/unittests/parsePseudoBigInt.ts b/src/testRunner/unittests/parsePseudoBigInt.ts index 10f5e098362f9..affe01a2d0d3d 100644 --- a/src/testRunner/unittests/parsePseudoBigInt.ts +++ b/src/testRunner/unittests/parsePseudoBigInt.ts @@ -12,7 +12,7 @@ describe("unittests:: BigInt literal base conversions", () => { for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { assert.equal( ts.parsePseudoBigInt("0".repeat(leadingZeros) + testNumber + "n"), - String(testNumber) + String(testNumber), ); } } @@ -52,19 +52,19 @@ describe("unittests:: BigInt literal base conversions", () => { it("can parse large literals", () => { assert.equal( ts.parsePseudoBigInt("123456789012345678901234567890n"), - "123456789012345678901234567890" + "123456789012345678901234567890", ); assert.equal( ts.parsePseudoBigInt("0b1100011101110100100001111111101101100001101110011111000001110111001001110001111110000101011010010n"), - "123456789012345678901234567890" + "123456789012345678901234567890", ); assert.equal( ts.parsePseudoBigInt("0o143564417755415637016711617605322n"), - "123456789012345678901234567890" + "123456789012345678901234567890", ); assert.equal( ts.parsePseudoBigInt("0x18ee90ff6c373e0ee4e3f0ad2n"), - "123456789012345678901234567890" + "123456789012345678901234567890", ); }); }); diff --git a/src/testRunner/unittests/paths.ts b/src/testRunner/unittests/paths.ts index fcd8de8ebee75..33de6b314914c 100644 --- a/src/testRunner/unittests/paths.ts +++ b/src/testRunner/unittests/paths.ts @@ -294,19 +294,19 @@ describe("unittests:: core paths", () => { it("toFileNameLowerCase", () => { assert.strictEqual( ts.toFileNameLowerCase("/user/UserName/projects/Project/file.ts"), - "/user/username/projects/project/file.ts" + "/user/username/projects/project/file.ts", ); assert.strictEqual( ts.toFileNameLowerCase("/user/UserName/projects/projectß/file.ts"), - "/user/username/projects/projectß/file.ts" + "/user/username/projects/projectß/file.ts", ); assert.strictEqual( ts.toFileNameLowerCase("/user/UserName/projects/İproject/file.ts"), - "/user/username/projects/İproject/file.ts" + "/user/username/projects/İproject/file.ts", ); assert.strictEqual( ts.toFileNameLowerCase("/user/UserName/projects/ı/file.ts"), - "/user/username/projects/ı/file.ts" + "/user/username/projects/ı/file.ts", ); }); }); diff --git a/src/testRunner/unittests/printer.ts b/src/testRunner/unittests/printer.ts index 1ac368226f435..dd724ed73f855 100644 --- a/src/testRunner/unittests/printer.ts +++ b/src/testRunner/unittests/printer.ts @@ -7,8 +7,7 @@ describe("unittests:: PrinterAPI", () => { function makePrintsCorrectly(prefix: string) { return function printsCorrectly(name: string, options: ts.PrinterOptions, printCallback: (printer: ts.Printer) => string) { it(name, () => { - Harness.Baseline.runBaseline(`printerApi/${prefix}.${name}.js`, - printCallback(ts.createPrinter({ newLine: ts.NewLineKind.CarriageReturnLineFeed, ...options }))); + Harness.Baseline.runBaseline(`printerApi/${prefix}.${name}.js`, printCallback(ts.createPrinter({ newLine: ts.NewLineKind.CarriageReturnLineFeed, ...options }))); }); }; } @@ -19,7 +18,9 @@ describe("unittests:: PrinterAPI", () => { // Avoid eagerly creating the sourceFile so that `createSourceFile` doesn't run unless one of these tests is run. let sourceFile: ts.SourceFile; before(() => { - sourceFile = ts.createSourceFile("source.ts", ` + sourceFile = ts.createSourceFile( + "source.ts", + ` interface A { // comment1 readonly prop?: T; @@ -53,7 +54,9 @@ describe("unittests:: PrinterAPI", () => { // comment10 function functionWithDefaultArgValue(argument: string = "defaultValue"): void { } - `, ts.ScriptTarget.ES2015); + `, + ts.ScriptTarget.ES2015, + ); }); printsCorrectly("default", {}, printer => printer.printFile(sourceFile)); printsCorrectly("removeComments", { removeComments: true }, printer => printer.printFile(sourceFile)); @@ -68,22 +71,24 @@ describe("unittests:: PrinterAPI", () => { // https://github.com/microsoft/TypeScript/issues/22239 printsCorrectly("importStatementRemoveComments", { removeComments: true }, printer => printer.printFile(ts.createSourceFile("source.ts", "import {foo} from 'foo';", ts.ScriptTarget.ESNext))); - printsCorrectly("classHeritageClauses", {}, printer => printer.printFile(ts.createSourceFile( - "source.ts", - `class A extends B implements C implements D {}`, - ts.ScriptTarget.ES2017 - ))); + printsCorrectly("classHeritageClauses", {}, printer => + printer.printFile(ts.createSourceFile( + "source.ts", + `class A extends B implements C implements D {}`, + ts.ScriptTarget.ES2017, + ))); // https://github.com/microsoft/TypeScript/issues/35093 - printsCorrectly("definiteAssignmentAssertions", {}, printer => printer.printFile(ts.createSourceFile( - "source.ts", - `class A { + printsCorrectly("definiteAssignmentAssertions", {}, printer => + printer.printFile(ts.createSourceFile( + "source.ts", + `class A { prop!: string; } let x!: string;`, - ts.ScriptTarget.ES2017 - ))); + ts.ScriptTarget.ES2017, + ))); // https://github.com/microsoft/TypeScript/issues/35054 printsCorrectly("jsx attribute escaping", {}, printer => { @@ -92,31 +97,35 @@ describe("unittests:: PrinterAPI", () => { String.raw``, ts.ScriptTarget.ESNext, /*setParentNodes*/ undefined, - ts.ScriptKind.TSX + ts.ScriptKind.TSX, )); }); }); describe("No duplicate ref directives when emiting .d.ts->.d.ts", () => { it("without statements", () => { - const host = new fakes.CompilerHost(new vfs.FileSystem(/*ignoreCase*/ true, { - files: { - "/test.d.ts": `/// \n/// \n/// { - const host = new fakes.CompilerHost(new vfs.FileSystem(/*ignoreCase*/ true, { - files: { - "/test.d.ts": `/// \n/// \n/// { let bundle: ts.Bundle; before(() => { bundle = ts.factory.createBundle([ - ts.createSourceFile("a.ts", ` + ts.createSourceFile( + "a.ts", + ` /*! [a.ts] */ // comment0 const a = 1; - `, ts.ScriptTarget.ES2015), - ts.createSourceFile("b.ts", ` + `, + ts.ScriptTarget.ES2015, + ), + ts.createSourceFile( + "b.ts", + ` /*! [b.ts] */ // comment1 const b = 2; - `, ts.ScriptTarget.ES2015) + `, + ts.ScriptTarget.ES2015, + ), ]); }); printsCorrectly("default", {}, printer => printer.printBundle(bundle)); @@ -149,169 +166,186 @@ describe("unittests:: PrinterAPI", () => { describe("printNode", () => { const printsCorrectly = makePrintsCorrectly("printsNodeCorrectly"); - printsCorrectly("class", {}, printer => printer.printNode( - ts.EmitHint.Unspecified, - ts.factory.createClassDeclaration( - /*modifiers*/ undefined, - /*name*/ ts.factory.createIdentifier("C"), - /*typeParameters*/ undefined, - /*heritageClauses*/ undefined, - [ts.factory.createPropertyDeclaration( - ts.factory.createNodeArray([ts.factory.createToken(ts.SyntaxKind.PublicKeyword)]), - ts.factory.createIdentifier("prop"), - /*questionOrExclamationToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined - )] - ), - ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015) - )); - - printsCorrectly("namespaceExportDeclaration", {}, printer => printer.printNode( - ts.EmitHint.Unspecified, - ts.factory.createNamespaceExportDeclaration("B"), - ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015) - )); - - printsCorrectly("newExpressionWithPropertyAccessOnCallExpression", {}, printer => printer.printNode( - ts.EmitHint.Unspecified, - ts.factory.createNewExpression( - ts.factory.createPropertyAccessExpression( - ts.factory.createCallExpression(ts.factory.createIdentifier("f"), /*typeArguments*/ undefined, /*argumentsArray*/ undefined), - "x"), - /*typeArguments*/ undefined, - /*argumentsArray*/ undefined - ), - ts.createSourceFile("source.ts", "", ts.ScriptTarget.ESNext)) - ); - - printsCorrectly("newExpressionOnConditionalExpression", {}, printer => printer.printNode( - ts.EmitHint.Unspecified, - ts.factory.createNewExpression( - ts.factory.createConditionalExpression( - ts.factory.createIdentifier("x"), ts.factory.createToken(ts.SyntaxKind.QuestionToken), - ts.factory.createIdentifier("y"), ts.factory.createToken(ts.SyntaxKind.ColonToken), - ts.factory.createIdentifier("z")), - /*typeArguments*/ undefined, - /*argumentsArray*/ undefined - ), - ts.createSourceFile("source.ts", "", ts.ScriptTarget.ESNext)) - ); - - printsCorrectly("emptyGlobalAugmentation", {}, printer => printer.printNode( - ts.EmitHint.Unspecified, - ts.factory.createModuleDeclaration( - /*modifiers*/ [ts.factory.createToken(ts.SyntaxKind.DeclareKeyword)], - ts.factory.createIdentifier("global"), - ts.factory.createModuleBlock(ts.emptyArray), - ts.NodeFlags.GlobalAugmentation), - ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015) - )); + printsCorrectly("class", {}, printer => + printer.printNode( + ts.EmitHint.Unspecified, + ts.factory.createClassDeclaration( + /*modifiers*/ undefined, + /*name*/ ts.factory.createIdentifier("C"), + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, + [ts.factory.createPropertyDeclaration( + ts.factory.createNodeArray([ts.factory.createToken(ts.SyntaxKind.PublicKeyword)]), + ts.factory.createIdentifier("prop"), + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined, + )], + ), + ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015), + )); - printsCorrectly("emptyGlobalAugmentationWithNoDeclareKeyword", {}, printer => printer.printNode( - ts.EmitHint.Unspecified, - ts.factory.createModuleDeclaration( - /*modifiers*/ undefined, - ts.factory.createIdentifier("global"), - ts.factory.createModuleBlock(ts.emptyArray), - ts.NodeFlags.GlobalAugmentation), - ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015) - )); + printsCorrectly("namespaceExportDeclaration", {}, printer => + printer.printNode( + ts.EmitHint.Unspecified, + ts.factory.createNamespaceExportDeclaration("B"), + ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015), + )); - // https://github.com/Microsoft/TypeScript/issues/15971 - printsCorrectly("classWithOptionalMethodAndProperty", {}, printer => printer.printNode( - ts.EmitHint.Unspecified, - ts.factory.createClassDeclaration( - /*modifiers*/ [ts.factory.createToken(ts.SyntaxKind.DeclareKeyword)], - /*name*/ ts.factory.createIdentifier("X"), - /*typeParameters*/ undefined, - /*heritageClauses*/ undefined, - [ - ts.factory.createMethodDeclaration( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ ts.factory.createIdentifier("method"), - /*questionToken*/ ts.factory.createToken(ts.SyntaxKind.QuestionToken), - /*typeParameters*/ undefined, - [], - /*type*/ ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword), - /*body*/ undefined - ), - ts.factory.createPropertyDeclaration( - /*modifiers*/ undefined, - /*name*/ ts.factory.createIdentifier("property"), - /*questionToken*/ ts.factory.createToken(ts.SyntaxKind.QuestionToken), - /*type*/ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), - /*initializer*/ undefined + printsCorrectly("newExpressionWithPropertyAccessOnCallExpression", {}, printer => + printer.printNode( + ts.EmitHint.Unspecified, + ts.factory.createNewExpression( + ts.factory.createPropertyAccessExpression( + ts.factory.createCallExpression(ts.factory.createIdentifier("f"), /*typeArguments*/ undefined, /*argumentsArray*/ undefined), + "x", ), - ] - ), - ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015) - )); - - // https://github.com/Microsoft/TypeScript/issues/15651 - printsCorrectly("functionTypes", {}, printer => printer.printNode( - ts.EmitHint.Unspecified, - ts.setEmitFlags(ts.factory.createTupleTypeNode([ - ts.factory.createFunctionTypeNode( - /*typeParameters*/ undefined, - [ts.factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - ts.factory.createIdentifier("args") - )], - ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword) + /*typeArguments*/ undefined, + /*argumentsArray*/ undefined, ), - ts.factory.createFunctionTypeNode( - [ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, "T")], - [ts.factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - ts.factory.createIdentifier("args") - )], - ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword) + ts.createSourceFile("source.ts", "", ts.ScriptTarget.ESNext), + )); + + printsCorrectly("newExpressionOnConditionalExpression", {}, printer => + printer.printNode( + ts.EmitHint.Unspecified, + ts.factory.createNewExpression( + ts.factory.createConditionalExpression( + ts.factory.createIdentifier("x"), + ts.factory.createToken(ts.SyntaxKind.QuestionToken), + ts.factory.createIdentifier("y"), + ts.factory.createToken(ts.SyntaxKind.ColonToken), + ts.factory.createIdentifier("z"), + ), + /*typeArguments*/ undefined, + /*argumentsArray*/ undefined, ), - ts.factory.createFunctionTypeNode( - /*typeParameters*/ undefined, - [ts.factory.createParameterDeclaration( - /*modifiers*/ undefined, - ts.factory.createToken(ts.SyntaxKind.DotDotDotToken), - ts.factory.createIdentifier("args") - )], - ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword) + ts.createSourceFile("source.ts", "", ts.ScriptTarget.ESNext), + )); + + printsCorrectly("emptyGlobalAugmentation", {}, printer => + printer.printNode( + ts.EmitHint.Unspecified, + ts.factory.createModuleDeclaration( + /*modifiers*/ [ts.factory.createToken(ts.SyntaxKind.DeclareKeyword)], + ts.factory.createIdentifier("global"), + ts.factory.createModuleBlock(ts.emptyArray), + ts.NodeFlags.GlobalAugmentation, ), - ts.factory.createFunctionTypeNode( - /*typeParameters*/ undefined, - [ts.factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - ts.factory.createIdentifier("args"), - ts.factory.createToken(ts.SyntaxKind.QuestionToken) - )], - ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword) + ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015), + )); + + printsCorrectly("emptyGlobalAugmentationWithNoDeclareKeyword", {}, printer => + printer.printNode( + ts.EmitHint.Unspecified, + ts.factory.createModuleDeclaration( + /*modifiers*/ undefined, + ts.factory.createIdentifier("global"), + ts.factory.createModuleBlock(ts.emptyArray), + ts.NodeFlags.GlobalAugmentation, ), - ts.factory.createFunctionTypeNode( + ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015), + )); + + // https://github.com/Microsoft/TypeScript/issues/15971 + printsCorrectly("classWithOptionalMethodAndProperty", {}, printer => + printer.printNode( + ts.EmitHint.Unspecified, + ts.factory.createClassDeclaration( + /*modifiers*/ [ts.factory.createToken(ts.SyntaxKind.DeclareKeyword)], + /*name*/ ts.factory.createIdentifier("X"), /*typeParameters*/ undefined, - [ts.factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - ts.factory.createIdentifier("args"), - /*questionToken*/ undefined, - ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword) - )], - ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword) + /*heritageClauses*/ undefined, + [ + ts.factory.createMethodDeclaration( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ ts.factory.createIdentifier("method"), + /*questionToken*/ ts.factory.createToken(ts.SyntaxKind.QuestionToken), + /*typeParameters*/ undefined, + [], + /*type*/ ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword), + /*body*/ undefined, + ), + ts.factory.createPropertyDeclaration( + /*modifiers*/ undefined, + /*name*/ ts.factory.createIdentifier("property"), + /*questionToken*/ ts.factory.createToken(ts.SyntaxKind.QuestionToken), + /*type*/ ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), + /*initializer*/ undefined, + ), + ], ), - ts.factory.createFunctionTypeNode( - /*typeParameters*/ undefined, - [ts.factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - ts.factory.createObjectBindingPattern([]) - )], - ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword) + ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015), + )); + + // https://github.com/Microsoft/TypeScript/issues/15651 + printsCorrectly("functionTypes", {}, printer => + printer.printNode( + ts.EmitHint.Unspecified, + ts.setEmitFlags( + ts.factory.createTupleTypeNode([ + ts.factory.createFunctionTypeNode( + /*typeParameters*/ undefined, + [ts.factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + ts.factory.createIdentifier("args"), + )], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), + ), + ts.factory.createFunctionTypeNode( + [ts.factory.createTypeParameterDeclaration(/*modifiers*/ undefined, "T")], + [ts.factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + ts.factory.createIdentifier("args"), + )], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), + ), + ts.factory.createFunctionTypeNode( + /*typeParameters*/ undefined, + [ts.factory.createParameterDeclaration( + /*modifiers*/ undefined, + ts.factory.createToken(ts.SyntaxKind.DotDotDotToken), + ts.factory.createIdentifier("args"), + )], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), + ), + ts.factory.createFunctionTypeNode( + /*typeParameters*/ undefined, + [ts.factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + ts.factory.createIdentifier("args"), + ts.factory.createToken(ts.SyntaxKind.QuestionToken), + )], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), + ), + ts.factory.createFunctionTypeNode( + /*typeParameters*/ undefined, + [ts.factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + ts.factory.createIdentifier("args"), + /*questionToken*/ undefined, + ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), + )], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), + ), + ts.factory.createFunctionTypeNode( + /*typeParameters*/ undefined, + [ts.factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + ts.factory.createObjectBindingPattern([]), + )], + ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), + ), + ]), + ts.EmitFlags.SingleLine, ), - ]), ts.EmitFlags.SingleLine), - ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015) - )); + ts.createSourceFile("source.ts", "", ts.ScriptTarget.ES2015), + )); }); }); diff --git a/src/testRunner/unittests/programApi.ts b/src/testRunner/unittests/programApi.ts index 29ee633f7d05e..1d3d9528db3d4 100644 --- a/src/testRunner/unittests/programApi.ts +++ b/src/testRunner/unittests/programApi.ts @@ -17,7 +17,6 @@ function verifyMissingFilePaths(missingPaths: readonly ts.Path[], expected: read } describe("unittests:: programApi:: Program.getMissingFilePaths", () => { - const options: ts.CompilerOptions = { noLib: true, }; @@ -30,19 +29,22 @@ describe("unittests:: programApi:: Program.getMissingFilePaths", () => { const referenceFileName = "reference.ts"; const referenceFileRelativePath = "./" + referenceFileName; - const referenceFile = new documents.TextDocument(referenceFileName, - "/// \n" + // Absolute - "/// \n" + // Relative - "/// \n" + // Unqualified - "/// \n" // No extension + const referenceFile = new documents.TextDocument( + referenceFileName, + '/// \n' + // Absolute + '/// \n' + // Relative + '/// \n' + // Unqualified + '/// \n', // No extension ); const testCompilerHost = new fakes.CompilerHost( vfs.createFromFileSystem( Harness.IO, /*ignoreCase*/ true, - { documents: [emptyFile, referenceFile], cwd: "d:\\pretend\\" }), - { newLine: ts.NewLineKind.LineFeed }); + { documents: [emptyFile, referenceFile], cwd: "d:\\pretend\\" }, + ), + { newLine: ts.NewLineKind.LineFeed }, + ); it("handles no missing root files", () => { const program = ts.createProgram([emptyFileRelativePath], options, testCompilerHost); @@ -99,7 +101,7 @@ describe("unittests:: programApi:: Program.getMissingFilePaths", () => { // From no-extension reference "d:/pretend/nonexistent4.d.ts", "d:/pretend/nonexistent4.ts", - "d:/pretend/nonexistent4.tsx" + "d:/pretend/nonexistent4.tsx", ]); }); @@ -114,15 +116,21 @@ describe("unittests:: programApi:: Program.getMissingFilePaths", () => { return fileName === "test.ts" ? ts.createSourceFile(fileName, testSource, languageVersion) : undefined; }, getDefaultLibFileName: () => "", - writeFile: (_fileName, _content) => { throw new Error("unsupported"); }, + writeFile: (_fileName, _content) => { + throw new Error("unsupported"); + }, getCurrentDirectory: () => ts.sys.getCurrentDirectory(), getCanonicalFileName: fileName => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(), getNewLine: () => ts.sys.newLine, useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames, fileExists: fileName => fileName === "test.ts", readFile: fileName => fileName === "test.ts" ? testSource : undefined, - resolveModuleNames: (_moduleNames: string[], _containingFile: string) => { throw new Error("unsupported"); }, - getDirectories: _path => { throw new Error("unsupported"); }, + resolveModuleNames: (_moduleNames: string[], _containingFile: string) => { + throw new Error("unsupported"); + }, + getDirectories: _path => { + throw new Error("unsupported"); + }, }; const program = ts.createProgram(["test.ts"], { module: ts.ModuleKind.ES2015 }, host); @@ -197,7 +205,7 @@ describe("unittests:: programApi:: Program.getTypeChecker / Program.getSemanticD assert.isEmpty(diag); }); it("getSymbolAtLocation does not cause additional error to be added on module resolution failure", () => { - const main = new documents.TextDocument("/main.ts", "import \"./module\";"); + const main = new documents.TextDocument("/main.ts", 'import "./module";'); const mod = new documents.TextDocument("/module.d.ts", "declare const foo: any;"); const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [main, mod], cwd: "/" }); @@ -212,12 +220,12 @@ describe("unittests:: programApi:: Program.getTypeChecker / Program.getSemanticD describe("unittests:: programApi:: CompilerOptions relative paths", () => { it("resolves relative paths by getCurrentDirectory", () => { - const main = new documents.TextDocument("/main.ts", "import \"module\";"); + const main = new documents.TextDocument("/main.ts", 'import "module";'); const mod = new documents.TextDocument("/lib/module.ts", "declare const foo: any;"); const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [main, mod], cwd: "/" }); const program = ts.createProgram(["./main.ts"], { - paths: { "*": ["./lib/*"] } + paths: { "*": ["./lib/*"] }, }, new fakes.CompilerHost(fs, { newLine: ts.NewLineKind.LineFeed })); assert.isEmpty(program.getConfigFileParsingDiagnostics()); diff --git a/src/testRunner/unittests/publicApi.ts b/src/testRunner/unittests/publicApi.ts index e0facd0594d82..7fb4fb096c122 100644 --- a/src/testRunner/unittests/publicApi.ts +++ b/src/testRunner/unittests/publicApi.ts @@ -87,12 +87,13 @@ describe("unittests:: Public APIs:: getTypeAtLocation", () => { const host = new fakes.CompilerHost(vfs.createFromFileSystem( Harness.IO, /*ignoreCase*/ true, - { documents: [new documents.TextDocument("/file.ts", content)], cwd: "/" })); + { documents: [new documents.TextDocument("/file.ts", content)], cwd: "/" }, + )); const program = ts.createProgram({ host, rootNames: ["/file.ts"], - options: { noLib: true } + options: { noLib: true }, }); const checker = program.getTypeChecker(); @@ -109,12 +110,13 @@ describe("unittests:: Public APIs:: getTypeAtLocation", () => { const host = new fakes.CompilerHost(vfs.createFromFileSystem( Harness.IO, /*ignoreCase*/ true, - { documents: [new documents.TextDocument("/file.ts", content)], cwd: "/" })); + { documents: [new documents.TextDocument("/file.ts", content)], cwd: "/" }, + )); const program = ts.createProgram({ host, rootNames: ["/file.ts"], - options: { noLib: true } + options: { noLib: true }, }); const checker = program.getTypeChecker(); @@ -133,12 +135,13 @@ describe("unittests:: Public APIs:: getTypeAtLocation", () => { const host = new fakes.CompilerHost(vfs.createFromFileSystem( Harness.IO, /*ignoreCase*/ true, - { documents: [new documents.TextDocument("/file.ts", content)], cwd: "/" })); + { documents: [new documents.TextDocument("/file.ts", content)], cwd: "/" }, + )); const program = ts.createProgram({ host, rootNames: ["/file.ts"], - options: { noLib: true } + options: { noLib: true }, }); const checker = program.getTypeChecker(); @@ -153,12 +156,13 @@ describe("unittests:: Public APIs:: getTypeAtLocation", () => { const host = new fakes.CompilerHost(vfs.createFromFileSystem( Harness.IO, /*ignoreCase*/ true, - { documents: [new documents.TextDocument("/file.ts", content)], cwd: "/" })); + { documents: [new documents.TextDocument("/file.ts", content)], cwd: "/" }, + )); const program = ts.createProgram({ host, rootNames: ["/file.ts"], - options: { noLib: true } + options: { noLib: true }, }); const checker = program.getTypeChecker(); @@ -187,7 +191,7 @@ describe("unittests:: Public APIs:: validateLocaleAndSetLanguage", () => { assert.isTrue(expectedToReadFile, `Locale : ${locale} ${expectedToReadFile ? "should" : "should not"} read ${fileName}.`); // Throw error here so that actual change to localized diagnostics messages doesnt take place throw new Error("cannot read file"); - } + }, }, errors); }); } diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index f5df90959ec39..e066c5a334536 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -40,7 +40,7 @@ describe("unittests:: Reuse program structure:: General", () => { baselines.push(ts.formatDiagnostics(program.getSemanticDiagnostics(), { getCurrentDirectory: () => program.getCurrentDirectory(), getNewLine: () => "\n", - getCanonicalFileName: ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames()) + getCanonicalFileName: ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames()), })); baselines.push("", ""); } @@ -53,11 +53,16 @@ describe("unittests:: Reuse program structure:: General", () => { function getFiles(): NamedSourceText[] { return [ { - name: "a.ts", text: SourceText.New(` + name: "a.ts", + text: SourceText.New( + ` /// /// /// -`, "", `var x = 1`) +`, + "", + `var x = 1`, + ), }, { name: "b.ts", text: SourceText.New(`/// `, "", `var y = 2`) }, { name: "c.ts", text: SourceText.New("", "", `var z = 1;`) }, @@ -268,7 +273,7 @@ describe("unittests:: Reuse program structure:: General", () => { ...host, getSourceFile(fileName) { return fileName === sourceFile.fileName ? sourceFile : program1.getSourceFile(fileName); - } + }, }; const program2 = ts.createProgram(["/a.ts"], options, updateHost, program1); baselineProgram(baselines, program2, updateHost); @@ -331,7 +336,7 @@ describe("unittests:: Reuse program structure:: General", () => { it("can reuse ambient module declarations from non-modified files", () => { const files = [ { name: "/a/b/app.ts", text: SourceText.New("", "import * as fs from 'fs'", "") }, - { name: "/a/b/node.d.ts", text: SourceText.New("", "", "declare module 'fs' {}") } + { name: "/a/b/node.d.ts", text: SourceText.New("", "", "declare module 'fs' {}") }, ]; const options = { target: ts.ScriptTarget.ES2015, traceResolution: true }; const program = newProgram(files, files.map(f => f.name), options); @@ -361,18 +366,19 @@ describe("unittests:: Reuse program structure:: General", () => { { name: "node_modules/@types/typerefs2/index.d.ts", text: SourceText.New("", "", "declare let z: string;") }, { name: "f1.ts", - text: - SourceText.New( - `/// ${newLine}/// ${newLine}/// `, - `import { B } from './b1';${newLine}export let BB = B;`, - "declare module './b1' { interface B { y: string; } }") + text: SourceText.New( + `/// ${newLine}/// ${newLine}/// `, + `import { B } from './b1';${newLine}export let BB = B;`, + "declare module './b1' { interface B { y: string; } }", + ), }, { name: "f2.ts", text: SourceText.New( `/// ${newLine}/// `, `import { B } from './b2';${newLine}import { BB } from './f1';`, - "(new BB).x; (new BB).y;") + "(new BB).x; (new BB).y;", + ), }, ]; @@ -427,7 +433,7 @@ describe("unittests:: Reuse program structure:: General", () => { const root = "/a.ts"; const compilerOptions = { target, moduleResolution: ts.ModuleResolutionKind.Node10 }; - function createRedirectProgram(useGetSourceFileByPath: boolean, options?: { bText: string, bVersion: string }): ProgramWithSourceTexts { + function createRedirectProgram(useGetSourceFileByPath: boolean, options?: { bText: string; bVersion: string; }): ProgramWithSourceTexts { const files: NamedSourceText[] = [ { name: "/node_modules/a/index.d.ts", @@ -538,21 +544,23 @@ describe("unittests:: Reuse program structure:: host is optional", () => { }); }); - describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { function getWhetherProgramIsUptoDate( program: ts.Program, newRootFileNames: string[], - newOptions: ts.CompilerOptions + newOptions: ts.CompilerOptions, ) { return ts.isProgramUptoDate( - program, newRootFileNames, newOptions, - path => program.getSourceFileByPath(path)!.version, /*fileExists*/ ts.returnFalse, + program, + newRootFileNames, + newOptions, + path => program.getSourceFileByPath(path)!.version, + /*fileExists*/ ts.returnFalse, /*hasInvalidatedResolutions*/ ts.returnFalse, /*hasInvalidatedLibResolutions*/ ts.returnFalse, /*hasChangedAutomaticTypeDirectiveNames*/ undefined, /*getParsedCommandLine*/ ts.returnUndefined, - /*projectReferences*/ undefined + /*projectReferences*/ undefined, ); } @@ -566,7 +574,7 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { function verifyProgramIsUptoDate( program: ts.Program, newRootFileNames: string[], - newOptions: ts.CompilerOptions + newOptions: ts.CompilerOptions, ) { const actual = getWhetherProgramIsUptoDate(program, newRootFileNames, newOptions); assert.isTrue(actual); @@ -577,7 +585,7 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { rootFiles, options, watchOptions: undefined, - system + system, })).getCurrentProgram().getProgram(); verifyProgramIsUptoDate(program, duplicate(rootFiles), duplicate(options)); } @@ -585,7 +593,7 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { function verifyProgramWithConfigFile(system: ts.System, configFileName: string) { const program = ts.createWatchProgram(ts.createWatchCompilerHostOfConfigFile({ configFileName, - system + system, })).getCurrentProgram().getProgram(); const { fileNames, options } = ts.parseConfigFileWithSystem(configFileName, {}, /*extendedConfigCache*/ undefined, /*watchOptionsToExtend*/ undefined, system, ts.notImplemented)!; // TODO: GH#18217 verifyProgramIsUptoDate(program, fileNames, options); @@ -600,15 +608,15 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { it("has empty options", () => { const file1: File = { path: "/a/b/file1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2: File = { path: "/a/b/file2.ts", - content: "let y = 1" + content: "let y = 1", }; const configFile: File = { path: "/a/b/tsconfig.json", - content: "{}" + content: "{}", }; verifyProgram([file1, file2, libFile, configFile], [file1.path, file2.path], {}, configFile.path); }); @@ -617,19 +625,19 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { const compilerOptions: ts.CompilerOptions = { lib: ["es5", "es2015.promise"] }; const app: File = { path: "/src/app.ts", - content: "var x: Promise;" + content: "var x: Promise;", }; const configFile: File = { path: "/src/tsconfig.json", - content: JSON.stringify({ compilerOptions }) + content: JSON.stringify({ compilerOptions }), }; const es5Lib: File = { path: "/compiler/lib.es5.d.ts", - content: "declare const eval: any" + content: "declare const eval: any", }; const es2015Promise: File = { path: "/compiler/lib.es2015.promise.d.ts", - content: "declare class Promise {}" + content: "declare class Promise {}", }; verifyProgram([app, configFile, es5Lib, es2015Promise], [app.path], compilerOptions, configFile.path); @@ -642,16 +650,16 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { "*": [ "packages/mail/data/*", "packages/styles/*", - "*" - ] - } + "*", + ], + }, }; const app: File = { path: "/src/packages/framework/app.ts", content: 'import classc from "module1/lib/file1";\ import classD from "module3/file3";\ let x = new classc();\ - let y = new classD();' + let y = new classD();', }; const module1: File = { path: "/src/packages/mail/data/module1/lib/file1.ts", @@ -663,11 +671,11 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { }; const module3: File = { path: "/src/packages/styles/module3/file3.ts", - content: "class classD { method() { return 10; } }\nexport default classD;" + content: "class classD { method() { return 10; } }\nexport default classD;", }; const configFile: File = { path: "/src/tsconfig.json", - content: JSON.stringify({ compilerOptions }) + content: JSON.stringify({ compilerOptions }), }; verifyProgram([app, module1, module2, module3, libFile, configFile], [app.path], compilerOptions, configFile.path); @@ -680,16 +688,16 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { "*": [ "packages/mail/data/*", "packages/styles/*", - "*" - ] - } + "*", + ], + }, }; const app: File = { path: "/src/packages/framework/app.ts", content: 'import classc from "module1/lib/file1";\ import classD from "module3/file3";\ let x = new classc();\ - let y = new classD();' + let y = new classD();', }; const module1: File = { path: "/src/packages/mail/data/module1/lib/file1.ts", @@ -701,11 +709,11 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { }; const module3: File = { path: "/src/packages/styles/module3/file3.ts", - content: "class classD { method() { return 10; } }\nexport default classD;" + content: "class classD { method() { return 10; } }\nexport default classD;", }; const configFile: File = { path: "/src/tsconfig.json", - content: JSON.stringify({ compilerOptions, include: ["packages/**/*.ts"] }) + content: JSON.stringify({ compilerOptions, include: ["packages/**/*.ts"] }), }; verifyProgramWithConfigFile(createWatchedSystem([app, module1, module2, module3, libFile, configFile]), configFile.path); }); @@ -720,7 +728,7 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { }; const module3: File = { path: "/src/packages/styles/module3/file3.ts", - content: "class classD { method() { return 10; } }\nexport default classD;" + content: "class classD { method() { return 10; } }\nexport default classD;", }; const rootFiles = [module1.path, module2.path, module3.path]; const system = createWatchedSystem([module1, module2, module3]); @@ -729,17 +737,16 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { rootFiles, options, watchOptions: undefined, - system + system, })).getCurrentProgram().getProgram(); verifyProgramIsUptoDate(program, duplicate(rootFiles), duplicate(options)); }); - }); describe("should return false when there is no change in compiler options but", () => { function verifyProgramIsNotUptoDate( program: ts.Program, newRootFileNames: string[], - newOptions: ts.CompilerOptions + newOptions: ts.CompilerOptions, ) { const actual = getWhetherProgramIsUptoDate(program, newRootFileNames, newOptions); assert.isFalse(actual); @@ -755,7 +762,7 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { }; const module3: File = { path: "/src/packages/styles/module3/file3.ts", - content: "class classD { method() { return 10; } }\nexport default classD;" + content: "class classD { method() { return 10; } }\nexport default classD;", }; const rootFiles = [module1.path, module2.path]; const newRootFiles = [module1.path, module2.path, module3.path]; @@ -765,7 +772,7 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { rootFiles, options, watchOptions: undefined, - system + system, })).getCurrentProgram().getProgram(); verifyProgramIsNotUptoDate(program, duplicate(newRootFiles), duplicate(options)); }); @@ -780,7 +787,7 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { }; const module3: File = { path: "/src/packages/styles/module3/file3.ts", - content: "class classD { method() { return 10; } }\nexport default classD;" + content: "class classD { method() { return 10; } }\nexport default classD;", }; const rootFiles = [module1.path, module2.path]; const newRootFiles = [module2.path, module3.path]; @@ -790,7 +797,7 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { rootFiles, options, watchOptions: undefined, - system + system, })).getCurrentProgram().getProgram(); verifyProgramIsNotUptoDate(program, duplicate(newRootFiles), duplicate(options)); }); diff --git a/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts index 7cc688965ad9c..ca397ab02d125 100644 --- a/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts +++ b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts @@ -9,21 +9,21 @@ describe("unittests:: services:: cancellableLanguageServiceOperations", () => { foo(f); `; 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"), ts.emptyOptions)!, r => assert.exists(r.items[0]) - ); + 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"), ts.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) - ); + 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)); }); 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) - ); + 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)); }); it("can cancel completion entry details mid-request", () => { @@ -48,14 +48,22 @@ describe("unittests:: services:: cancellableLanguageServiceOperations", () => { placeOpenBraceOnNewLineForFunctions: false, 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, /*source*/ undefined, {}, /*data*/ undefined)!, r => assert.exists(r.displayParts) - ); + 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, /*source*/ undefined, {}, /*data*/ 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 } + 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 }, ); }); }); @@ -70,7 +78,7 @@ function verifyOperationCancelledAfter(content: string, cancelAfter: number, checks = -Infinity; // Cancel just once, then disable cancellation, effectively } return result; - } + }, }; const adapter = new Harness.LanguageService.NativeLanguageServiceAdapter(token, options); const host = adapter.getHost(); diff --git a/src/testRunner/unittests/services/colorization.ts b/src/testRunner/unittests/services/colorization.ts index b3747eeadaba7..27232e8fd0b95 100644 --- a/src/testRunner/unittests/services/colorization.ts +++ b/src/testRunner/unittests/services/colorization.ts @@ -80,293 +80,139 @@ describe("unittests:: services:: Colorization", () => { describe("test getClassifications", () => { it("returns correct token classes", () => { - testLexicalClassification("var x: string = \"foo\" ?? \"bar\"; //Hello", - ts.EndOfLineState.None, - keyword("var"), - whitespace(" "), - identifier("x"), - punctuation(":"), - keyword("string"), - operator("="), - stringLiteral("\"foo\""), - whitespace(" "), - operator("??"), - stringLiteral("\"foo\""), - comment("//Hello"), - punctuation(";")); + testLexicalClassification('var x: string = "foo" ?? "bar"; //Hello', ts.EndOfLineState.None, keyword("var"), whitespace(" "), identifier("x"), punctuation(":"), keyword("string"), operator("="), stringLiteral('"foo"'), whitespace(" "), operator("??"), stringLiteral('"foo"'), comment("//Hello"), punctuation(";")); }); it("correctly classifies a comment after a divide operator", () => { - testLexicalClassification("1 / 2 // comment", - ts.EndOfLineState.None, - numberLiteral("1"), - whitespace(" "), - operator("/"), - numberLiteral("2"), - comment("// comment")); + testLexicalClassification("1 / 2 // comment", ts.EndOfLineState.None, numberLiteral("1"), whitespace(" "), operator("/"), numberLiteral("2"), comment("// comment")); }); it("correctly classifies a literal after a divide operator", () => { - testLexicalClassification("1 / 2, 3 / 4", - ts.EndOfLineState.None, - numberLiteral("1"), - whitespace(" "), - operator("/"), - numberLiteral("2"), - numberLiteral("3"), - numberLiteral("4"), - operator(",")); + testLexicalClassification("1 / 2, 3 / 4", ts.EndOfLineState.None, numberLiteral("1"), whitespace(" "), operator("/"), numberLiteral("2"), numberLiteral("3"), numberLiteral("4"), operator(",")); }); it("correctly classifies a multiline string with one backslash", () => { - testLexicalClassification("'line1\\", - ts.EndOfLineState.None, - stringLiteral("'line1\\"), - finalEndOfLineState(ts.EndOfLineState.InSingleQuoteStringLiteral)); + testLexicalClassification("'line1\\", ts.EndOfLineState.None, stringLiteral("'line1\\"), finalEndOfLineState(ts.EndOfLineState.InSingleQuoteStringLiteral)); }); it("correctly classifies a multiline string with three backslashes", () => { - testLexicalClassification("'line1\\\\\\", - ts.EndOfLineState.None, - stringLiteral("'line1\\\\\\"), - finalEndOfLineState(ts.EndOfLineState.InSingleQuoteStringLiteral)); + testLexicalClassification("'line1\\\\\\", ts.EndOfLineState.None, stringLiteral("'line1\\\\\\"), finalEndOfLineState(ts.EndOfLineState.InSingleQuoteStringLiteral)); }); it("correctly classifies an unterminated single-line string with no backslashes", () => { - testLexicalClassification("'line1", - ts.EndOfLineState.None, - stringLiteral("'line1"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("'line1", ts.EndOfLineState.None, stringLiteral("'line1"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("correctly classifies an unterminated single-line string with two backslashes", () => { - testLexicalClassification("'line1\\\\", - ts.EndOfLineState.None, - stringLiteral("'line1\\\\"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("'line1\\\\", ts.EndOfLineState.None, stringLiteral("'line1\\\\"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("correctly classifies an unterminated single-line string with four backslashes", () => { - testLexicalClassification("'line1\\\\\\\\", - ts.EndOfLineState.None, - stringLiteral("'line1\\\\\\\\"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("'line1\\\\\\\\", ts.EndOfLineState.None, stringLiteral("'line1\\\\\\\\"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("correctly classifies the continuing line of a multiline string ending in one backslash", () => { - testLexicalClassification("\\", - ts.EndOfLineState.InDoubleQuoteStringLiteral, - stringLiteral("\\"), - finalEndOfLineState(ts.EndOfLineState.InDoubleQuoteStringLiteral)); + testLexicalClassification("\\", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral("\\"), finalEndOfLineState(ts.EndOfLineState.InDoubleQuoteStringLiteral)); }); it("correctly classifies the continuing line of a multiline string ending in three backslashes", () => { - testLexicalClassification("\\", - ts.EndOfLineState.InDoubleQuoteStringLiteral, - stringLiteral("\\"), - finalEndOfLineState(ts.EndOfLineState.InDoubleQuoteStringLiteral)); + testLexicalClassification("\\", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral("\\"), finalEndOfLineState(ts.EndOfLineState.InDoubleQuoteStringLiteral)); }); it("correctly classifies the last line of an unterminated multiline string ending in no backslashes", () => { - testLexicalClassification(" ", - ts.EndOfLineState.InDoubleQuoteStringLiteral, - stringLiteral(" "), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification(" ", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral(" "), finalEndOfLineState(ts.EndOfLineState.None)); }); it("correctly classifies the last line of an unterminated multiline string ending in two backslashes", () => { - testLexicalClassification("\\\\", - ts.EndOfLineState.InDoubleQuoteStringLiteral, - stringLiteral("\\\\"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("\\\\", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral("\\\\"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("correctly classifies the last line of an unterminated multiline string ending in four backslashes", () => { - testLexicalClassification("\\\\\\\\", - ts.EndOfLineState.InDoubleQuoteStringLiteral, - stringLiteral("\\\\\\\\"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("\\\\\\\\", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral("\\\\\\\\"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("correctly classifies the last line of a multiline string", () => { - testLexicalClassification("'", - ts.EndOfLineState.InSingleQuoteStringLiteral, - stringLiteral("'"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("'", ts.EndOfLineState.InSingleQuoteStringLiteral, stringLiteral("'"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("correctly classifies an unterminated multiline comment", () => { - testLexicalClassification("/*", - ts.EndOfLineState.None, - comment("/*"), - finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); + testLexicalClassification("/*", ts.EndOfLineState.None, comment("/*"), finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); }); it("correctly classifies the termination of a multiline comment", () => { - testLexicalClassification(" */ ", - ts.EndOfLineState.InMultiLineCommentTrivia, - comment(" */"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification(" */ ", ts.EndOfLineState.InMultiLineCommentTrivia, comment(" */"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("correctly classifies the continuation of a multiline comment", () => { - testLexicalClassification("LOREM IPSUM DOLOR ", - ts.EndOfLineState.InMultiLineCommentTrivia, - comment("LOREM IPSUM DOLOR "), - finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); + testLexicalClassification("LOREM IPSUM DOLOR ", ts.EndOfLineState.InMultiLineCommentTrivia, comment("LOREM IPSUM DOLOR "), finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); }); it("correctly classifies an unterminated multiline comment on a line ending in '/*/'", () => { - testLexicalClassification(" /*/", - ts.EndOfLineState.None, - comment("/*/"), - finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); + testLexicalClassification(" /*/", ts.EndOfLineState.None, comment("/*/"), finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); }); it("correctly classifies an unterminated multiline comment with trailing space", () => { - testLexicalClassification("/* ", - ts.EndOfLineState.None, - comment("/* "), - finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); + testLexicalClassification("/* ", ts.EndOfLineState.None, comment("/* "), finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); }); it("correctly classifies a keyword after a dot", () => { - testLexicalClassification("a.var", - ts.EndOfLineState.None, - identifier("var")); + testLexicalClassification("a.var", ts.EndOfLineState.None, identifier("var")); }); it("correctly classifies a string literal after a dot", () => { - testLexicalClassification("a.\"var\"", - ts.EndOfLineState.None, - stringLiteral("\"var\"")); + testLexicalClassification('a."var"', ts.EndOfLineState.None, stringLiteral('"var"')); }); it("correctly classifies a keyword after a dot separated by comment trivia", () => { - testLexicalClassification("a./*hello world*/ var", - ts.EndOfLineState.None, - identifier("a"), - punctuation("."), - comment("/*hello world*/"), - identifier("var")); + testLexicalClassification("a./*hello world*/ var", ts.EndOfLineState.None, identifier("a"), punctuation("."), comment("/*hello world*/"), identifier("var")); }); it("classifies a property access with whitespace around the dot", () => { - testLexicalClassification(" x .\tfoo ()", - ts.EndOfLineState.None, - identifier("x"), - identifier("foo")); + testLexicalClassification(" x .\tfoo ()", ts.EndOfLineState.None, identifier("x"), identifier("foo")); }); it("classifies a keyword after a dot on previous line", () => { - testLexicalClassification("var", - ts.EndOfLineState.None, - keyword("var"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("var", ts.EndOfLineState.None, keyword("var"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("classifies multiple keywords properly", () => { - testLexicalClassification("public static", - ts.EndOfLineState.None, - keyword("public"), - keyword("static"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("public static", ts.EndOfLineState.None, keyword("public"), keyword("static"), finalEndOfLineState(ts.EndOfLineState.None)); - testLexicalClassification("public var", - ts.EndOfLineState.None, - keyword("public"), - identifier("var"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("public var", ts.EndOfLineState.None, keyword("public"), identifier("var"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("classifies a single line no substitution template string correctly", () => { - testLexicalClassification("`number number public string`", - ts.EndOfLineState.None, - stringLiteral("`number number public string`"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("`number number public string`", ts.EndOfLineState.None, stringLiteral("`number number public string`"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("classifies substitution parts of a template string correctly", () => { - testLexicalClassification("`number '${ 1 + 1 }' string '${ 'hello' }'`", - ts.EndOfLineState.None, - stringLiteral("`number '${"), - numberLiteral("1"), - operator("+"), - numberLiteral("1"), - stringLiteral("}' string '${"), - stringLiteral("'hello'"), - stringLiteral("}'`"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("`number '${ 1 + 1 }' string '${ 'hello' }'`", ts.EndOfLineState.None, stringLiteral("`number '${"), numberLiteral("1"), operator("+"), numberLiteral("1"), stringLiteral("}' string '${"), stringLiteral("'hello'"), stringLiteral("}'`"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("classifies an unterminated no substitution template string correctly", () => { - testLexicalClassification("`hello world", - ts.EndOfLineState.None, - stringLiteral("`hello world"), - finalEndOfLineState(ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate)); + testLexicalClassification("`hello world", ts.EndOfLineState.None, stringLiteral("`hello world"), finalEndOfLineState(ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate)); }); it("classifies the entire line of an unterminated multiline no-substitution/head template", () => { - testLexicalClassification("...", - ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, - stringLiteral("..."), - finalEndOfLineState(ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate)); + testLexicalClassification("...", ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, stringLiteral("..."), finalEndOfLineState(ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate)); }); it("classifies the entire line of an unterminated multiline template middle/end", () => { - testLexicalClassification("...", - ts.EndOfLineState.InTemplateMiddleOrTail, - stringLiteral("..."), - finalEndOfLineState(ts.EndOfLineState.InTemplateMiddleOrTail)); + testLexicalClassification("...", ts.EndOfLineState.InTemplateMiddleOrTail, stringLiteral("..."), finalEndOfLineState(ts.EndOfLineState.InTemplateMiddleOrTail)); }); it("classifies a termination of a multiline template head", () => { - testLexicalClassification("...${", - ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, - stringLiteral("...${"), - finalEndOfLineState(ts.EndOfLineState.InTemplateSubstitutionPosition)); + testLexicalClassification("...${", ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, stringLiteral("...${"), finalEndOfLineState(ts.EndOfLineState.InTemplateSubstitutionPosition)); }); it("classifies the termination of a multiline no substitution template", () => { - testLexicalClassification("...`", - ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, - stringLiteral("...`"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("...`", ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, stringLiteral("...`"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("classifies the substitution parts and middle/tail of a multiline template string", () => { - testLexicalClassification("${ 1 + 1 }...`", - ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, - stringLiteral("${"), - numberLiteral("1"), - operator("+"), - numberLiteral("1"), - stringLiteral("}...`"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("${ 1 + 1 }...`", ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, stringLiteral("${"), numberLiteral("1"), operator("+"), numberLiteral("1"), stringLiteral("}...`"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("classifies a template middle and propagates the end of line state", () => { - testLexicalClassification("${ 1 + 1 }...`", - ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, - stringLiteral("${"), - numberLiteral("1"), - operator("+"), - numberLiteral("1"), - stringLiteral("}...`"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("${ 1 + 1 }...`", ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, stringLiteral("${"), numberLiteral("1"), operator("+"), numberLiteral("1"), stringLiteral("}...`"), finalEndOfLineState(ts.EndOfLineState.None)); }); it("classifies substitution expressions with curly braces appropriately", () => { let pos = 0; let lastLength = 0; - testLexicalClassification("...${ () => { } } ${ { x: `1` } }...`", - ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, - stringLiteral(track("...${"), pos), - punctuation(track(" ", "("), pos), - punctuation(track(")"), pos), - punctuation(track(" ", "=>"), pos), - punctuation(track(" ", "{"), pos), - punctuation(track(" ", "}"), pos), - stringLiteral(track(" ", "} ${"), pos), - punctuation(track(" ", "{"), pos), - identifier(track(" ", "x"), pos), - punctuation(track(":"), pos), - stringLiteral(track(" ", "`1`"), pos), - punctuation(track(" ", "}"), pos), - stringLiteral(track(" ", "}...`"), pos), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("...${ () => { } } ${ { x: `1` } }...`", ts.EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate, stringLiteral(track("...${"), pos), punctuation(track(" ", "("), pos), punctuation(track(")"), pos), punctuation(track(" ", "=>"), pos), punctuation(track(" ", "{"), pos), punctuation(track(" ", "}"), pos), stringLiteral(track(" ", "} ${"), pos), punctuation(track(" ", "{"), pos), identifier(track(" ", "x"), pos), punctuation(track(":"), pos), stringLiteral(track(" ", "`1`"), pos), punctuation(track(" ", "}"), pos), stringLiteral(track(" ", "}...`"), pos), finalEndOfLineState(ts.EndOfLineState.None)); // Adjusts 'pos' by accounting for the length of each portion of the string, // but only return the last given string @@ -380,37 +226,19 @@ describe("unittests:: services:: Colorization", () => { }); it("classifies partially written generics correctly.", () => { - testLexicalClassification("Foo { // Test conflict markers. testLexicalClassification( - "class C {\r\n\ +"class C {\r\n\ <<<<<<< HEAD\r\n\ v = 1;\r\n\ =======\r\n\ @@ -429,10 +257,11 @@ describe("unittests:: services:: Colorization", () => { comment("=======\r\n v = 2;\r\n"), comment(">>>>>>> Branch - a"), punctuation("}"), - finalEndOfLineState(ts.EndOfLineState.None)); + finalEndOfLineState(ts.EndOfLineState.None), + ); testLexicalClassification( - "<<<<<<< HEAD\r\n\ +"<<<<<<< HEAD\r\n\ class C { }\r\n\ =======\r\n\ class D { }\r\n\ @@ -445,10 +274,11 @@ class D { }\r\n\ punctuation("}"), comment("=======\r\nclass D { }\r\n"), comment(">>>>>>> Branch - a"), - finalEndOfLineState(ts.EndOfLineState.None)); + 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\ @@ -470,10 +300,11 @@ class D { }\r\n\ comment("=======\r\n v = 2;\r\n"), comment(">>>>>>> Branch - a"), punctuation("}"), - finalEndOfLineState(ts.EndOfLineState.None)); + finalEndOfLineState(ts.EndOfLineState.None), + ); testLexicalClassification( - "<<<<<<< HEAD\r\n\ +"<<<<<<< HEAD\r\n\ class C { }\r\n\ ||||||| merged common ancestors\r\n\ class E { }\r\n\ @@ -489,22 +320,12 @@ class D { }\r\n\ comment("||||||| merged common ancestors\r\nclass E { }\r\n"), comment("=======\r\nclass D { }\r\n"), comment(">>>>>>> Branch - a"), - finalEndOfLineState(ts.EndOfLineState.None)); + finalEndOfLineState(ts.EndOfLineState.None), + ); }); it("'of' keyword", () => { - testLexicalClassification("for (var of of of) { }", - ts.EndOfLineState.None, - keyword("for"), - punctuation("("), - keyword("var"), - keyword("of"), - keyword("of"), - keyword("of"), - punctuation(")"), - punctuation("{"), - punctuation("}"), - finalEndOfLineState(ts.EndOfLineState.None)); + testLexicalClassification("for (var of of of) { }", ts.EndOfLineState.None, keyword("for"), punctuation("("), keyword("var"), keyword("of"), keyword("of"), keyword("of"), punctuation(")"), punctuation("{"), punctuation("}"), finalEndOfLineState(ts.EndOfLineState.None)); }); }); }); diff --git a/src/testRunner/unittests/services/convertToAsyncFunction.ts b/src/testRunner/unittests/services/convertToAsyncFunction.ts index 00b46896aaaa2..657fd6a222727 100644 --- a/src/testRunner/unittests/services/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/services/convertToAsyncFunction.ts @@ -1,6 +1,8 @@ import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; -import { createProjectService } from "../helpers/tsserver"; +import { + createProjectService, +} from "../helpers/tsserver"; import { createServerHost, File, @@ -271,15 +273,14 @@ interface PromiseConstructor { declare var Promise: PromiseConstructor; interface RegExp {} interface String { charAt: any; } -interface Array {}` +interface Array {}`, }; const moduleFile: File = { path: "/module.ts", - content: -`export function fn(res: any): any { + content: `export function fn(res: any): any { return res; -}` +}`, }; type WithSkipAndOnly = ((...args: T) => void) & { @@ -328,8 +329,7 @@ function testConvertToAsyncFunction(it: Mocha.PendingTestFunction, caption: stri const extensions = expectFailure ? [ts.Extension.Ts] : [ts.Extension.Ts, ts.Extension.Js]; - extensions.forEach(extension => - it(`${caption} [${extension}]`, () => runBaseline(extension))); + extensions.forEach(extension => it(`${caption} [${extension}]`, () => runBaseline(extension))); function runBaseline(extension: ts.Extension) { const path = "/a" + extension; @@ -344,7 +344,7 @@ function testConvertToAsyncFunction(it: Mocha.PendingTestFunction, caption: stri const f = { path, - content: t.source + content: t.source, }; const sourceFile = program.getSourceFile(path)!; @@ -356,11 +356,12 @@ function testConvertToAsyncFunction(it: Mocha.PendingTestFunction, caption: stri cancellationToken: { throwIfCancellationRequested: ts.noop, isCancellationRequested: ts.returnFalse }, preferences: ts.emptyOptions, host: notImplementedHost, - formatContext: ts.formatting.getFormatContext(ts.testFormatSettings, notImplementedHost) + formatContext: ts.formatting.getFormatContext(ts.testFormatSettings, notImplementedHost), }; const diagnostics = languageService.getSuggestionDiagnostics(f.path); - const diagnostic = ts.find(diagnostics, diagnostic => diagnostic.messageText === ts.Diagnostics.This_may_be_converted_to_an_async_function.message && + const diagnostic = ts.find(diagnostics, diagnostic => + diagnostic.messageText === ts.Diagnostics.This_may_be_converted_to_an_async_function.message && diagnostic.start === context.span.start && diagnostic.length === context.span.length); const actions = ts.codefix.getFixes(context); const action = ts.find(actions, action => action.description === ts.Diagnostics.Convert_to_async_function.message); @@ -446,58 +447,93 @@ const _testConvertToAsyncFunctionWithModule = createTestWrapper((it, caption: st }); describe("unittests:: services:: convertToAsyncFunction", () => { - _testConvertToAsyncFunction("convertToAsyncFunction_basic", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_basic", + ` function [#|f|](): Promise{ return fetch('https://typescriptlang.org').then(result => { console.log(result) }); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_arrayBindingPattern", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_arrayBindingPattern", + ` function [#|f|](): Promise{ return fetch('https://typescriptlang.org').then(([result]) => { console.log(result) }); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_objectBindingPattern", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_objectBindingPattern", + ` function [#|f|](): Promise{ return fetch('https://typescriptlang.org').then(({ result }) => { console.log(result) }); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_arrayBindingPatternRename", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_arrayBindingPatternRename", + ` function [#|f|](): Promise{ const result = getResult(); return fetch('https://typescriptlang.org').then(([result]) => { console.log(result) }); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_objectBindingPatternRename", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_objectBindingPatternRename", + ` 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. */ // a /*b*/ return /*c*/ fetch( /*d*/ 'https://typescriptlang.org' /*e*/).then( /*f*/ result /*g*/ => { /*h*/ console.log(/*i*/ result /*j*/) /*k*/}/*l*/); // m -}`); +}`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_ArrowFunction", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_ArrowFunction", + ` [#|():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)); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_Catch", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_Catch", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(result => { console.log(result); }).catch(err => { console.log(err); }); -}`); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_CatchAndRej", ` +}`, + ); + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_CatchAndRej", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(result => { console.log(result); }, rejection => { console.log("rejected:", rejection); }).catch(err => { console.log(err) }); -}`); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_CatchAndRejRef", ` +}`, + ); + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_CatchAndRejRef", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(res, rej).catch(catch_err) } @@ -509,8 +545,11 @@ function rej(rejection){ } function catch_err(err){ console.log(err); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchRef", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchRef", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(res).catch(catch_err) } @@ -520,49 +559,66 @@ function res(result){ function catch_err(err){ console.log(err); } -`); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchNoBrackets", ` +`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchNoBrackets", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(result => console.log(result)).catch(err => console.log(err)); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_IgnoreArgs1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_IgnoreArgs1", + ` function [#|f|](): Promise { return fetch('https://typescriptlang.org').then( _ => { console.log("done"); }); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_IgnoreArgs2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_IgnoreArgs2", + ` function [#|f|](): Promise { return fetch('https://typescriptlang.org').then( () => console.log("done") ); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_IgnoreArgs3", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_IgnoreArgs3", + ` function [#|f|](): Promise { return fetch('https://typescriptlang.org').then( () => console.log("almost done") ).then( () => console.log("done") ); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_IgnoreArgs4", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_IgnoreArgs4", + ` function [#|f|]() { return fetch('https://typescriptlang.org').then(res); } function res(){ console.log("done"); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Method", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Method", + ` class Parser { [#|f|]():Promise { return fetch('https://typescriptlang.org').then(result => console.log(result)); } -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_MultipleCatches", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_MultipleCatches", + ` function [#|f|](): Promise { return fetch('https://typescriptlang.org').then(res => console.log(res)).catch(err => console.log("err", err)).catch(err2 => console.log("err2", err2)); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_MultipleThens", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_MultipleThens", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(res).then(res2); } @@ -571,9 +627,11 @@ function res(result){ } function res2(result2){ console.log(result2); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_MultipleThensSameVarName", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_MultipleThensSameVarName", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(res).then(res2); } @@ -583,65 +641,85 @@ function res(result){ function res2(result){ return result.bodyUsed; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_NoRes", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_NoRes", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(null, rejection => console.log("rejected:", rejection)); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_NoRes2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_NoRes2", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(undefined).catch(rej => console.log(rej)); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_NoRes3", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_NoRes3", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').catch(rej => console.log(rej)); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_NoRes4", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_NoRes4", + ` function [#|f|]() { return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection)); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_NoCatchHandler", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_NoCatchHandler", + ` function [#|f|]() { return fetch('https://typescriptlang.org').then(x => x.statusText).catch(undefined); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestion", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_NoSuggestion", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org'); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_PromiseDotAll", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_PromiseDotAll", + ` function [#|f|]():Promise{ return Promise.all([fetch('https://typescriptlang.org'), fetch('https://microsoft.com'), fetch('https://youtube.com')]).then(function(vals){ vals.forEach(console.log); }); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestionNoPromise", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_NoSuggestionNoPromise", + ` function [#|f|]():void{ } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Rej", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_Rej", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(result => { console.log(result); }, rejection => { console.log("rejected:", rejection); }); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_RejRef", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_RejRef", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(res, rej); } @@ -651,26 +729,32 @@ function res(result){ function rej(err){ console.log(err); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_RejNoBrackets", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_RejNoBrackets", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(result => console.log(result), rejection => console.log("rejected:", rejection)); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_ResRef", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_ResRef", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(res); } function res(result){ return result.ok; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_ResRef1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_ResRef1", + ` class Foo { public [#|method|](): Promise { return fetch('a').then(this.foo); @@ -680,9 +764,12 @@ class Foo { return res.ok; } } - `); + `, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_ResRef2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_ResRef2", + ` class Foo { public [#|method|](): Promise { return fetch('a').then(this.foo); @@ -690,65 +777,80 @@ class Foo { private foo = res => res; } - `); + `, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_ResRef3", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_ResRef3", + ` const res = (result) => { return result.ok; } function [#|f|](): Promise { return fetch('https://typescriptlang.org').then(res); } - ` + `, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestionResRef1", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_NoSuggestionResRef1", + ` const res = 1; function [#|f|]() { return fetch('https://typescriptlang.org').then(res); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestionResRef2", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_NoSuggestionResRef2", + ` class Foo { private foo = 1; public [#|method|](): Promise { return fetch('a').then(this.foo); } } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestionResRef3", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_NoSuggestionResRef3", + ` const res = undefined; function [#|f|]() { return fetch('https://typescriptlang.org').then(res); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestionResRef4", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_NoSuggestionResRef4", + ` class Foo { private foo = undefined; public [#|method|](): Promise { return fetch('a').then(this.foo); } } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_ResRefNoReturnVal", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_ResRefNoReturnVal", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(res); } function res(result){ console.log(result); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_ResRefNoReturnVal1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_ResRefNoReturnVal1", + ` class Foo { public [#|method|](): Promise { return fetch('a').then(this.foo); @@ -758,35 +860,46 @@ class Foo { console.log(res); } } - `); + `, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_NoBrackets", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_NoBrackets", + ` function [#|f|]():Promise { return fetch('https://typescriptlang.org').then(result => console.log(result)); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally1", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_Finally1", + ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").then(res => console.log(res)).catch(rej => console.log("error", rej)).finally(console.log("finally!")); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally2", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_Finally2", + ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").then(res => console.log(res)).finally(console.log("finally!")); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally3", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_Finally3", + ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").finally(console.log("finally!")); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromise", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_InnerPromise", + ` function [#|innerPromise|](): Promise { return fetch("https://typescriptlang.org").then(resp => { var blob2 = resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); @@ -795,9 +908,11 @@ function [#|innerPromise|](): Promise { return blob.toString(); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRet", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_InnerPromiseRet", + ` function [#|innerPromise|](): Promise { return fetch("https://typescriptlang.org").then(resp => { return resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); @@ -805,10 +920,12 @@ function [#|innerPromise|](): Promise { return blob.toString(); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRetBinding1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_InnerPromiseRetBinding1", + ` function [#|innerPromise|](): Promise { return fetch("https://typescriptlang.org").then(resp => { return resp.blob().then(({ blob }) => blob.byteOffset).catch(({ message }) => 'Error ' + message); @@ -816,10 +933,12 @@ function [#|innerPromise|](): Promise { return blob.toString(); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRetBinding2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_InnerPromiseRetBinding2", + ` function [#|innerPromise|](): Promise { return fetch("https://typescriptlang.org").then(resp => { return resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); @@ -827,10 +946,12 @@ function [#|innerPromise|](): Promise { return x.toString(); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRetBinding3", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_InnerPromiseRetBinding3", + ` function [#|innerPromise|](): Promise { return fetch("https://typescriptlang.org").then(resp => { return resp.blob().then(({ blob }) => blob.byteOffset).catch(({ message }) => 'Error ' + message); @@ -838,10 +959,12 @@ function [#|innerPromise|](): Promise { return (x || y).toString(); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseRetBinding4", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_InnerPromiseRetBinding4", + ` function [#|innerPromise|](): Promise { return fetch("https://typescriptlang.org").then(resp => { return resp.blob().then(({ blob }: { blob: { byteOffset: number } }) => [0, blob.byteOffset]).catch(({ message }: Error) => ['Error ', message]); @@ -849,25 +972,31 @@ function [#|innerPromise|](): Promise { return (x || y).toString(); }); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn01", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn01", + ` function [#|f|]() { let blob = fetch("https://typescriptlang.org").then(resp => console.log(resp)); return blob; } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn02", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn02", + ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); blob.then(resp => console.log(resp)); return blob; } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn03", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn03", + ` function [#|f|]() { let blob = fetch("https://typescriptlang.org") let blob2 = blob.then(resp => console.log(resp)); @@ -878,9 +1007,11 @@ function [#|f|]() { function err (rej) { console.log(rej) } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn04", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn04", + ` function [#|f|]() { var blob = fetch("https://typescriptlang.org").then(res => console.log(res)), blob2 = fetch("https://microsoft.com").then(res => res.ok).catch(err); return blob; @@ -888,27 +1019,33 @@ function [#|f|]() { function err (rej) { console.log(rej) } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn05", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn05", + ` function [#|f|]() { var blob = fetch("https://typescriptlang.org").then(res => console.log(res)); blob.then(x => x); return blob; } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn06", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn06", + ` function [#|f|]() { var blob = fetch("https://typescriptlang.org"); return blob; } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn07", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn07", + ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); let blob2 = fetch("https://microsoft.com"); @@ -916,10 +1053,12 @@ function [#|f|]() { blob.then(resp => console.log(resp)); return blob; } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn08", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn08", + ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); if (!blob.ok){ @@ -928,10 +1067,12 @@ function [#|f|]() { blob.then(resp => console.log(resp)); return blob; } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn09", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn09", + ` function [#|f|]() { let blob3; let blob = fetch("https://typescriptlang.org"); @@ -941,11 +1082,12 @@ function [#|f|]() { blob3 = blob2.catch(rej => rej.ok); return blob; } -` +`, ); - - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn10", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn10", + ` function [#|f|]() { let blob3; let blob = fetch("https://typescriptlang.org"); @@ -956,20 +1098,22 @@ function [#|f|]() { blob3 = blob2; return blob; } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn11", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_VarReturn11", + ` function [#|f|]() { let blob; return blob; } -` +`, ); - - - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Param1", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_Param1", + ` function [#|f|]() { return my_print(fetch("https://typescriptlang.org").then(res => console.log(res))); } @@ -980,10 +1124,12 @@ function my_print (resp) { return 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)); } @@ -995,10 +1141,12 @@ function my_print (resp): Promise { } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_MultipleReturns1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_MultipleReturns1", + ` function [#|f|](): Promise { let x = fetch("https://microsoft.com").then(res => console.log("Microsoft:", res)); if (x.ok) { @@ -1008,10 +1156,12 @@ function [#|f|](): Promise { var blob = resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_MultipleReturns2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_MultipleReturns2", + ` function [#|f|](): Promise { let x = fetch("https://microsoft.com").then(res => console.log("Microsoft:", res)); if (x.ok) { @@ -1022,11 +1172,12 @@ function [#|f|](): Promise { return fetch("https://microsoft.com").then(res => console.log("Another one!")); }); } -` +`, ); - - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_SeperateLines", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_SeperateLines", + ` function [#|f|](): Promise { var blob = fetch("https://typescriptlang.org") blob.then(resp => { @@ -1038,11 +1189,12 @@ function [#|f|](): Promise { return blob; } -` +`, ); - - _testConvertToAsyncFunction("convertToAsyncFunction_InnerVarNameConflict", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_InnerVarNameConflict", + ` function [#|f|](): Promise { return fetch("https://typescriptlang.org").then(resp => { var blob = resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); @@ -1050,9 +1202,11 @@ function [#|f|](): Promise { return blob.toString(); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_InnerPromiseSimple", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_InnerPromiseSimple", + ` function [#|f|](): Promise { return fetch("https://typescriptlang.org").then(resp => { return resp.blob().then(blob => blob.byteOffset); @@ -1060,9 +1214,11 @@ function [#|f|](): Promise { return blob.toString(); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_PromiseAllAndThen1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_PromiseAllAndThen1", + ` function [#|f|]() { return Promise.resolve().then(function () { return Promise.all([fetch("https://typescriptlang.org"), fetch("https://microsoft.com"), Promise.resolve().then(function () { @@ -1070,10 +1226,12 @@ function [#|f|]() { }).then(res => res.toString())]); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_PromiseAllAndThen2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_PromiseAllAndThen2", + ` function [#|f|]() { return Promise.resolve().then(function () { return Promise.all([fetch("https://typescriptlang.org"), fetch("https://microsoft.com"), Promise.resolve().then(function () { @@ -1081,29 +1239,35 @@ function [#|f|]() { })]).then(res => res.toString()); }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_PromiseAllAndThen3", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_PromiseAllAndThen3", + ` function [#|f|]() { return Promise.resolve().then(() => Promise.all([fetch("https://typescriptlang.org"), fetch("https://microsoft.com"), Promise.resolve().then(function () { return fetch("https://github.com"); }).then(res => res.toString())])); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_PromiseAllAndThen4", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_PromiseAllAndThen4", + ` function [#|f|]() { return Promise.resolve().then(() => Promise.all([fetch("https://typescriptlang.org"), fetch("https://microsoft.com"), Promise.resolve().then(function () { return fetch("https://github.com"); })]).then(res => res.toString())); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Scope1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Scope1", + ` function [#|f|]() { var var1: Response, var2; return fetch('https://typescriptlang.org').then( _ => @@ -1118,9 +1282,12 @@ function [#|f|]() { function res(response){ console.log(response); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_Conditionals", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Conditionals", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res => { if (res.ok) { @@ -1136,10 +1303,12 @@ function [#|f|](){ } }); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThen", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThen", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1151,10 +1320,12 @@ function res(result){ function rej(reject){ return reject; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes01", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMatchingTypes01", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1166,10 +1337,12 @@ function res(result): number { function rej(reject): number { return 3; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes01NoAnnotations", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMatchingTypes01NoAnnotations", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1181,11 +1354,12 @@ function res(result){ function rej(reject){ return 3; } -` +`, ); - - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMatchingTypes02", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res => 0).catch(rej => 1).then(res); } @@ -1193,10 +1367,12 @@ function [#|f|](){ function res(result): number { return 5; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02NoAnnotations", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMatchingTypes02NoAnnotations", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res => 0).catch(rej => 1).then(res); } @@ -1204,10 +1380,12 @@ function [#|f|](){ function res(result){ return 5; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes01", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMismatchTypes01", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1219,10 +1397,12 @@ function res(result){ function rej(reject){ return "Error"; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMismatchTypes02", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1234,10 +1414,12 @@ function res(result){ function rej(reject): Response{ return reject; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02NoAnnotations", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMismatchTypes02NoAnnotations", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1249,11 +1431,12 @@ function res(result){ function rej(reject){ return reject; } -` +`, ); - - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes03", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMismatchTypes03", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1265,10 +1448,12 @@ function res(result){ function rej(reject){ return Promise.resolve(1); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes04", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_CatchFollowedByThenMismatchTypes04", + ` interface a { name: string; age: number; @@ -1290,10 +1475,12 @@ function res(result): b{ function rej(reject): a{ return {name: "myName", age: 27}; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_ParameterNameCollision", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_ParameterNameCollision", + ` async function foo(x: T): Promise { return x; } @@ -1301,45 +1488,59 @@ async function foo(x: T): Promise { function [#|bar|](x: T): Promise { return foo(x).then(foo) } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Return1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Return1", + ` function [#|f|](p: Promise) { return p.catch((error: Error) => { return Promise.reject(error); }); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Return2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Return2", + ` function [#|f|](p: Promise) { return p.catch((error: Error) => Promise.reject(error)); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Return3", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Return3", + ` function [#|f|](p: Promise) { return p.catch(function (error: Error) { return Promise.reject(error); }); -}` +}`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_LocalReturn", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_LocalReturn", + ` function [#|f|]() { let x = fetch("https://typescriptlang.org").then(res => console.log(res)); return x.catch(err => console.log("Error!", err)); } -`); - _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(); } @@ -1351,27 +1552,33 @@ function res(result){ function rej(reject){ return reject; } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Scope2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Scope2", + ` function [#|f|](){ var i:number; return fetch("https://typescriptlang.org").then(i => i.ok).then(res => i+1).catch(err => i-1) } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Loop", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Loop", + ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res => { for(let i=0; i<10; i++){ console.log(res); }}) } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Conditional2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Conditional2", + ` function [#|f|](){ var res = 100; if (res > 50) { @@ -1385,10 +1592,12 @@ function [#|f|](){ function res_func(result){ console.log(result); } -` +`, ); - _testConvertToAsyncFunction("convertToAsyncFunction_Scope3", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_Scope3", + ` function [#|f|]() { var obj; return fetch("https://typescriptlang.org").then(function (res) { @@ -1399,10 +1608,12 @@ function [#|f|]() { }; }); } -` +`, ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunctionWrongLocation", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_NestedFunctionWrongLocation", + ` function [#|f|]() { function fn2(){ function fn3(){ @@ -1412,9 +1623,12 @@ function [#|f|]() { } return fn2(); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_NestedFunctionRightLocation", + ` function f() { function fn2(){ function [#|fn3|](){ @@ -1424,67 +1638,97 @@ function f() { } return fn2(); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_UntypedFunction", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_UntypedFunction", + ` function [#|f|]() { return Promise.resolve().then(res => console.log(res)); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_TernaryConditional", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_TernaryConditional", + ` function [#|f|]() { let i; return Promise.resolve().then(res => res ? i = res : i = 100); } -`); +`, + ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_ResRejNoArgsArrow", ` + _testConvertToAsyncFunctionFailed( + "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); } function res({ status, trailer }){ console.log(status); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_bindingPatternNameCollision", + ` function [#|f|]() { const result = 'https://typescriptlang.org'; return fetch(result).then(res); @@ -1492,68 +1736,98 @@ function [#|f|]() { function res({ status, trailer }){ console.log(status); } -`); +`, + ); - _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")); } function res(result) { return Promise.resolve().then(x => console.log(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)) .catch(err => console.log(err)); } -`); +`, + ); - _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_noArgs1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_noArgs1", + ` function delay(millis: number): Promise { throw "no" } @@ -1565,9 +1839,12 @@ function [#|main2|]() { .then(() => { console.log("."); return delay(500); }) .then(() => { console.log("."); return delay(500); }) } - `); + `, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_noArgs2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_noArgs2", + ` function delay(millis: number): Promise { throw "no" } @@ -1579,22 +1856,31 @@ function [#|main2|]() { .then(() => delay(500)) .then(() => 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'); }) } -`); - _testConvertToAsyncFunction("convertToAsyncFunction_decoratedMethod", ` +`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_decoratedMethod", + ` function decorator() { return (target: any, key: any, descriptor: PropertyDescriptor) => descriptor; } @@ -1604,9 +1890,12 @@ class Foo { return fetch('a').then(x => x); } } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_decoratedMethodWithSingleLineComment", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_decoratedMethodWithSingleLineComment", + ` function decorator() { return (target: any, key: any, descriptor: PropertyDescriptor) => descriptor; } @@ -1617,9 +1906,12 @@ class Foo { return fetch('a').then(x => x); } } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_decoratedMethodWithMultipleLineComment", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_decoratedMethodWithMultipleLineComment", + ` function decorator() { return (target: any, key: any, descriptor: PropertyDescriptor) => descriptor; } @@ -1632,9 +1924,12 @@ class Foo { return fetch('a').then(x => x); } } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_decoratedMethodWithModifier", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_decoratedMethodWithModifier", + ` function decorator() { return (target: any, key: any, descriptor: PropertyDescriptor) => descriptor; } @@ -1644,17 +1939,23 @@ class Foo { return fetch('a').then(x => x); } } -`); +`, + ); - _testConvertToAsyncFunctionFailedSuggestion("convertToAsyncFunction_OutermostOnlyFailure", ` + _testConvertToAsyncFunctionFailedSuggestion( + "convertToAsyncFunction_OutermostOnlyFailure", + ` function foo() { return fetch('a').then([#|() => {|] return fetch('b').then(() => 'c'); }) } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_thenTypeArgument1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_thenTypeArgument1", + ` type APIResponse = { success: true, data: T } | { success: false }; function wrapResponse(response: T): APIResponse { @@ -1664,9 +1965,12 @@ function wrapResponse(response: T): APIResponse { function [#|get|]() { return Promise.resolve(undefined!).then>(wrapResponse); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_thenTypeArgument2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_thenTypeArgument2", + ` type APIResponse = { success: true, data: T } | { success: false }; function wrapResponse(response: T): APIResponse { @@ -1676,9 +1980,12 @@ function wrapResponse(response: T): APIResponse { function [#|get|]() { return Promise.resolve(undefined!).then>(d => wrapResponse(d)); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_thenTypeArgument3", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_thenTypeArgument3", + ` type APIResponse = { success: true, data: T } | { success: false }; function wrapResponse(response: T): APIResponse { @@ -1691,9 +1998,12 @@ function [#|get|]() { return wrapResponse(d); }); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_catchTypeArgument1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_catchTypeArgument1", + ` type APIResponse = { success: true, data: T } | { success: false }; function [#|get|]() { @@ -1701,14 +2011,20 @@ function [#|get|]() { .resolve>({ success: true, data: { email: "" } }) .catch>(() => ({ success: false })); } -`); +`, + ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_threeArguments", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction_threeArguments", + ` function [#|f|]() { return Promise.resolve().then(undefined, undefined, () => 1); -}`); +}`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_callbackArgument", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_callbackArgument", + ` function foo(props: any): void { return props; } @@ -1719,54 +2035,75 @@ const fn = (): Promise<(message: string) => void> => function [#|f|]() { return fn().then(res => res("test")); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_emptyCatch1", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_emptyCatch1", + ` function [#|f|]() { return Promise.resolve().catch(); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_emptyCatch2", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_emptyCatch2", + ` function [#|f|]() { return Promise.resolve(0).then(x => x).catch(); } -`); +`, + ); - _testConvertToAsyncFunctionWithModule("convertToAsyncFunction_importedFunction", ` + _testConvertToAsyncFunctionWithModule( + "convertToAsyncFunction_importedFunction", + ` import { fn } from "./module"; function [#|f|]() { return Promise.resolve(0).then(fn); } -`); +`, + ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction__NoSuggestionInFunctionsWithNonFixableReturnStatements1", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction__NoSuggestionInFunctionsWithNonFixableReturnStatements1", + ` function f(x: number): Promise; function f(): void; function [#|f|](x?: number): Promise | void { if (!x) return; return fetch('').then(() => {}); } -`); +`, + ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction__NoSuggestionInFunctionsWithNonFixableReturnStatements2", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction__NoSuggestionInFunctionsWithNonFixableReturnStatements2", + ` function f(x: number): Promise; function f(): number; function [#|f|](x?: number): Promise | number { if (x) return x; return fetch('').then(() => {}); } -`); +`, + ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction__NoSuggestionInGetters", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction__NoSuggestionInGetters", + ` class Foo { get [#|m|](): Promise { return Promise.resolve(1).then(n => n); } } -`); +`, + ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction__NoSuggestionForGeneratorCallbacks", ` + _testConvertToAsyncFunctionFailed( + "convertToAsyncFunction__NoSuggestionForGeneratorCallbacks", + ` function [#|foo|](p: Promise) { return p.then(function* (strings) { for (const s of strings) { @@ -1774,54 +2111,84 @@ function [#|foo|](p: Promise) { } }); } -`); +`, + ); - _testConvertToAsyncFunction("convertToAsyncFunction_thenNoArguments", ` + _testConvertToAsyncFunction( + "convertToAsyncFunction_thenNoArguments", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().then(); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_catchNoArguments", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_catchNoArguments", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().catch(); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_chainedThenCatchThen", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_chainedThenCatchThen", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().then(x => Promise.resolve(x + 1)).catch(() => 1).then(y => y + 2); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_finally", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_finally", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().finally(() => console.log("done")); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_finallyNoArguments", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_finallyNoArguments", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().finally(); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_finallyNull", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_finallyNull", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().finally(null); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_finallyUndefined", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_finallyUndefined", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().finally(undefined); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_thenFinally", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_thenFinally", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().then(x => x + 1).finally(() => console.log("done")); -}`); - _testConvertToAsyncFunction("convertToAsyncFunction_thenFinallyThen", ` +}`, + ); + _testConvertToAsyncFunction( + "convertToAsyncFunction_thenFinallyThen", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().then(x => Promise.resolve(x + 1)).finally(() => console.log("done")).then(y => y + 2); -}`); - _testConvertToAsyncFunctionFailedAction("convertToAsyncFunction_returnInBranch", ` +}`, + ); + _testConvertToAsyncFunctionFailedAction( + "convertToAsyncFunction_returnInBranch", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().then(() => { @@ -1833,8 +2200,11 @@ function [#|f|](): Promise { return a + 1; }); } -`); - _testConvertToAsyncFunctionFailedAction("convertToAsyncFunction_partialReturnInBranch", ` +`, + ); + _testConvertToAsyncFunctionFailedAction( + "convertToAsyncFunction_partialReturnInBranch", + ` declare function foo(): Promise; function [#|f|](): Promise { return foo().then(() => { @@ -1846,5 +2216,6 @@ function [#|f|](): Promise { return a + 1; }); } -`); +`, + ); }); diff --git a/src/testRunner/unittests/services/documentRegistry.ts b/src/testRunner/unittests/services/documentRegistry.ts index 6281f73125276..93d51c5b6d0e4 100644 --- a/src/testRunner/unittests/services/documentRegistry.ts +++ b/src/testRunner/unittests/services/documentRegistry.ts @@ -23,7 +23,6 @@ describe("unittests:: services:: DocumentRegistry", () => { assert(f1 === f2, "Expected to have the same document instance"); - // change value of compilation setting that is used during production of AST - new document is required compilerOptions.target = ts.ScriptTarget.ES3; const f3 = documentRegistry.acquireDocument("file1.ts", compilerOptions, ts.ScriptSnapshot.fromString("var x = 1;"), /* version */ "1"); diff --git a/src/testRunner/unittests/services/extract/constants.ts b/src/testRunner/unittests/services/extract/constants.ts index 24b44e689deb0..a479a311b1aea 100644 --- a/src/testRunner/unittests/services/extract/constants.ts +++ b/src/testRunner/unittests/services/extract/constants.ts @@ -5,59 +5,73 @@ import { } from "./helpers"; describe("unittests:: services:: extract:: extractConstants", () => { - testExtractConstant("extractConstant_TopLevel", - `let x = [#|1|];`); + testExtractConstant("extractConstant_TopLevel", `let x = [#|1|];`); - testExtractConstant("extractConstant_Namespace", + testExtractConstant( + "extractConstant_Namespace", `namespace N { let x = [#|1|]; -}`); +}`, + ); - testExtractConstant("extractConstant_Class", + testExtractConstant( + "extractConstant_Class", `class C { x = [#|1|]; -}`); +}`, + ); - testExtractConstant("extractConstant_Method", + testExtractConstant( + "extractConstant_Method", `class C { M() { let x = [#|1|]; } -}`); +}`, + ); - testExtractConstant("extractConstant_Function", + testExtractConstant( + "extractConstant_Function", `function F() { let x = [#|1|]; -}`); +}`, + ); - testExtractConstant("extractConstant_ExpressionStatement", - `[#|"hello";|]`); + testExtractConstant("extractConstant_ExpressionStatement", `[#|"hello";|]`); - testExtractConstant("extractConstant_ExpressionStatementExpression", - `[#|"hello"|];`); + testExtractConstant("extractConstant_ExpressionStatementExpression", `[#|"hello"|];`); - testExtractConstant("extractConstant_ExpressionStatementInNestedScope", ` + testExtractConstant( + "extractConstant_ExpressionStatementInNestedScope", + ` let i = 0; function F() { [#|i++|]; } - `); + `, + ); - testExtractConstant("extractConstant_ExpressionStatementConsumesLocal", ` + testExtractConstant( + "extractConstant_ExpressionStatementConsumesLocal", + ` function F() { let i = 0; [#|i++|]; } - `); + `, + ); - testExtractConstant("extractConstant_BlockScopes_NoDependencies", + testExtractConstant( + "extractConstant_BlockScopes_NoDependencies", `for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { let x = [#|1|]; } -}`); +}`, + ); - testExtractConstant("extractConstant_ClassInsertionPosition1", + testExtractConstant( + "extractConstant_ClassInsertionPosition1", `class C { a = 1; b = 2; @@ -66,9 +80,11 @@ function F() { M3() { let x = [#|1|]; } -}`); +}`, + ); - testExtractConstant("extractConstant_ClassInsertionPosition2", + testExtractConstant( + "extractConstant_ClassInsertionPosition2", `class C { a = 1; M1() { } @@ -77,9 +93,11 @@ function F() { M3() { let x = [#|1|]; } -}`); +}`, + ); - testExtractConstant("extractConstant_ClassInsertionPosition3", + testExtractConstant( + "extractConstant_ClassInsertionPosition3", `class C { M1() { } a = 1; @@ -88,91 +106,121 @@ function F() { M3() { let x = [#|1|]; } -}`); +}`, + ); - testExtractConstant("extractConstant_Parameters", + testExtractConstant( + "extractConstant_Parameters", `function F() { let w = 1; let x = [#|w + 1|]; -}`); +}`, + ); - testExtractConstant("extractConstant_TypeParameters", + testExtractConstant( + "extractConstant_TypeParameters", `function F(t: T) { let x = [#|t + 1|]; -}`); +}`, + ); - testExtractConstant("extractConstant_RepeatedSubstitution", + testExtractConstant( + "extractConstant_RepeatedSubstitution", `namespace X { export const j = 10; export const y = [#|j * j|]; -}`); +}`, + ); - testExtractConstant("extractConstant_VariableList_const", - `const a = 1, b = [#|a + 1|];`); + testExtractConstant("extractConstant_VariableList_const", `const a = 1, b = [#|a + 1|];`); // NOTE: this test isn't normative - it just documents our sub-optimal behavior. - testExtractConstant("extractConstant_VariableList_let", - `let a = 1, b = [#|a + 1|];`); + testExtractConstant("extractConstant_VariableList_let", `let a = 1, b = [#|a + 1|];`); // NOTE: this test isn't normative - it just documents our sub-optimal behavior. - testExtractConstant("extractConstant_VariableList_MultipleLines", + testExtractConstant( + "extractConstant_VariableList_MultipleLines", `const /*About A*/a = 1, - /*About B*/b = [#|a + 1|];`); + /*About B*/b = [#|a + 1|];`, + ); - testExtractConstant("extractConstant_BlockScopeMismatch", ` + testExtractConstant( + "extractConstant_BlockScopeMismatch", + ` for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { const x = [#|i + 1|]; } } - `); + `, + ); - testExtractConstant("extractConstant_StatementInsertionPosition1", ` + testExtractConstant( + "extractConstant_StatementInsertionPosition1", + ` const i = 0; for (let j = 0; j < 10; j++) { const x = [#|i + 1|]; } - `); + `, + ); - testExtractConstant("extractConstant_StatementInsertionPosition2", ` + testExtractConstant( + "extractConstant_StatementInsertionPosition2", + ` const i = 0; function F() { for (let j = 0; j < 10; j++) { const x = [#|i + 1|]; } } - `); + `, + ); - testExtractConstant("extractConstant_StatementInsertionPosition3", ` + testExtractConstant( + "extractConstant_StatementInsertionPosition3", + ` for (let j = 0; j < 10; j++) { const x = [#|2 + 1|]; } - `); + `, + ); - testExtractConstant("extractConstant_StatementInsertionPosition4", ` + testExtractConstant( + "extractConstant_StatementInsertionPosition4", + ` function F() { for (let j = 0; j < 10; j++) { const x = [#|2 + 1|]; } } - `); + `, + ); - testExtractConstant("extractConstant_StatementInsertionPosition5", ` + testExtractConstant( + "extractConstant_StatementInsertionPosition5", + ` function F0() { function F1() { function F2(x = [#|2 + 1|]) { } } } - `); + `, + ); - testExtractConstant("extractConstant_StatementInsertionPosition6", ` + testExtractConstant( + "extractConstant_StatementInsertionPosition6", + ` class C { x = [#|2 + 1|]; } - `); + `, + ); - testExtractConstant("extractConstant_StatementInsertionPosition7", ` + testExtractConstant( + "extractConstant_StatementInsertionPosition7", + ` const i = 0; class C { M() { @@ -181,27 +229,39 @@ class C { } } } - `); + `, + ); - testExtractConstant("extractConstant_TripleSlash", ` + testExtractConstant( + "extractConstant_TripleSlash", + ` /// const x = [#|2 + 1|]; - `); + `, + ); - testExtractConstant("extractConstant_PinnedComment", ` + testExtractConstant( + "extractConstant_PinnedComment", + ` /*! Copyright */ const x = [#|2 + 1|]; - `); + `, + ); - testExtractConstant("extractConstant_Directive", ` + testExtractConstant( + "extractConstant_Directive", + ` "strict"; const x = [#|2 + 1|]; - `); + `, + ); - testExtractConstant("extractConstant_MultipleHeaders", ` + testExtractConstant( + "extractConstant_MultipleHeaders", + ` /*! Copyright */ /// @@ -209,94 +269,126 @@ const x = [#|2 + 1|]; "strict"; const x = [#|2 + 1|]; - `); + `, + ); - testExtractConstant("extractConstant_PinnedCommentAndDocComment", ` + testExtractConstant( + "extractConstant_PinnedCommentAndDocComment", + ` /*! Copyright */ /* About x */ const x = [#|2 + 1|]; - `); + `, + ); - testExtractConstant("extractConstant_ArrowFunction_Block", ` + testExtractConstant( + "extractConstant_ArrowFunction_Block", + ` const f = () => { return [#|2 + 1|]; -};`); +};`, + ); - testExtractConstant("extractConstant_ArrowFunction_Expression", - `const f = () => [#|2 + 1|];`); + testExtractConstant("extractConstant_ArrowFunction_Expression", `const f = () => [#|2 + 1|];`); - testExtractConstant("extractConstant_PreserveTrivia", ` + testExtractConstant( + "extractConstant_PreserveTrivia", + ` // a var q = /*b*/ //c /*d*/ [#|1 /*e*/ //f /*g*/ + /*h*/ //i /*j*/ 2|] /*k*/ //l - /*m*/; /*n*/ //o`); + /*m*/; /*n*/ //o`, + ); - testExtractConstantFailed("extractConstant_Void", ` + testExtractConstantFailed( + "extractConstant_Void", + ` function f(): void { } -[#|f();|]`); +[#|f();|]`, + ); - testExtractConstantFailed("extractConstant_Never", ` + testExtractConstantFailed( + "extractConstant_Never", + ` function f(): never { } -[#|f();|]`); +[#|f();|]`, + ); - testExtractConstant("extractConstant_This_Constructor", ` + testExtractConstant( + "extractConstant_This_Constructor", + ` class C { constructor() { [#|this.m2()|]; } m2() { return 1; } -}`); +}`, + ); - testExtractConstant("extractConstant_This_Method", ` + testExtractConstant( + "extractConstant_This_Method", + ` class C { m1() { [#|this.m2()|]; } m2() { return 1; } -}`); +}`, + ); - testExtractConstant("extractConstant_This_Property", ` + testExtractConstant( + "extractConstant_This_Property", + ` namespace N { // Force this test to be TS-only class C { x = 1; y = [#|this.x|]; } -}`); +}`, + ); // TODO (https://github.com/Microsoft/TypeScript/issues/20727): the extracted constant should have a type annotation. - testExtractConstant("extractConstant_ContextualType", ` + testExtractConstant( + "extractConstant_ContextualType", + ` interface I { a: 1 | 2 | 3 } let i: I = [#|{ a: 1 }|]; -`); +`, + ); - testExtractConstant("extractConstant_ContextualType_Lambda", ` + testExtractConstant( + "extractConstant_ContextualType_Lambda", + ` const myObj: { member(x: number, y: string): void } = { member: [#|(x, y) => x + y|], } -`); +`, + ); - testExtractConstant("extractConstant_CaseClauseExpression", ` + testExtractConstant( + "extractConstant_CaseClauseExpression", + ` switch (1) { case [#|1|]: break; } -`); +`, + ); - testExtractConstant("extractConstant_PropertyName", - `[#|x.y|].z();`); + testExtractConstant("extractConstant_PropertyName", `[#|x.y|].z();`); - testExtractConstant("extractConstant_PropertyName_ExistingName", + testExtractConstant( + "extractConstant_PropertyName_ExistingName", `let y; -[#|x.y|].z();`); +[#|x.y|].z();`, + ); - testExtractConstant("extractConstant_PropertyName_Keyword", - `[#|x.if|].z();`); + testExtractConstant("extractConstant_PropertyName_Keyword", `[#|x.if|].z();`); - testExtractConstant("extractConstant_PropertyName_PrivateIdentifierKeyword", - `[#|this.#if|].z();`); + testExtractConstant("extractConstant_PropertyName_PrivateIdentifierKeyword", `[#|this.#if|].z();`); }); function testExtractConstant(caption: string, text: string) { diff --git a/src/testRunner/unittests/services/extract/functions.ts b/src/testRunner/unittests/services/extract/functions.ts index 0405a55c1f320..359b2d98241d8 100644 --- a/src/testRunner/unittests/services/extract/functions.ts +++ b/src/testRunner/unittests/services/extract/functions.ts @@ -1,8 +1,11 @@ import * as ts from "../../../_namespaces/ts"; -import { testExtractSymbol } from "./helpers"; +import { + testExtractSymbol, +} from "./helpers"; describe("unittests:: services:: extract:: extractFunctions", () => { - testExtractFunction("extractFunction1", + testExtractFunction( + "extractFunction1", `namespace A { let x = 1; function foo() { @@ -17,8 +20,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { foo();|] } } -}`); - testExtractFunction("extractFunction2", +}`, + ); + testExtractFunction( + "extractFunction2", `namespace A { let x = 1; function foo() { @@ -31,8 +36,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return foo();|] } } -}`); - testExtractFunction("extractFunction3", +}`, + ); + testExtractFunction( + "extractFunction3", `namespace A { function foo() { } @@ -44,8 +51,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return foo();|] } } -}`); - testExtractFunction("extractFunction4", +}`, + ); + testExtractFunction( + "extractFunction4", `namespace A { function foo() { } @@ -59,8 +68,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return foo();|] } } -}`); - testExtractFunction("extractFunction5", +}`, + ); + testExtractFunction( + "extractFunction5", `namespace A { let x = 1; export function foo() { @@ -75,8 +86,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { foo();|] } } -}`); - testExtractFunction("extractFunction6", +}`, + ); + testExtractFunction( + "extractFunction6", `namespace A { let x = 1; export function foo() { @@ -91,8 +104,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return foo();|] } } -}`); - testExtractFunction("extractFunction7", +}`, + ); + testExtractFunction( + "extractFunction7", `namespace A { let x = 1; export namespace C { @@ -109,8 +124,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return C.foo();|] } } -}`); - testExtractFunction("extractFunction9", +}`, + ); + testExtractFunction( + "extractFunction9", `namespace A { export interface I { x: number }; namespace B { @@ -119,8 +136,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return a1.x + 10;|] } } -}`); - testExtractFunction("extractFunction10", +}`, + ); + testExtractFunction( + "extractFunction10", `namespace A { export interface I { x: number }; class C { @@ -130,8 +149,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return a1.x + 10;|] } } -}`); - testExtractFunction("extractFunction11", +}`, + ); + testExtractFunction( + "extractFunction11", `namespace A { let y = 1; class C { @@ -143,8 +164,10 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return a1.x + 10;|] } } -}`); - testExtractFunction("extractFunction12", +}`, + ); + testExtractFunction( + "extractFunction12", `namespace A { let y = 1; class C { @@ -158,13 +181,15 @@ describe("unittests:: services:: extract:: extractFunctions", () => { return a1.x + 10;|] } } -}`); +}`, + ); // The "b" type parameters aren't used and shouldn't be passed to the extracted function. // Type parameters should be in syntactic order (i.e. in order or character offset from BOF). // In all cases, we could use type inference, rather than passing explicit type arguments. // Note the inclusion of arrow functions to ensure that some type parameters are not from // targetable scopes. - testExtractFunction("extractFunction13", + testExtractFunction( + "extractFunction13", `(u1a: U1a, u1b: U1b) => { function F1(t1a: T1a, t1b: T1b) { (u2a: U2a, u2b: U2b) => { @@ -179,107 +204,138 @@ describe("unittests:: services:: extract:: extractFunctions", () => { } } } -}`); +}`, + ); // This test is descriptive, rather than normative. The current implementation // doesn't handle type parameter shadowing. - testExtractFunction("extractFunction14", + testExtractFunction( + "extractFunction14", `function F(t1: T) { function G(t2: T) { [#|t1.toString(); t2.toString();|] } -}`); +}`, + ); // Confirm that the constraint is preserved. - testExtractFunction("extractFunction15", + testExtractFunction( + "extractFunction15", `function F(t1: T) { function G(t2: U) { [#|t2.toString();|] } -}`, /*includeLib*/ true); +}`, + /*includeLib*/ true, + ); // Confirm that the contextual type of an extracted expression counts as a use. - testExtractFunction("extractFunction16", + testExtractFunction( + "extractFunction16", `function F() { const array: T[] = [#|[]|]; -}`, /*includeLib*/ true); +}`, + /*includeLib*/ true, + ); // Class type parameter - testExtractFunction("extractFunction17", + testExtractFunction( + "extractFunction17", `class C { M(t1: T1, t2: T2) { [#|t1.toString()|]; } -}`); +}`, + ); // Function type parameter - testExtractFunction("extractFunction18", + testExtractFunction( + "extractFunction18", `class C { M(t1: T1, t2: T2) { [#|t1.toString()|]; } -}`); +}`, + ); // Coupled constraints - testExtractFunction("extractFunction19", + testExtractFunction( + "extractFunction19", `function F(v: V) { [#|v.toString()|]; -}`, /*includeLib*/ true); +}`, + /*includeLib*/ true, + ); - testExtractFunction("extractFunction20", + testExtractFunction( + "extractFunction20", `const _ = class { a() { [#|let a1 = { x: 1 }; return a1.x + 10;|] } -}`); +}`, + ); // Write + void return - testExtractFunction("extractFunction21", + testExtractFunction( + "extractFunction21", `function foo() { let x = 10; [#|x++; return;|] -}`); +}`, + ); // Return in finally block - testExtractFunction("extractFunction22", + testExtractFunction( + "extractFunction22", `function test() { try { } finally { [#|return 1;|] } -}`); +}`, + ); // Extraction position - namespace - testExtractFunction("extractFunction23", + testExtractFunction( + "extractFunction23", `namespace NS { function M1() { } function M2() { [#|return 1;|] } function M3() { } -}`); +}`, + ); // Extraction position - function - testExtractFunction("extractFunction24", + testExtractFunction( + "extractFunction24", `function Outer() { function M1() { } function M2() { [#|return 1;|] } function M3() { } -}`); +}`, + ); // Extraction position - file - testExtractFunction("extractFunction25", + testExtractFunction( + "extractFunction25", `function M1() { } function M2() { [#|return 1;|] } -function M3() { }`); +function M3() { }`, + ); // Extraction position - class without ctor - testExtractFunction("extractFunction26", + testExtractFunction( + "extractFunction26", `class C { M1() { } M2() { [#|return 1;|] } M3() { } -}`); +}`, + ); // Extraction position - class with ctor in middle - testExtractFunction("extractFunction27", + testExtractFunction( + "extractFunction27", `class C { M1() { } M2() { @@ -287,9 +343,11 @@ function M3() { }`); } constructor() { } M3() { } -}`); +}`, + ); // Extraction position - class with ctor at end - testExtractFunction("extractFunction28", + testExtractFunction( + "extractFunction28", `class C { M1() { } M2() { @@ -297,9 +355,11 @@ function M3() { }`); } M3() { } constructor() { } -}`); +}`, + ); // Shorthand property names - testExtractFunction("extractFunction29", + testExtractFunction( + "extractFunction29", `interface UnaryExpression { kind: "Unary"; operator: string; @@ -316,14 +376,18 @@ function parseUnaryExpression(operator: string): UnaryExpression { function parsePrimaryExpression(): any { throw "Not implemented"; -}`); +}`, + ); // Type parameter as declared type - testExtractFunction("extractFunction30", + testExtractFunction( + "extractFunction30", `function F() { [#|let t: T;|] -}`); +}`, + ); // Return in nested function - testExtractFunction("extractFunction31", + testExtractFunction( + "extractFunction31", `namespace N { export const value = 1; @@ -334,9 +398,11 @@ function parsePrimaryExpression(): any { return value; }|] } -}`); +}`, + ); // Return in nested class - testExtractFunction("extractFunction32", + testExtractFunction( + "extractFunction32", `namespace N { export const value = 1; @@ -348,187 +414,262 @@ function parsePrimaryExpression(): any { } }|] } -}`); +}`, + ); // Selection excludes leading trivia of declaration - testExtractFunction("extractFunction33", + testExtractFunction( + "extractFunction33", `function F() { [#|function G() { }|] -}`); +}`, + ); // Arrow function - testExtractFunction("extractFunction34", + testExtractFunction( + "extractFunction34", `const F = () => { [#|function G() { }|] -};`); +};`, + ); - testExtractFunction("extractFunction_RepeatedSubstitution", + testExtractFunction( + "extractFunction_RepeatedSubstitution", `namespace X { export const j = 10; export const y = [#|j * j|]; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Var", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Var", + ` [#|var x = 1; "hello"|] x; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Let_Type", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Let_Type", + ` [#|let x: number = 1; "hello";|] x; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Let_NoType", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Let_NoType", + ` [#|let x = 1; "hello";|] x; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Const_Type", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Const_Type", + ` [#|const x: number = 1; "hello";|] x; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Const_NoType", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Const_NoType", + ` [#|const x = 1; "hello";|] x; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Multiple1", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Multiple1", + ` [#|const x = 1, y: string = "a";|] x; y; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Multiple2", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Multiple2", + ` [#|const x = 1, y = "a"; const z = 3;|] x; y; z; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Multiple3", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Multiple3", + ` [#|const x = 1, y: string = "a"; let z = 3;|] x; y; z; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_ConsumedTwice", ` + testExtractFunction( + "extractFunction_VariableDeclaration_ConsumedTwice", + ` [#|const x: number = 1; "hello";|] x; x; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_DeclaredTwice", ` + testExtractFunction( + "extractFunction_VariableDeclaration_DeclaredTwice", + ` [#|var x = 1; var x = 2;|] x; -`); +`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Var", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Var", + ` function f() { let a = 1; [#|var x = 1; a++;|] a; x; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_NoType", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Let_NoType", + ` function f() { let a = 1; [#|let x = 1; a++;|] a; x; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_Type", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Let_Type", + ` function f() { let a = 1; [#|let x: number = 1; a++;|] a; x; -}`); +}`, + ); // We propagate numericLiteralFlags, but it's not consumed by the emitter, // so everything comes out decimal. It would be nice to improve this. - testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType1", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Let_LiteralType1", + ` function f() { let a = 1; [#|let x: 0o10 | 10 | 0b10 = 10; a++;|] a; x; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType2", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Let_LiteralType2", + ` function f() { let a = 1; [#|let x: "a" | 'b' = 'a'; a++;|] a; x; -}`); +}`, + ); // We propagate numericLiteralFlags, but it's not consumed by the emitter, // so everything comes out decimal. It would be nice to improve this. - testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType1", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Let_LiteralType1", + ` function f() { let a = 1; [#|let x: 0o10 | 10 | 0b10 = 10; a++;|] a; x; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_TypeWithComments", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Let_TypeWithComments", + ` function f() { let a = 1; [#|let x: /*A*/ "a" /*B*/ | /*C*/ 'b' /*D*/ = 'a'; a++;|] a; x; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Const_NoType", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Const_NoType", + ` function f() { let a = 1; [#|const x = 1; a++;|] a; x; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Const_Type", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Const_Type", + ` function f() { let a = 1; [#|const x: number = 1; a++;|] a; x; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed1", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Mixed1", + ` function f() { let a = 1; [#|const x = 1; let y = 2; a++;|] a; x; y; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed2", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Mixed2", + ` function f() { let a = 1; [#|var x = 1; let y = 2; a++;|] a; x; y; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed3", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_Mixed3", + ` function f() { let a = 1; [#|let x: number = 1; let y = 2; a++;|] a; x; y; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_Writes_UnionUndefined", ` + testExtractFunction( + "extractFunction_VariableDeclaration_Writes_UnionUndefined", + ` function f() { let a = 1; [#|let x: number | undefined = 1; @@ -536,33 +677,46 @@ function f() { let z: (undefined | number) = 3; a++;|] a; x; y; z; -}`); +}`, + ); - testExtractFunction("extractFunction_VariableDeclaration_ShorthandProperty", ` + testExtractFunction( + "extractFunction_VariableDeclaration_ShorthandProperty", + ` function f() { [#|let x;|] return { x }; -}`); +}`, + ); - testExtractFunction("extractFunction_PreserveTrivia", ` + testExtractFunction( + "extractFunction_PreserveTrivia", + ` // a var q = /*b*/ //c /*d*/ [#|1 /*e*/ //f /*g*/ + /*h*/ //i /*j*/ 2|] /*k*/ //l - /*m*/; /*n*/ //o`); + /*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 -}`); +}`, + ); }); function testExtractFunction(caption: string, text: string, includeLib?: boolean) { diff --git a/src/testRunner/unittests/services/extract/helpers.ts b/src/testRunner/unittests/services/extract/helpers.ts index cc139c3f42a2c..65995d34c5537 100644 --- a/src/testRunner/unittests/services/extract/helpers.ts +++ b/src/testRunner/unittests/services/extract/helpers.ts @@ -1,6 +1,8 @@ import * as Harness from "../../../_namespaces/Harness"; import * as ts from "../../../_namespaces/ts"; -import { createProjectService } from "../../helpers/tsserver"; +import { + createProjectService, +} from "../../helpers/tsserver"; import { createServerHost, libFile, @@ -25,8 +27,10 @@ export function extractTest(source: string): Test { const ranges = new Map(); while (pos < source.length) { - if (source.charCodeAt(pos) === ts.CharacterCodes.openBracket && - (source.charCodeAt(pos + 1) === ts.CharacterCodes.hash || source.charCodeAt(pos + 1) === ts.CharacterCodes.$)) { + if ( + source.charCodeAt(pos) === ts.CharacterCodes.openBracket && + (source.charCodeAt(pos + 1) === ts.CharacterCodes.hash || source.charCodeAt(pos + 1) === ts.CharacterCodes.$) + ) { const saved = pos; pos += 2; const s = pos; @@ -80,7 +84,7 @@ export const notImplementedHost: ts.LanguageServiceHost = { getDefaultLibFileName: ts.notImplemented, getCurrentDirectory: ts.notImplemented, readFile: ts.notImplemented, - fileExists: ts.notImplemented + fileExists: ts.notImplemented, }; export function testExtractSymbol(caption: string, text: string, baselineFolder: string, description: ts.DiagnosticMessage, includeLib?: boolean) { @@ -90,8 +94,7 @@ export function testExtractSymbol(caption: string, text: string, baselineFolder: throw new Error(`Test ${caption} does not specify selection range`); } - [ts.Extension.Ts, ts.Extension.Js].forEach(extension => - it(`${caption} [${extension}]`, () => runBaseline(extension))); + [ts.Extension.Ts, ts.Extension.Js].forEach(extension => it(`${caption} [${extension}]`, () => runBaseline(extension))); function runBaseline(extension: ts.Extension) { const path = "/a" + extension; @@ -136,7 +139,7 @@ export function testExtractSymbol(caption: string, text: string, baselineFolder: Harness.Baseline.runBaseline(`${baselineFolder}/${caption}${extension}`, data.join(newLineCharacter)); } - function makeProgram(f: {path: string, content: string }, includeLib?: boolean) { + function makeProgram(f: { path: string; content: string; }, includeLib?: boolean) { const host = createServerHost(includeLib ? [f, libFile] : [f]); // libFile is expensive to parse repeatedly - only test when required const projectService = createProjectService(host, { allowNonBaseliningLogger: true }); projectService.openClientFile(f.path); @@ -160,7 +163,7 @@ export function testExtractSymbolFailed(caption: string, text: string, descripti } const f = { path: "/a.ts", - content: t.source + content: t.source, }; const host = createServerHost([f, libFile]); const projectService = createProjectService(host, { allowNonBaseliningLogger: true }); diff --git a/src/testRunner/unittests/services/extract/ranges.ts b/src/testRunner/unittests/services/extract/ranges.ts index 60d4cce5b8694..ce0312d3f1288 100644 --- a/src/testRunner/unittests/services/extract/ranges.ts +++ b/src/testRunner/unittests/services/extract/ranges.ts @@ -1,5 +1,7 @@ import * as ts from "../../../_namespaces/ts"; -import { extractTest } from "./helpers"; +import { + extractTest, +} from "./helpers"; function testExtractRangeFailed(caption: string, s: string, expectedErrors: string[]) { return it(caption, () => { @@ -48,68 +50,109 @@ function testExtractRange(caption: string, s: string) { describe("unittests:: services:: extract:: extractRanges", () => { describe("get extract range from selection", () => { - testExtractRange("extractRange1", ` + testExtractRange( + "extractRange1", + ` [#| [$|var x = 1; var y = 2;|]|] - `); - testExtractRange("extractRange2", ` + `, + ); + testExtractRange( + "extractRange2", + ` [$|[#|var x = 1; var y = 2|];|] - `); - testExtractRange("extractRange3", ` + `, + ); + testExtractRange( + "extractRange3", + ` [#|var x = [$|1|]|]; var y = 2; - `); - testExtractRange("extractRange4", ` + `, + ); + testExtractRange( + "extractRange4", + ` var x = [$|10[#|00|]|]; - `); - testExtractRange("extractRange5", ` + `, + ); + testExtractRange( + "extractRange5", + ` [$|va[#|r foo = 1; var y = 200|]0;|] - `); - testExtractRange("extractRange6", ` + `, + ); + testExtractRange( + "extractRange6", + ` var x = [$|fo[#|o.bar.baz()|]|]; - `); - testExtractRange("extractRange7", ` + `, + ); + testExtractRange( + "extractRange7", + ` if ([#|[#extracted|a && b && c && d|]|]) { } - `); - testExtractRange("extractRange8", ` + `, + ); + testExtractRange( + "extractRange8", + ` if [#|(a && b && c && d|]) { } - `); - testExtractRange("extractRange9", ` + `, + ); + testExtractRange( + "extractRange9", + ` if ([$|a[#|a && b && c && d|]d|]) { } - `); - testExtractRange("extractRange10", ` + `, + ); + testExtractRange( + "extractRange10", + ` if (a && b && c && d) { [#| [$|var x = 1; console.log(x);|] |] } - `); - testExtractRange("extractRange11", ` + `, + ); + testExtractRange( + "extractRange11", + ` [#| if (a) { return 100; } |] - `); - testExtractRange("extractRange12", ` + `, + ); + testExtractRange( + "extractRange12", + ` function foo() { [#| [$|if (a) { } return 100|] |] } - `); - testExtractRange("extractRange13", ` + `, + ); + testExtractRange( + "extractRange13", + ` [#| [$|l1: if (x) { break l1; }|]|] - `); - testExtractRange("extractRange14", ` + `, + ); + testExtractRange( + "extractRange14", + ` [#| [$|l2: { @@ -117,22 +160,31 @@ describe("unittests:: services:: extract:: extractRanges", () => { } break l2; }|]|] - `); - testExtractRange("extractRange15", ` + `, + ); + testExtractRange( + "extractRange15", + ` while (true) { [#| if(x) { } break; |] } - `); - testExtractRange("extractRange16", ` + `, + ); + testExtractRange( + "extractRange16", + ` while (true) { [#| if(x) { } continue; |] } - `); - testExtractRange("extractRange17", ` + `, + ); + testExtractRange( + "extractRange17", + ` l3: { [#| @@ -140,8 +192,11 @@ describe("unittests:: services:: extract:: extractRanges", () => { } break l3; |] } - `); - testExtractRange("extractRange18", ` + `, + ); + testExtractRange( + "extractRange18", + ` function f() { while (true) { [#| @@ -150,8 +205,11 @@ describe("unittests:: services:: extract:: extractRanges", () => { } |] } } - `); - testExtractRange("extractRange19", ` + `, + ); + testExtractRange( + "extractRange19", + ` function f() { while (true) { [#| @@ -161,14 +219,20 @@ describe("unittests:: services:: extract:: extractRanges", () => { |] } } - `); - testExtractRange("extractRange20", ` + `, + ); + testExtractRange( + "extractRange20", + ` function f() { return [#| [$|1 + 2|] |]+ 3; } } - `); - testExtractRange("extractRange21", ` + `, + ); + testExtractRange( + "extractRange21", + ` function f(x: number) { [#|[$|try { x++; @@ -177,7 +241,8 @@ describe("unittests:: services:: extract:: extractRanges", () => { return 1; }|]|] } - `); + `, + ); // Variable statements testExtractRange("extractRange22", `[#|let x = [$|1|];|]`); @@ -197,7 +262,8 @@ describe("unittests:: services:: extract:: extractRanges", () => { testExtractRange("extractRange30", `for (var i = [#|[$|1|]|]; i < 2; i++) {}`); }); - testExtractRangeFailed("extractRangeFailed1", + testExtractRangeFailed( + "extractRangeFailed1", ` namespace A { function f() { @@ -210,9 +276,11 @@ function f() { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message], + ); - testExtractRangeFailed("extractRangeFailed2", + testExtractRangeFailed( + "extractRangeFailed2", ` namespace A { function f() { @@ -227,9 +295,11 @@ function f() { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message], + ); - testExtractRangeFailed("extractRangeFailed3", + testExtractRangeFailed( + "extractRangeFailed3", ` namespace A { function f() { @@ -244,9 +314,11 @@ function f() { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message], + ); - testExtractRangeFailed("extractRangeFailed4", + testExtractRangeFailed( + "extractRangeFailed4", ` namespace A { function f() { @@ -261,9 +333,11 @@ function f() { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange.message], + ); - testExtractRangeFailed("extractRangeFailed5", + testExtractRangeFailed( + "extractRangeFailed5", ` namespace A { function f() { @@ -280,9 +354,11 @@ function f2() { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message], + ); - testExtractRangeFailed("extractRangeFailed6", + testExtractRangeFailed( + "extractRangeFailed6", ` namespace A { function f() { @@ -299,9 +375,11 @@ function f2() { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message], + ); - testExtractRangeFailed("extractRangeFailed7", + testExtractRangeFailed( + "extractRangeFailed7", ` function test(x: number) { while (x) { @@ -310,9 +388,11 @@ while (x) { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message], + ); - testExtractRangeFailed("extractRangeFailed8", + testExtractRangeFailed( + "extractRangeFailed8", ` function test(x: number) { switch (x) { @@ -321,22 +401,24 @@ switch (x) { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message], + ); - testExtractRangeFailed("extractRangeFailed9", - `var x = ([#||]1 + 2);`, - [ts.refactor.extractSymbol.Messages.cannotExtractEmpty.message]); + testExtractRangeFailed("extractRangeFailed9", `var x = ([#||]1 + 2);`, [ts.refactor.extractSymbol.Messages.cannotExtractEmpty.message]); - testExtractRangeFailed("extractRangeFailed10", + testExtractRangeFailed( + "extractRangeFailed10", ` function f() { return 1 + [#|2 + 3|]; } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRange.message], + ); - testExtractRangeFailed("extractRangeFailed11", + testExtractRangeFailed( + "extractRangeFailed11", ` function f(x: number) { while (true) { @@ -349,61 +431,62 @@ switch (x) { } } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message], + ); - testExtractRangeFailed("extractRangeFailed12", - `let [#|x|];`, - [ts.refactor.extractSymbol.Messages.statementOrExpressionExpected.message]); + testExtractRangeFailed("extractRangeFailed12", `let [#|x|];`, [ts.refactor.extractSymbol.Messages.statementOrExpressionExpected.message]); - testExtractRangeFailed("extractRangeFailed13", - `[#|return;|]`, - [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); + testExtractRangeFailed("extractRangeFailed13", `[#|return;|]`, [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); - testExtractRangeFailed("extractRangeFailed14", + testExtractRangeFailed( + "extractRangeFailed14", ` switch(1) { case [#|1: break;|] } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRange.message], + ); - testExtractRangeFailed("extractRangeFailed15", + testExtractRangeFailed( + "extractRangeFailed15", ` switch(1) { case [#|1: break|]; } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRange.message], + ); // Documentation only - it would be nice if the result were [$|1|] - testExtractRangeFailed("extractRangeFailed16", + testExtractRangeFailed( + "extractRangeFailed16", ` switch(1) { [#|case 1|]: break; } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRange.message], + ); // Documentation only - it would be nice if the result were [$|1|] - testExtractRangeFailed("extractRangeFailed17", + testExtractRangeFailed( + "extractRangeFailed17", ` switch(1) { [#|case 1:|] break; } `, - [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); + [ts.refactor.extractSymbol.Messages.cannotExtractRange.message], + ); - testExtractRangeFailed("extractRangeFailed18", - `[#|{ 1;|] }`, - [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); + testExtractRangeFailed("extractRangeFailed18", `[#|{ 1;|] }`, [ts.refactor.extractSymbol.Messages.cannotExtractRange.message]); - testExtractRangeFailed("extractRangeFailed19", - `[#|/** @type {number} */|] const foo = 1;`, - [ts.refactor.extractSymbol.Messages.cannotExtractJSDoc.message]); + testExtractRangeFailed("extractRangeFailed19", `[#|/** @type {number} */|] const foo = 1;`, [ts.refactor.extractSymbol.Messages.cannotExtractJSDoc.message]); testExtractRangeFailed("extract-method-not-for-token-expression-statement", `[#|a|]`, [ts.refactor.extractSymbol.Messages.cannotExtractIdentifier.message]); }); diff --git a/src/testRunner/unittests/services/extract/symbolWalker.ts b/src/testRunner/unittests/services/extract/symbolWalker.ts index 0c2285ceda6bc..48a2121a4f565 100644 --- a/src/testRunner/unittests/services/extract/symbolWalker.ts +++ b/src/testRunner/unittests/services/extract/symbolWalker.ts @@ -4,43 +4,53 @@ import * as ts from "../../../_namespaces/ts"; describe("unittests:: services:: extract:: Symbol Walker", () => { function test(description: string, source: string, verifier: (file: ts.SourceFile, checker: ts.TypeChecker) => void) { it(description, () => { - const result = Harness.Compiler.compileFiles([{ - unitName: "main.ts", - content: source - }], [], {}, {}, "/"); + const result = Harness.Compiler.compileFiles( + [{ + unitName: "main.ts", + content: source, + }], + [], + {}, + {}, + "/", + ); const file = result.program!.getSourceFile("main.ts")!; const checker = result.program!.getTypeChecker(); verifier(file, checker); }); } - test("can be created", ` + test( + "can be created", + ` interface Bar { x: number; y: number; history: Bar[]; } -export default function foo(a: number, b: Bar): void {}`, (file, checker) => { - let foundCount = 0; - let stdLibRefSymbols = 0; - const expectedSymbols = ["default", "a", "b", "Bar", "x", "y", "history"]; - const walker = checker.getSymbolWalker(symbol => { - const isStdLibSymbol = ts.forEach(symbol.declarations, d => { - return ts.getSourceFileOfNode(d).hasNoDefaultLib; +export default function foo(a: number, b: Bar): void {}`, + (file, checker) => { + let foundCount = 0; + let stdLibRefSymbols = 0; + const expectedSymbols = ["default", "a", "b", "Bar", "x", "y", "history"]; + const walker = checker.getSymbolWalker(symbol => { + const isStdLibSymbol = ts.forEach(symbol.declarations, d => { + return ts.getSourceFileOfNode(d).hasNoDefaultLib; + }); + if (isStdLibSymbol) { + stdLibRefSymbols++; + return false; // Don't traverse into the stdlib. That's unnecessary for this test. + } + assert.equal(symbol.name, expectedSymbols[foundCount]); + foundCount++; + return true; }); - if (isStdLibSymbol) { - stdLibRefSymbols++; - return false; // Don't traverse into the stdlib. That's unnecessary for this test. + const symbols = checker.getExportsOfModule(file.symbol); + for (const symbol of symbols) { + walker.walkSymbol(symbol); } - assert.equal(symbol.name, expectedSymbols[foundCount]); - foundCount++; - return true; - }); - const symbols = checker.getExportsOfModule(file.symbol); - for (const symbol of symbols) { - walker.walkSymbol(symbol); - } - assert.equal(foundCount, expectedSymbols.length); - assert.equal(stdLibRefSymbols, 1); // Expect 1 stdlib entry symbol - the implicit Array referenced by Bar.history - }); + assert.equal(foundCount, expectedSymbols.length); + assert.equal(stdLibRefSymbols, 1); // Expect 1 stdlib entry symbol - the implicit Array referenced by Bar.history + }, + ); }); diff --git a/src/testRunner/unittests/services/hostNewLineSupport.ts b/src/testRunner/unittests/services/hostNewLineSupport.ts index d5028708f6dfa..a509a29e16f48 100644 --- a/src/testRunner/unittests/services/hostNewLineSupport.ts +++ b/src/testRunner/unittests/services/hostNewLineSupport.ts @@ -31,7 +31,7 @@ describe("unittests:: services:: hostNewLineSupport", () => { const ls = testLSWithFiles(options, [{ content, fileOptions: {}, - unitName: "input.ts" + unitName: "input.ts", }]); const result = ls.getEmitOutput("input.ts"); assert(!result.emitSkipped, "emit was skipped"); @@ -50,7 +50,7 @@ describe("unittests:: services:: hostNewLineSupport", () => { const ls = testLSWithFiles(options, [{ content, fileOptions: {}, - unitName: "input.ts" + unitName: "input.ts", }]); const span = ls.getOutliningSpans("input.ts")[0]; const textAfterSpanCollapse = content.substring(span.textSpan.start + span.textSpan.length); @@ -67,12 +67,10 @@ describe("unittests:: services:: hostNewLineSupport", () => { }); it("should respect CRLF line endings around outlining spans", () => { - verifyOutliningSpanNewLines("// comment not included\r\n// #region name\r\nlet x: string = \"x\";\r\n// #endregion name\r\n", - { newLine: ts.NewLineKind.CarriageReturnLineFeed }); + verifyOutliningSpanNewLines('// comment not included\r\n// #region name\r\nlet x: string = "x";\r\n// #endregion name\r\n', { newLine: ts.NewLineKind.CarriageReturnLineFeed }); }); it("should respect LF line endings around outlining spans", () => { - verifyOutliningSpanNewLines("// comment not included\n// #region name\nlet x: string = \"x\";\n// #endregion name\n\n", - { newLine: ts.NewLineKind.LineFeed }); + verifyOutliningSpanNewLines('// comment not included\n// #region name\nlet x: string = "x";\n// #endregion name\n\n', { newLine: ts.NewLineKind.LineFeed }); }); }); diff --git a/src/testRunner/unittests/services/languageService.ts b/src/testRunner/unittests/services/languageService.ts index f34256c4fccbe..128eec74a2a09 100644 --- a/src/testRunner/unittests/services/languageService.ts +++ b/src/testRunner/unittests/services/languageService.ts @@ -1,4 +1,6 @@ -import { expect } from "chai"; +import { + expect, +} from "chai"; import * as ts from "../../_namespaces/ts"; import { @@ -8,7 +10,7 @@ import { } from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: services:: languageService", () => { - const files: {[index: string]: string} = { + const files: { [index: string]: string; } = { "foo.ts": `import Vue from "./vue"; import Component from "./vue-class-component"; import { vueTemplateHtml } from "./variables"; @@ -21,7 +23,7 @@ class Carousel extends Vue { "variables.ts": `export const vueTemplateHtml = \`
\`;`, "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;` +export function Component(x: Config): any;`, }; function createLanguageService() { @@ -46,7 +48,7 @@ export function Component(x: Config): any;` return ts.getDefaultLibFilePath(options); }, fileExists: name => !!files[name], - readFile: name => files[name] + readFile: name => files[name], }); } // Regression test for GH #18245 - bug in single line comment writer caused a debug assertion when attempting @@ -62,20 +64,20 @@ export function Component(x: Config): any;` assert.deepEqual( languageService.getEmitOutput( "foo.ts", - /*emitOnlyDtsFiles*/ true + /*emitOnlyDtsFiles*/ true, ), { emitSkipped: true, diagnostics: ts.emptyArray, outputFiles: ts.emptyArray, - } + }, ); assert.deepEqual( languageService.getEmitOutput( "foo.ts", /*emitOnlyDtsFiles*/ true, - /*forceDtsEmit*/ true + /*forceDtsEmit*/ true, ), { emitSkipped: false, @@ -83,16 +85,16 @@ export function Component(x: Config): any;` outputFiles: [{ name: "foo.d.ts", text: "export {};\n", - writeByteOrderMark: false + writeByteOrderMark: false, }], - } + }, ); }); describe("detects program upto date correctly", () => { function verifyProgramUptoDate(useProjectVersion: boolean) { let projectVersion = "1"; - const files = new Map(); + const files = new Map(); files.set("/project/root.ts", { version: "1", text: `import { foo } from "./other"` }); files.set("/project/other.ts", { version: "1", text: `export function foo() { }` }); files.set("/lib/lib.d.ts", { version: "1", text: libFile.content }); @@ -109,7 +111,7 @@ export function Component(x: Config): any;` return text ? ts.ScriptSnapshot.fromString(text) : undefined; }, getCurrentDirectory: () => "/project", - getDefaultLibFileName: () => "/lib/lib.d.ts" + getDefaultLibFileName: () => "/lib/lib.d.ts", }; const ls = ts.createLanguageService(host); const program1 = ls.getProgram()!; @@ -134,7 +136,7 @@ export function Component(x: Config): any;` function verifyProgramFiles(program: ts.Program) { assert.deepEqual( program.getSourceFiles().map(f => f.fileName), - ["/lib/lib.d.ts", "/project/other.ts", "/project/root.ts"] + ["/lib/lib.d.ts", "/project/other.ts", "/project/root.ts"], ); } } @@ -153,34 +155,34 @@ export function Component(x: Config): any;` content: JSON.stringify({ compilerOptions: { module: "none", - composite: true + composite: true, }, - exclude: ["temp"] - }) + exclude: ["temp"], + }), }; const class1: File = { path: `/user/username/projects/myproject/projects/project1/class1.ts`, - content: `class class1 {}` + content: `class class1 {}`, }; const class1Dts: File = { path: `/user/username/projects/myproject/projects/project1/class1.d.ts`, - content: `declare class class1 {}` + content: `declare class class1 {}`, }; const config2: File = { path: `/user/username/projects/myproject/projects/project2/tsconfig.json`, content: JSON.stringify({ compilerOptions: { module: "none", - composite: true + composite: true, }, references: [ - { path: "../project1" } - ] - }) + { path: "../project1" }, + ], + }), }; const class2: File = { path: `/user/username/projects/myproject/projects/project2/class2.ts`, - content: `class class2 {}` + content: `class class2 {}`, }; const system = createServerHost([config1, class1, class1Dts, config2, class2, libFile]); const result = ts.getParsedCommandLineOfConfigFile(`/user/username/projects/myproject/projects/project2/tsconfig.json`, /*optionsToExtend*/ undefined, { @@ -218,7 +220,7 @@ export function Component(x: Config): any;` const { ls, system, class1, class2 } = setup(ts.returnTrue); assert.deepEqual( ls.getProgram()!.getSourceFiles().map(f => f.fileName), - [libFile.path, class1.path, class2.path] + [libFile.path, class1.path, class2.path], ); // Add new file to referenced project const class3 = `/user/username/projects/myproject/projects/project1/class3.ts`; @@ -226,7 +228,7 @@ export function Component(x: Config): any;` const program = ls.getProgram()!; assert.deepEqual( program.getSourceFiles().map(f => f.fileName), - [libFile.path, class1.path, class3, class2.path] + [libFile.path, class1.path, class3, class2.path], ); // Add excluded file to referenced project system.ensureFileOrFolder({ path: `/user/username/projects/myproject/projects/project1/temp/file.d.ts`, content: `declare class file {}` }); @@ -241,7 +243,7 @@ export function Component(x: Config): any;` const program1 = ls.getProgram()!; assert.deepEqual( program1.getSourceFiles().map(f => f.fileName), - [libFile.path, class1Dts.path, class2.path] + [libFile.path, class1Dts.path, class2.path], ); // Add new file to referenced project const class3 = `/user/username/projects/myproject/projects/project1/class3.ts`; @@ -249,7 +251,7 @@ export function Component(x: Config): any;` assert.notStrictEqual(ls.getProgram(), program1); assert.deepEqual( ls.getProgram()!.getSourceFiles().map(f => f.fileName), - [libFile.path, class1Dts.path, class2.path] + [libFile.path, class1Dts.path, class2.path], ); // Add class3 output const class3Dts = `/user/username/projects/myproject/projects/project1/class3.d.ts`; @@ -257,7 +259,7 @@ export function Component(x: Config): any;` const program2 = ls.getProgram()!; assert.deepEqual( program2.getSourceFiles().map(f => f.fileName), - [libFile.path, class1Dts.path, class3Dts, class2.path] + [libFile.path, class1Dts.path, class3Dts, class2.path], ); // Add excluded file to referenced project system.ensureFileOrFolder({ path: `/user/username/projects/myproject/projects/project1/temp/file.d.ts`, content: `declare class file {}` }); @@ -266,13 +268,13 @@ export function Component(x: Config): any;` system.deleteFile(class3Dts); assert.deepEqual( ls.getProgram()!.getSourceFiles().map(f => f.fileName), - [libFile.path, class1Dts.path, class2.path] + [libFile.path, class1Dts.path, class2.path], ); // Write output again system.writeFile(class3Dts, `declare class class3 {}`); assert.deepEqual( ls.getProgram()!.getSourceFiles().map(f => f.fileName), - [libFile.path, class1Dts.path, class3Dts, class2.path] + [libFile.path, class1Dts.path, class3Dts, class2.path], ); }); }); diff --git a/src/testRunner/unittests/services/organizeImports.ts b/src/testRunner/unittests/services/organizeImports.ts index 9794bd1d68746..ba87f5acba615 100644 --- a/src/testRunner/unittests/services/organizeImports.ts +++ b/src/testRunner/unittests/services/organizeImports.ts @@ -1,43 +1,52 @@ import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; -import { createProjectService } from "../helpers/tsserver"; +import { + createProjectService, +} from "../helpers/tsserver"; import { createServerHost, File, } from "../helpers/virtualFileSystemWithWatch"; -import { newLineCharacter } from "./extract/helpers"; +import { + newLineCharacter, +} from "./extract/helpers"; describe("unittests:: services:: organizeImports", () => { describe("Sort imports", () => { it("Sort - non-relative vs non-relative", () => { assertSortsBefore( `import y from "lib1";`, - `import x from "lib2";`); + `import x from "lib2";`, + ); }); it("Sort - relative vs relative", () => { assertSortsBefore( `import y from "./lib1";`, - `import x from "./lib2";`); + `import x from "./lib2";`, + ); }); it("Sort - relative vs non-relative", () => { assertSortsBefore( `import y from "lib";`, - `import x from "./lib";`); + `import x from "./lib";`, + ); }); it("Sort - case-insensitive", () => { assertSortsBefore( `import y from "a";`, - `import x from "Z";`); + `import x from "Z";`, + ); assertSortsBefore( `import y from "A";`, - `import x from "z";`); + `import x from "z";`, + ); }); function assertSortsBefore(importString1: string, importString2: string) { - const [{moduleSpecifier: moduleSpecifier1}, {moduleSpecifier: moduleSpecifier2}] = parseImports(importString1, importString2); + const [{ moduleSpecifier: moduleSpecifier1 }, { moduleSpecifier: moduleSpecifier2 }] = parseImports(importString1, importString2); assert.equal(ts.OrganizeImports.compareModuleSpecifiers(moduleSpecifier1, moduleSpecifier2, /*ignoreCase*/ true), ts.Comparison.LessThan); assert.equal(ts.OrganizeImports.compareModuleSpecifiers(moduleSpecifier2, moduleSpecifier1, /*ignoreCase*/ true), ts.Comparison.GreaterThan); } @@ -58,7 +67,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine side-effect-only imports", () => { const sortedImports = parseImports( `import "lib";`, - `import "lib";`); + `import "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = parseImports(`import "lib";`); assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -67,7 +77,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine namespace imports", () => { const sortedImports = parseImports( `import * as x from "lib";`, - `import * as y from "lib";`); + `import * as y from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = sortedImports; assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -76,7 +87,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine default imports", () => { const sortedImports = parseImports( `import x from "lib";`, - `import y from "lib";`); + `import y from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = parseImports(`import { default as x, default as y } from "lib";`); assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -85,7 +97,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine property imports", () => { const sortedImports = parseImports( `import { x } from "lib";`, - `import { y as z } from "lib";`); + `import { y as z } from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = parseImports(`import { x, y as z } from "lib";`); assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -94,7 +107,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine side-effect-only import with namespace import", () => { const sortedImports = parseImports( `import "lib";`, - `import * as x from "lib";`); + `import * as x from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = sortedImports; assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -103,7 +117,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine side-effect-only import with default import", () => { const sortedImports = parseImports( `import "lib";`, - `import x from "lib";`); + `import x from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = sortedImports; assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -112,7 +127,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine side-effect-only import with property import", () => { const sortedImports = parseImports( `import "lib";`, - `import { x } from "lib";`); + `import { x } from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = sortedImports; assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -121,17 +137,20 @@ describe("unittests:: services:: organizeImports", () => { it("Combine namespace import with default import", () => { const sortedImports = parseImports( `import * as x from "lib";`, - `import y from "lib";`); + `import y from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = parseImports( - `import y, * as x from "lib";`); + `import y, * as x from "lib";`, + ); assertListEqual(actualCoalescedImports, expectedCoalescedImports); }); it("Combine namespace import with property import", () => { const sortedImports = parseImports( `import * as x from "lib";`, - `import { y } from "lib";`); + `import { y } from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = sortedImports; assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -140,10 +159,12 @@ describe("unittests:: services:: organizeImports", () => { it("Combine default import with property import", () => { const sortedImports = parseImports( `import x from "lib";`, - `import { y } from "lib";`); + `import { y } from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = parseImports( - `import x, { y } from "lib";`); + `import x, { y } from "lib";`, + ); assertListEqual(actualCoalescedImports, expectedCoalescedImports); }); @@ -156,13 +177,15 @@ describe("unittests:: services:: organizeImports", () => { `import "lib";`, `import * as x from "lib";`, `import z from "lib";`, - `import { a } from "lib";`); + `import { a } from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = parseImports( `import "lib";`, `import * as x from "lib";`, `import * as y from "lib";`, - `import { a, b, default as w, default as z } from "lib";`); + `import { a, b, default as w, default as z } from "lib";`, + ); assertListEqual(actualCoalescedImports, expectedCoalescedImports); }); @@ -171,7 +194,8 @@ describe("unittests:: services:: organizeImports", () => { const sortedImports = parseImports( `import * as x from "lib";`, `import * as y from "lib";`, - `import z from "lib";`); + `import z from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = sortedImports; assertListEqual(actualCoalescedImports, expectedCoalescedImports); @@ -181,11 +205,13 @@ describe("unittests:: services:: organizeImports", () => { const sortedImports = parseImports( `import type { x } from "lib";`, `import type { y } from "lib";`, - `import { z } from "lib";`); + `import { z } from "lib";`, + ); const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); const expectedCoalescedImports = parseImports( `import { z } from "lib";`, - `import type { x, y } from "lib";`); + `import type { x, y } from "lib";`, + ); assertListEqual(actualCoalescedImports, expectedCoalescedImports); }); @@ -193,7 +219,8 @@ describe("unittests:: services:: organizeImports", () => { const sortedImports = parseImports( `import type { x } from "lib";`, `import type * as y from "lib";`, - `import type z from "lib";`); + `import type z from "lib";`, + ); // Default import could be rewritten as a named import to combine with `x`, // but seems of debatable merit. const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true); @@ -224,7 +251,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine namespace re-exports", () => { const sortedExports = parseExports( `export * from "lib";`, - `export * from "lib";`); + `export * from "lib";`, + ); const actualCoalescedExports = ts.OrganizeImports.coalesceExports(sortedExports, /*ignoreCase*/ true); const expectedCoalescedExports = parseExports(`export * from "lib";`); assertListEqual(actualCoalescedExports, expectedCoalescedExports); @@ -233,7 +261,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine property exports", () => { const sortedExports = parseExports( `export { x };`, - `export { y as z };`); + `export { y as z };`, + ); const actualCoalescedExports = ts.OrganizeImports.coalesceExports(sortedExports, /*ignoreCase*/ true); const expectedCoalescedExports = parseExports(`export { x, y as z };`); assertListEqual(actualCoalescedExports, expectedCoalescedExports); @@ -242,7 +271,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine property re-exports", () => { const sortedExports = parseExports( `export { x } from "lib";`, - `export { y as z } from "lib";`); + `export { y as z } from "lib";`, + ); const actualCoalescedExports = ts.OrganizeImports.coalesceExports(sortedExports, /*ignoreCase*/ true); const expectedCoalescedExports = parseExports(`export { x, y as z } from "lib";`); assertListEqual(actualCoalescedExports, expectedCoalescedExports); @@ -251,7 +281,8 @@ describe("unittests:: services:: organizeImports", () => { it("Combine namespace re-export with property re-export", () => { const sortedExports = parseExports( `export * from "lib";`, - `export { y } from "lib";`); + `export { y } from "lib";`, + ); const actualCoalescedExports = ts.OrganizeImports.coalesceExports(sortedExports, /*ignoreCase*/ true); const expectedCoalescedExports = sortedExports; assertListEqual(actualCoalescedExports, expectedCoalescedExports); @@ -261,10 +292,12 @@ describe("unittests:: services:: organizeImports", () => { const sortedExports = parseExports( `export { x };`, `export { y as w, z as default };`, - `export { w as q };`); + `export { w as q };`, + ); const actualCoalescedExports = ts.OrganizeImports.coalesceExports(sortedExports, /*ignoreCase*/ true); const expectedCoalescedExports = parseExports( - `export { z as default, w as q, y as w, x };`); + `export { z as default, w as q, y as w, x };`, + ); assertListEqual(actualCoalescedExports, expectedCoalescedExports); }); @@ -272,18 +305,21 @@ describe("unittests:: services:: organizeImports", () => { const sortedExports = parseExports( `export { x as a, y } from "lib";`, `export * from "lib";`, - `export { z as b } from "lib";`); + `export { z as b } from "lib";`, + ); const actualCoalescedExports = ts.OrganizeImports.coalesceExports(sortedExports, /*ignoreCase*/ true); const expectedCoalescedExports = parseExports( `export * from "lib";`, - `export { x as a, z as b, y } from "lib";`); + `export { x as a, z as b, y } from "lib";`, + ); assertListEqual(actualCoalescedExports, expectedCoalescedExports); }); it("Keep type-only exports separate", () => { const sortedExports = parseExports( `export { x };`, - `export type { y };`); + `export type { y };`, + ); const actualCoalescedExports = ts.OrganizeImports.coalesceExports(sortedExports, /*ignoreCase*/ true); const expectedCoalescedExports = sortedExports; assertListEqual(actualCoalescedExports, expectedCoalescedExports); @@ -292,17 +328,17 @@ describe("unittests:: services:: organizeImports", () => { it("Combine type-only exports", () => { const sortedExports = parseExports( `export type { x };`, - `export type { y };`); + `export type { y };`, + ); const actualCoalescedExports = ts.OrganizeImports.coalesceExports(sortedExports, /*ignoreCase*/ true); const expectedCoalescedExports = parseExports( - `export type { x, y };`); + `export type { x, y };`, + ); assertListEqual(actualCoalescedExports, expectedCoalescedExports); }); }); - describe("Baselines", () => { - const libFile = { path: "/lib.ts", content: ` @@ -346,29 +382,24 @@ export const Other = 1; it("doesn't return any changes when the text would be identical", () => { const testFile = { path: "/a.ts", - content: `import { f } from 'foo';\nf();` + content: `import { f } from 'foo';\nf();`, }; const languageService = makeLanguageService(testFile); const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, ts.testFormatSettings, ts.emptyOptions); assert.isEmpty(changes); }); - testOrganizeImports("Renamed_used", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("Renamed_used", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { F1 as EffOne, F2 as EffTwo } from "lib"; EffOne(); `, - }, - libFile); + }, libFile); - testOrganizeImports("Simple", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("Simple", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { F1, F2 } from "lib"; import * as NS from "lib"; import D from "lib"; @@ -378,29 +409,23 @@ D(); F1(); F2(); `, - }, - libFile); + }, libFile); - testOrganizeImports("Unused_Some", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("Unused_Some", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { F1, F2 } from "lib"; import * as NS from "lib"; import D from "lib"; D(); `, - }, - libFile); - - describe("skipDestructiveCodeActions=true", () => { - testOrganizeImports("Syntax_Error_Body_skipDestructiveCodeActions", - /*skipDestructiveCodeActions*/ true, - { - path: "/test.ts", - content: ` + }, libFile); + + describe("skipDestructiveCodeActions=true", () => { + testOrganizeImports("Syntax_Error_Body_skipDestructiveCodeActions", /*skipDestructiveCodeActions*/ true, { + path: "/test.ts", + content: ` import { F1, F2 } from "lib"; import * as NS from "lib"; import D from "lib"; @@ -408,15 +433,12 @@ import D from "lib"; class class class; D; `, - }, - libFile); - }); - - testOrganizeImports("Syntax_Error_Imports_skipDestructiveCodeActions", - /*skipDestructiveCodeActions*/ true, - { - path: "/test.ts", - content: ` + }, libFile); + }); + + testOrganizeImports("Syntax_Error_Imports_skipDestructiveCodeActions", /*skipDestructiveCodeActions*/ true, { + path: "/test.ts", + content: ` import { F1, F2 class class class; } from "lib"; import * as NS from "lib"; class class class; @@ -424,15 +446,12 @@ import D from "lib"; D; `, - }, - libFile); - - describe("skipDestructiveCodeActions=false", () => { - testOrganizeImports("Syntax_Error_Body", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + }, libFile); + + describe("skipDestructiveCodeActions=false", () => { + testOrganizeImports("Syntax_Error_Body", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { F1, F2 } from "lib"; import * as NS from "lib"; import D from "lib"; @@ -440,14 +459,11 @@ import D from "lib"; class class class; D; `, - }, - libFile); - - testOrganizeImports("Syntax_Error_Imports", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + }, libFile); + + testOrganizeImports("Syntax_Error_Imports", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { F1, F2 class class class; } from "lib"; import * as NS from "lib"; class class class; @@ -455,31 +471,27 @@ import D from "lib"; D; `, - }, - libFile); - }); - - it("doesn't return any changes when the text would be identical", () => { - const testFile = { - path: "/a.ts", - content: `import { f } from 'foo';\nf();` - }; - const languageService = makeLanguageService(testFile); - const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, ts.testFormatSettings, ts.emptyOptions); - assert.isEmpty(changes); - }); - - testOrganizeImports("Unused_All", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + }, libFile); + }); + + it("doesn't return any changes when the text would be identical", () => { + const testFile = { + path: "/a.ts", + content: `import { f } from 'foo';\nf();`, + }; + const languageService = makeLanguageService(testFile); + const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, ts.testFormatSettings, ts.emptyOptions); + assert.isEmpty(changes); + }); + + testOrganizeImports("Unused_All", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { F1, F2 } from "lib"; import * as NS from "lib"; import D from "lib"; `, - }, - libFile); + }, libFile); it("Unused_Empty", () => { const testFile = { @@ -493,11 +505,9 @@ import { } from "lib"; assert.isEmpty(changes); }); - testOrganizeImports("Unused_false_positive_module_augmentation", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.d.ts", - content: ` + testOrganizeImports("Unused_false_positive_module_augmentation", /*skipDestructiveCodeActions*/ false, { + path: "/test.d.ts", + content: ` import foo from 'foo'; import { Caseless } from 'caseless'; @@ -506,14 +516,12 @@ declare module 'caseless' { interface Caseless { test(name: KeyType): boolean; } -}` - }); +}`, + }); - testOrganizeImports("Unused_preserve_imports_for_module_augmentation_in_non_declaration_file", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("Unused_preserve_imports_for_module_augmentation_in_non_declaration_file", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import foo from 'foo'; import { Caseless } from 'caseless'; @@ -522,7 +530,7 @@ declare module 'caseless' { interface Caseless { test(name: KeyType): boolean; } -}` +}`, }); it("Unused_false_positive_shorthand_assignment", () => { @@ -531,7 +539,7 @@ declare module 'caseless' { content: ` import { x } from "a"; const o = { x }; -` +`, }; const languageService = makeLanguageService(testFile); const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, ts.testFormatSettings, ts.emptyOptions); @@ -544,18 +552,16 @@ const o = { x }; content: ` import { x } from "a"; export { x }; -` +`, }; const languageService = makeLanguageService(testFile); const changes = languageService.organizeImports({ type: "file", fileName: testFile.path }, ts.testFormatSettings, ts.emptyOptions); assert.isEmpty(changes); }); - testOrganizeImports("MoveToTop", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("MoveToTop", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { F1, F2 } from "lib"; F1(); F2(); @@ -564,15 +570,12 @@ NS.F1(); import D from "lib"; D(); `, - }, - libFile); + }, libFile); /* eslint-disable no-template-curly-in-string */ - testOrganizeImports("MoveToTop_Invalid", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("MoveToTop_Invalid", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { F1, F2 } from "lib"; F1(); F2(); @@ -583,24 +586,22 @@ import a from ${"`${'lib'}`"}; import D from "lib"; D(); `, - }, - libFile); + }, libFile); /* eslint-enable no-template-curly-in-string */ - testOrganizeImports("TypeOnly", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("TypeOnly", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { X } from "lib"; import type Y from "lib"; import { Z } from "lib"; import type { A, B } from "lib"; -export { A, B, X, Y, Z };` - }); +export { A, B, X, Y, Z };`, + }); - testOrganizeImports("CoalesceMultipleModules", + testOrganizeImports( + "CoalesceMultipleModules", /*skipDestructiveCodeActions*/ false, { path: "/test.ts", @@ -613,23 +614,22 @@ a + b + c + d; `, }, { path: "/lib1.ts", content: "export const b = 1, d = 2;" }, - { path: "/lib2.ts", content: "export const a = 3, c = 4;" }); + { path: "/lib2.ts", content: "export const a = 3, c = 4;" }, + ); - testOrganizeImports("CoalesceTrivia", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("CoalesceTrivia", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` /*A*/import /*B*/ { /*C*/ F2 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/;/*H*/ //I /*J*/import /*K*/ { /*L*/ F1 /*M*/ } /*N*/ from /*O*/ "lib" /*P*/;/*Q*/ //R F1(); F2(); `, - }, - libFile); + }, libFile); - testOrganizeImports("SortTrivia", + testOrganizeImports( + "SortTrivia", /*skipDestructiveCodeActions*/ false, { path: "/test.ts", @@ -639,42 +639,35 @@ F2(); `, }, { path: "/lib1.ts", content: "" }, - { path: "/lib2.ts", content: "" }); + { path: "/lib2.ts", content: "" }, + ); - testOrganizeImports("UnusedTrivia1", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("UnusedTrivia1", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` /*A*/import /*B*/ { /*C*/ F1 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/;/*H*/ //I `, - }, - libFile); + }, libFile); - testOrganizeImports("UnusedTrivia2", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("UnusedTrivia2", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` /*A*/import /*B*/ { /*C*/ F1 /*D*/, /*E*/ F2 /*F*/ } /*G*/ from /*H*/ "lib" /*I*/;/*J*/ //K F1(); `, - }, - libFile); + }, libFile); - testOrganizeImports("UnusedHeaderComment", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("UnusedHeaderComment", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` // Header import { F1 } from "lib"; `, - }, - libFile); + }, libFile); - testOrganizeImports("SortHeaderComment", + testOrganizeImports( + "SortHeaderComment", /*skipDestructiveCodeActions*/ false, { path: "/test.ts", @@ -685,13 +678,12 @@ import "lib1"; `, }, { path: "/lib1.ts", content: "" }, - { path: "/lib2.ts", content: "" }); + { path: "/lib2.ts", content: "" }, + ); - testOrganizeImports("AmbientModule", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("AmbientModule", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` declare module "mod" { import { F1 } from "lib"; import * as NS from "lib"; @@ -700,14 +692,11 @@ declare module "mod" { function F(f1: {} = F1, f2: {} = F2) {} } `, - }, - libFile); + }, libFile); - testOrganizeImports("TopLevelAndAmbientModule", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("TopLevelAndAmbientModule", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import D from "lib"; declare module "mod" { @@ -723,168 +712,130 @@ import "lib"; D(); `, - }, - libFile); + }, libFile); - testOrganizeImports("JsxFactoryUsedJsx", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.jsx", - content: ` + testOrganizeImports("JsxFactoryUsedJsx", /*skipDestructiveCodeActions*/ false, { + path: "/test.jsx", + content: ` import { React, Other } from "react";
; `, - }, - reactLibFile); + }, reactLibFile); - testOrganizeImports("JsxFactoryUsedJs", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.js", - content: ` + testOrganizeImports("JsxFactoryUsedJs", /*skipDestructiveCodeActions*/ false, { + path: "/test.js", + content: ` import { React, Other } from "react";
; `, - }, - reactLibFile); + }, reactLibFile); - testOrganizeImports("JsxFactoryUsedTsx", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.tsx", - content: ` + testOrganizeImports("JsxFactoryUsedTsx", /*skipDestructiveCodeActions*/ false, { + path: "/test.tsx", + content: ` import { React, Other } from "react";
; `, - }, - reactLibFile); + }, reactLibFile); // TS files are not JSX contexts, so the parser does not treat // `
` as a JSX element. - testOrganizeImports("JsxFactoryUsedTs", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("JsxFactoryUsedTs", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { React, Other } from "react";
; `, - }, - reactLibFile); + }, reactLibFile); - testOrganizeImports("JsxFactoryUnusedJsx", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.jsx", - content: ` + testOrganizeImports("JsxFactoryUnusedJsx", /*skipDestructiveCodeActions*/ false, { + path: "/test.jsx", + content: ` import { React, Other } from "react"; `, - }, - reactLibFile); + }, reactLibFile); // Note: Since the file extension does not end with "x", the jsx compiler option // will not be enabled. The import should be retained regardless. - testOrganizeImports("JsxFactoryUnusedJs", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.js", - content: ` + testOrganizeImports("JsxFactoryUnusedJs", /*skipDestructiveCodeActions*/ false, { + path: "/test.js", + content: ` import { React, Other } from "react"; `, - }, - reactLibFile); + }, reactLibFile); - testOrganizeImports("JsxFactoryUnusedTsx", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.tsx", - content: ` + testOrganizeImports("JsxFactoryUnusedTsx", /*skipDestructiveCodeActions*/ false, { + path: "/test.tsx", + content: ` import { React, Other } from "react"; `, - }, - reactLibFile); + }, reactLibFile); - testOrganizeImports("JsxFactoryUnusedTs", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.ts", - content: ` + testOrganizeImports("JsxFactoryUnusedTs", /*skipDestructiveCodeActions*/ false, { + path: "/test.ts", + content: ` import { React, Other } from "react"; `, - }, - reactLibFile); + }, reactLibFile); - testOrganizeImports("JsxPragmaTsx", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.tsx", - content: `/** @jsx jsx */ + testOrganizeImports("JsxPragmaTsx", /*skipDestructiveCodeActions*/ false, { + path: "/test.tsx", + content: `/** @jsx jsx */ import { Global, jsx } from '@emotion/core'; import * as React from 'react'; export const App: React.FunctionComponent = _ =>

Hello!

`, - }, - { - path: "/@emotion/core/index.d.ts", - content: `import { createElement } from 'react' + }, { + path: "/@emotion/core/index.d.ts", + content: `import { createElement } from 'react' export const jsx: typeof createElement; -export function Global(props: any): ReactElement;` - }, - { - path: reactLibFile.path, - content: `${reactLibFile.content} +export function Global(props: any): ReactElement;`, + }, { + path: reactLibFile.path, + content: `${reactLibFile.content} export namespace React { interface FunctionComponent { } } -` - } - ); +`, + }); - testOrganizeImports("JsxFragmentPragmaTsx", - /*skipDestructiveCodeActions*/ false, - { - path: "/test.tsx", - content: `/** @jsx h */ + testOrganizeImports("JsxFragmentPragmaTsx", /*skipDestructiveCodeActions*/ false, { + path: "/test.tsx", + content: `/** @jsx h */ /** @jsxFrag frag */ import { h, frag } from "@foo/core"; const elem = <>
Foo
; `, - }, - { - path: "/@foo/core/index.d.ts", - content: `export function h(): void; + }, { + path: "/@foo/core/index.d.ts", + content: `export function h(): void; export function frag(): void; -` - } - ); +`, + }); describe("Exports", () => { - - testOrganizeExports("MoveToTop", - { - path: "/test.ts", - content: ` + testOrganizeExports("MoveToTop", { + path: "/test.ts", + content: ` export { F1, F2 } from "lib"; 1; export * from "lib"; 2; `, - }, - libFile); + }, libFile); /* eslint-disable no-template-curly-in-string */ - testOrganizeExports("MoveToTop_Invalid", - { - path: "/test.ts", - content: ` + testOrganizeExports("MoveToTop_Invalid", { + path: "/test.ts", + content: ` export { F1, F2 } from "lib"; 1; export * from "lib"; @@ -894,14 +845,12 @@ export { a } from ${"`${'lib'}`"}; export { D } from "lib"; 3; `, - }, - libFile); + }, libFile); /* eslint-enable no-template-curly-in-string */ - testOrganizeExports("MoveToTop_WithImportsFirst", - { - path: "/test.ts", - content: ` + testOrganizeExports("MoveToTop_WithImportsFirst", { + path: "/test.ts", + content: ` import { F1, F2 } from "lib"; 1; export { F1, F2 } from "lib"; @@ -912,13 +861,11 @@ export * from "lib"; 4; F1(); F2(); NS.F1(); `, - }, - libFile); + }, libFile); - testOrganizeExports("MoveToTop_WithExportsFirst", - { - path: "/test.ts", - content: ` + testOrganizeExports("MoveToTop_WithExportsFirst", { + path: "/test.ts", + content: ` export { F1, F2 } from "lib"; 1; import { F1, F2 } from "lib"; @@ -929,10 +876,10 @@ import * as NS from "lib"; 4; F1(); F2(); NS.F1(); `, - }, - libFile); + }, libFile); - testOrganizeExports("CoalesceMultipleModules", + testOrganizeExports( + "CoalesceMultipleModules", { path: "/test.ts", content: ` @@ -943,19 +890,19 @@ export { a } from "lib2"; `, }, { path: "/lib1.ts", content: "export const b = 1, d = 2;" }, - { path: "/lib2.ts", content: "export const a = 3, c = 4;" }); + { path: "/lib2.ts", content: "export const a = 3, c = 4;" }, + ); - testOrganizeExports("CoalesceTrivia", - { - path: "/test.ts", - content: ` + testOrganizeExports("CoalesceTrivia", { + path: "/test.ts", + content: ` /*A*/export /*B*/ { /*C*/ F2 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/;/*H*/ //I /*J*/export /*K*/ { /*L*/ F1 /*M*/ } /*N*/ from /*O*/ "lib" /*P*/;/*Q*/ //R `, - }, - libFile); + }, libFile); - testOrganizeExports("SortTrivia", + testOrganizeExports( + "SortTrivia", { path: "/test.ts", content: ` @@ -964,9 +911,11 @@ export { a } from "lib2"; `, }, { path: "/lib1.ts", content: "" }, - { path: "/lib2.ts", content: "" }); + { path: "/lib2.ts", content: "" }, + ); - testOrganizeExports("SortHeaderComment", + testOrganizeExports( + "SortHeaderComment", { path: "/test.ts", content: ` @@ -976,25 +925,23 @@ export * from "lib1"; `, }, { path: "/lib1.ts", content: "" }, - { path: "/lib2.ts", content: "" }); + { path: "/lib2.ts", content: "" }, + ); - testOrganizeExports("AmbientModule", - { - path: "/test.ts", - content: ` + testOrganizeExports("AmbientModule", { + path: "/test.ts", + content: ` declare module "mod" { export { F1 } from "lib"; export * from "lib"; export { F2 } from "lib"; } `, - }, - libFile); + }, libFile); - testOrganizeExports("TopLevelAndAmbientModule", - { - path: "/test.ts", - content: ` + testOrganizeExports("TopLevelAndAmbientModule", { + path: "/test.ts", + content: ` export { D } from "lib"; declare module "mod" { @@ -1006,8 +953,7 @@ declare module "mod" { export { E } from "lib"; export * from "lib"; `, - }, - libFile); + }, libFile); }); function testOrganizeExports(testName: string, testFile: File, ...otherFiles: File[]) { @@ -1026,12 +972,15 @@ export * from "lib"; assert.equal(changes[0].fileName, testPath); const newText = ts.textChanges.applyChanges(testContent, changes[0].textChanges); - Harness.Baseline.runBaseline(baselinePath, [ - "// ==ORIGINAL==", - testContent, - "// ==ORGANIZED==", - newText, - ].join(newLineCharacter)); + Harness.Baseline.runBaseline( + baselinePath, + [ + "// ==ORIGINAL==", + testContent, + "// ==ORGANIZED==", + newText, + ].join(newLineCharacter), + ); } function makeLanguageService(...files: File[]) { diff --git a/src/testRunner/unittests/services/preProcessFile.ts b/src/testRunner/unittests/services/preProcessFile.ts index 53332cebc5220..1bd38bb2e0851 100644 --- a/src/testRunner/unittests/services/preProcessFile.ts +++ b/src/testRunner/unittests/services/preProcessFile.ts @@ -23,251 +23,219 @@ describe("unittests:: services:: PreProcessFile:", () => { describe("Test preProcessFiles,", () => { it("Correctly return referenced files from triple slash", () => { - test("///" + "\n" + "///" + "\n" + "///" + "\n" + "///", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [{ fileName: "refFile1.ts", pos: 22, end: 33 }, { fileName: "refFile2.ts", pos: 59, end: 70 }, - { fileName: "refFile3.ts", pos: 94, end: 105 }, { fileName: "..\\refFile4d.ts", pos: 131, end: 146 }], - importedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - ambientExternalModules: undefined, - isLibFile: false - }); + test('///' + "\n" + '///' + "\n" + '///' + "\n" + '///', /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { + referencedFiles: [{ fileName: "refFile1.ts", pos: 22, end: 33 }, { fileName: "refFile2.ts", pos: 59, end: 70 }, { fileName: "refFile3.ts", pos: 94, end: 105 }, { fileName: "..\\refFile4d.ts", pos: 131, end: 146 }], + importedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + ambientExternalModules: undefined, + isLibFile: false, + }); }); it("Do not return reference path because of invalid triple-slash syntax", () => { - test("///" + "\n" + "///" + "\n" + "///" + "\n" + "///", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [] as ts.FileReference[], - importedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - ambientExternalModules: undefined, - isLibFile: false - }); + test('///' + "\n" + '///' + "\n" + '///' + "\n" + '///', /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { + referencedFiles: [] as ts.FileReference[], + importedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + ambientExternalModules: undefined, + isLibFile: false, + }); }); it("Do not return reference path of non-imports", () => { - test("Quill.import('delta');", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [] as ts.FileReference[], - importedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - ambientExternalModules: undefined, - isLibFile: false - }); + test("Quill.import('delta');", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { + referencedFiles: [] as ts.FileReference[], + importedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + ambientExternalModules: undefined, + isLibFile: false, + }); }); it("Do not return reference path of nested non-imports", () => { - test("a.b.import('c');", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [] as ts.FileReference[], - importedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - ambientExternalModules: undefined, - isLibFile: false - }); + test("a.b.import('c');", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { + referencedFiles: [] as ts.FileReference[], + importedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + ambientExternalModules: undefined, + isLibFile: false, + }); }); it("Correctly return imported files", () => { - test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [{ fileName: "r1.ts", pos: 20, end: 25 }, { fileName: "r2.ts", pos: 49, end: 54 }, { fileName: "r3.ts", pos: 78, end: 83 }, - { fileName: "r4.ts", pos: 106, end: 111 }, { fileName: "r5.ts", pos: 138, end: 143 }], - ambientExternalModules: undefined, - isLibFile: false - }); + test('import i1 = require("r1.ts"); import i2 =require("r2.ts"); import i3= require("r3.ts"); import i4=require("r4.ts"); import i5 = require ("r5.ts");', /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { + referencedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [{ fileName: "r1.ts", pos: 20, end: 25 }, { fileName: "r2.ts", pos: 49, end: 54 }, { fileName: "r3.ts", pos: 78, end: 83 }, { fileName: "r4.ts", pos: 106, end: 111 }, { fileName: "r5.ts", pos: 138, end: 143 }], + ambientExternalModules: undefined, + isLibFile: false, + }); }); it("Do not return imported files if readImportFiles argument is false", () => { - test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");", - /*readImportFile*/ false, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [] as ts.FileReference[], - ambientExternalModules: undefined, - isLibFile: false - }); + test('import i1 = require("r1.ts"); import i2 =require("r2.ts"); import i3= require("r3.ts"); import i4=require("r4.ts"); import i5 = require ("r5.ts");', /*readImportFile*/ false, /*detectJavaScriptImports*/ false, { + referencedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [] as ts.FileReference[], + ambientExternalModules: undefined, + isLibFile: false, + }); }); it("Do not return import path because of invalid import syntax", () => { - test("import i1 require(\"r1.ts\"); import = require(\"r2.ts\") import i3= require(\"r3.ts\"); import i5", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [{ fileName: "r3.ts", pos: 73, end: 78 }], - ambientExternalModules: undefined, - isLibFile: false - }); + test('import i1 require("r1.ts"); import = require("r2.ts") import i3= require("r3.ts"); import i5', /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { + referencedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [{ fileName: "r3.ts", pos: 73, end: 78 }], + ambientExternalModules: undefined, + isLibFile: false, + }); }); it("Correctly return referenced files and import files", () => { - test("///" + "\n" + "///" + "\n" + "import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\");", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }, { fileName: "refFile2.ts", pos: 57, end: 68 }], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [{ fileName: "r1.ts", pos: 92, end: 97 }, { fileName: "r2.ts", pos: 121, end: 126 }], - ambientExternalModules: undefined, - isLibFile: false - }); + test('///' + "\n" + '///' + "\n" + 'import i1 = require("r1.ts"); import i2 =require("r2.ts");', /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { + referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }, { fileName: "refFile2.ts", pos: 57, end: 68 }], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [{ fileName: "r1.ts", pos: 92, end: 97 }, { fileName: "r2.ts", pos: 121, end: 126 }], + ambientExternalModules: undefined, + isLibFile: false, + }); }); it("Correctly return referenced files and import files even with some invalid syntax", () => { - test("///" + "\n" + "///" + "\n" + "import i1 = require(\"r1.ts\"); import = require(\"r2.ts\"); import i2 = require(\"r3.ts\");", + test('///' + "\n" + '///' + "\n" + 'import i1 = require("r1.ts"); import = require("r2.ts"); import i2 = require("r3.ts");', /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { + referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [{ fileName: "r1.ts", pos: 91, end: 96 }, { fileName: "r3.ts", pos: 148, end: 153 }], + ambientExternalModules: undefined, + isLibFile: false, + }); + }); + + it("Correctly return ES6 imports", () => { + test( + 'import * as ns from "m1";' + "\n" + + 'import def, * as ns from "m2";' + "\n" + + 'import def from "m3";' + "\n" + + 'import {a} from "m4";' + "\n" + + '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: [{ fileName: "refFile1.ts", pos: 20, end: 31 }], + referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], - importedFiles: [{ fileName: "r1.ts", pos: 91, end: 96 }, { fileName: "r3.ts", pos: 148, end: 153 }], + 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 imports", () => { - test("import * as ns from \"m1\";" + "\n" + - "import def, * as ns from \"m2\";" + "\n" + - "import def from \"m3\";" + "\n" + - "import {a} from \"m4\";" + "\n" + - "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 - }); + isLibFile: false, + }, + ); }); it("Correctly ignore commented imports following template expression", () => { /* eslint-disable no-template-curly-in-string */ - test("/**" + "\n" + - " * Before" + "\n" + - " * ```" + "\n" + - " * import * as a from \"a\";" + "\n" + - " * ```" + "\n" + - " */" + "\n" + - "type Foo = `${string}`;" + "\n" + + test( "/**" + "\n" + - " * After" + "\n" + - " * ```" + "\n" + - " * import { B } from \"b\";" + "\n" + - " * import * as c from \"c\";" + "\n" + - " * ```" + "\n" + - " */", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [], - ambientExternalModules: undefined, - isLibFile: false - }); + " * Before" + "\n" + + " * ```" + "\n" + + ' * import * as a from "a";' + "\n" + + " * ```" + "\n" + + " */" + "\n" + + "type Foo = `${string}`;" + "\n" + + "/**" + "\n" + + " * After" + "\n" + + " * ```" + "\n" + + ' * import { B } from "b";' + "\n" + + ' * import * as c from "c";' + "\n" + + " * ```" + "\n" + + " */", + /*readImportFile*/ true, + /*detectJavaScriptImports*/ true, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); /* eslint-enable no-template-curly-in-string */ }); it("Ignores imports in template strings", () => { /* eslint-disable no-template-curly-in-string */ - test("a ? `&${a}` : `#${b}`;\n\n `import(\"${moduleSpecifier}\").${id}`;", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { + test('a ? `&${a}` : `#${b}`;\n\n `import("${moduleSpecifier}").${id}`;', /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [], ambientExternalModules: undefined, - isLibFile: false + isLibFile: false, }); /* eslint-enable no-template-curly-in-string */ }); it("Correctly returns imports after a template expression", () => { /* eslint-disable no-template-curly-in-string */ - test("`${foo}`; import \"./foo\";", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { + test('`${foo}`; import "./foo";', /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ - { fileName: "./foo", pos: 17, end: 22 } + { fileName: "./foo", pos: 17, end: 22 }, ], ambientExternalModules: undefined, - isLibFile: false + isLibFile: false, }); /* eslint-enable no-template-curly-in-string */ }); it("Correctly returns dynamic imports from template expression", () => { /* eslint-disable no-template-curly-in-string */ - test("`${(
Text `` ${} text {} " + "\n" + - "${import(\"a\")} {import(\"b\")} " + "\n" + - "${/* A comment */} ${/* import(\"ignored\") */}
)}`", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "a", pos: 39, end: 40 }, - { fileName: "b", pos: 53, end: 54 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + test( + "`${(
Text `` ${} text {} " + "\n" + + '${import("a")} {import("b")} ' + "\n" + + '${/* A comment */} ${/* import("ignored") */}
)}`', + /*readImportFile*/ true, + /*detectJavaScriptImports*/ true, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "a", pos: 39, end: 40 }, + { fileName: "b", pos: 53, end: 54 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); /* eslint-enable no-template-curly-in-string */ }); it("Correctly returns dynamic imports from nested template expression", () => { /* eslint-disable no-template-curly-in-string */ - test("`${foo(`${bar(`${import(\"a\")} ${import(\"b\")}`, `${baz(`${import(\"c\") ${import(\"d\")}`)}`)}`)}`", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { + test('`${foo(`${bar(`${import("a")} ${import("b")}`, `${baz(`${import("c") ${import("d")}`)}`)}`)}`', /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], @@ -278,17 +246,14 @@ describe("unittests:: services:: PreProcessFile:", () => { { fileName: "d", pos: 78, end: 79 }, ], ambientExternalModules: undefined, - isLibFile: false + isLibFile: false, }); /* eslint-enable no-template-curly-in-string */ }); it("Correctly returns dynamic imports from tagged template expression", () => { /* eslint-disable no-template-curly-in-string */ - test("foo`${ fn({ a: 100 }, import(\"a\"), `${import(\"b\")}`, import(\"c\"), `${import(\"d\")} foo`, import(\"e\")) }`", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { + test('foo`${ fn({ a: 100 }, import("a"), `${import("b")}`, import("c"), `${import("d")} foo`, import("e")) }`', /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], @@ -300,397 +265,424 @@ describe("unittests:: services:: PreProcessFile:", () => { { fileName: "e", pos: 95, end: 96 }, ], ambientExternalModules: undefined, - isLibFile: false + isLibFile: false, }); /* eslint-enable no-template-curly-in-string */ }); it("Correctly returns dynamic imports from template expression and imports following it", () => { /* eslint-disable no-template-curly-in-string */ - test("const x = `hello ${await import(\"a\").default}`;" + "\n\n" + - "import { y } from \"b\";", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "a", pos: 32, end: 33 }, - { fileName: "b", pos: 67, end: 68 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + test( + 'const x = `hello ${await import("a").default}`;' + "\n\n" + + 'import { y } from "b";', + /*readImportFile*/ true, + /*detectJavaScriptImports*/ true, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "a", pos: 32, end: 33 }, + { fileName: "b", pos: 67, end: 68 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); /* eslint-enable no-template-curly-in-string */ }); it("Correctly returns dynamic imports from template expressions and other imports", () => { /* eslint-disable no-template-curly-in-string */ - test("const x = `x ${await import(\"a\").default}`;" + "\n\n" + - "import { y } from \"b\";" + "\n" + - "const y = `y ${import(\"c\")}`;" + "\n\n" + - "import { d } from \"d\";", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "a", pos: 28, end: 29 }, - { fileName: "b", pos: 63, end: 64 }, - { fileName: "c", pos: 90, end: 91 }, - { fileName: "d", pos: 117, end: 118 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + test( + 'const x = `x ${await import("a").default}`;' + "\n\n" + + 'import { y } from "b";' + "\n" + + 'const y = `y ${import("c")}`;' + "\n\n" + + 'import { d } from "d";', + /*readImportFile*/ true, + /*detectJavaScriptImports*/ true, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "a", pos: 28, end: 29 }, + { fileName: "b", pos: 63, end: 64 }, + { fileName: "c", pos: 90, end: 91 }, + { fileName: "d", pos: 117, end: 118 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); /* eslint-enable no-template-curly-in-string */ }); it("Correctly returns empty importedFiles with incorrect template expression", () => { - test("const foo = `${", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { + test("const foo = `${", /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [], ambientExternalModules: undefined, - isLibFile: false + isLibFile: false, }); }); it("Correctly return ES6 exports", () => { - test("export * from \"m1\";" + "\n" + - "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 - }); + test( + 'export * from "m1";' + "\n" + + '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, + }, + ); }); it("Correctly handles import types", () => { - test("import type * as ns from \"m1\";" + "\n" + - "import type def, * as ns from \"m2\";" + "\n" + - "import type def from \"m3\";" + "\n" + - "import type {a} from \"m4\";" + "\n" + - "import type {a as A} from \"m5\";" + "\n" + - "import type {a as A, b, c as C} from \"m6\";" + "\n" + - "import type def , {a, b, c as C} from \"m7\";" + "\n" + - "import type from \"m8\";" + "\n" + - "import type T = require(\"m9\");" + "\n" + - "import type = require(\"m10\");" + "\n" + - "export import type T = require(\"m11\");" + "\n" + - "export import type = require(\"m12\");" + "\n", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m1", pos: 25, end: 27 }, - { fileName: "m2", pos: 61, end: 63 }, - { fileName: "m3", pos: 88, end: 90 }, - { fileName: "m4", pos: 115, end: 117 }, - { fileName: "m5", pos: 147, end: 149 }, - { fileName: "m6", pos: 190, end: 192 }, - { fileName: "m7", pos: 234, end: 236 }, - { fileName: "m8", pos: 257, end: 259 }, - { fileName: "m9", pos: 287, end: 289 }, - { fileName: "m10", pos: 316, end: 319 }, - { fileName: "m11", pos: 355, end: 358 }, - { fileName: "m12", pos: 392, end: 395 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + test( + 'import type * as ns from "m1";' + "\n" + + 'import type def, * as ns from "m2";' + "\n" + + 'import type def from "m3";' + "\n" + + 'import type {a} from "m4";' + "\n" + + 'import type {a as A} from "m5";' + "\n" + + 'import type {a as A, b, c as C} from "m6";' + "\n" + + 'import type def , {a, b, c as C} from "m7";' + "\n" + + 'import type from "m8";' + "\n" + + 'import type T = require("m9");' + "\n" + + 'import type = require("m10");' + "\n" + + 'export import type T = require("m11");' + "\n" + + 'export import type = require("m12");' + "\n", + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m1", pos: 25, end: 27 }, + { fileName: "m2", pos: 61, end: 63 }, + { fileName: "m3", pos: 88, end: 90 }, + { fileName: "m4", pos: 115, end: 117 }, + { fileName: "m5", pos: 147, end: 149 }, + { fileName: "m6", pos: 190, end: 192 }, + { fileName: "m7", pos: 234, end: 236 }, + { fileName: "m8", pos: 257, end: 259 }, + { fileName: "m9", pos: 287, end: 289 }, + { fileName: "m10", pos: 316, end: 319 }, + { fileName: "m11", pos: 355, end: 358 }, + { fileName: "m12", pos: 392, end: 395 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("Correctly handles export types", () => { - test("export type * from \"m1\";" + "\n" + - "export type {a} from \"m2\";" + "\n" + - "export type {a as A} from \"m3\";" + "\n" + - "export type {a as A, b, c as C} from \"m4\";" + "\n", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [] as ts.FileReference[], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m1", pos: 19, end: 21 }, - { fileName: "m2", pos: 46, end: 48 }, - { fileName: "m3", pos: 78, end: 80 }, - { fileName: "m4", pos: 121, end: 123 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + test( + 'export type * from "m1";' + "\n" + + 'export type {a} from "m2";' + "\n" + + 'export type {a as A} from "m3";' + "\n" + + 'export type {a as A, b, c as C} from "m4";' + "\n", + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [] as ts.FileReference[], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m1", pos: 19, end: 21 }, + { fileName: "m2", pos: 46, end: 48 }, + { fileName: "m3", pos: 78, end: 80 }, + { fileName: "m4", pos: 121, end: 123 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("Correctly handles import type node", () => { - test("const x: import(\"m1\") = { x: 0, y: 0 };" + "\n" + - "let y: import(\"m2\").Bar.I = { a: \"\", b: 0 };" + "\n" + - "let shim: typeof import(\"m3\") = { Bar: Bar2 };" + "\n", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m1", pos: 16, end: 18 }, - { fileName: "m2", pos: 54, end: 56 }, - { fileName: "m3", pos: 109, end: 111 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + test( + 'const x: import("m1") = { x: 0, y: 0 };' + "\n" + + 'let y: import("m2").Bar.I = { a: "", b: 0 };' + "\n" + + 'let shim: typeof import("m3") = { Bar: Bar2 };' + "\n", + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m1", pos: 16, end: 18 }, + { fileName: "m2", pos: 54, end: 56 }, + { fileName: "m3", pos: 109, end: 111 }, + ], + 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 - }); - }); - - it("Correctly handles export import declarations", () => { - test("export import a = require(\"m1\");", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], - importedFiles: [ - { fileName: "m1", pos: 26, end: 28 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + importedFiles: [], + ambientExternalModules: ["B"], + isLibFile: false, + }, + ); }); - it("Correctly handles export require calls in JavaScript files", () => { - test(` - export import a = require("m1"); - var x = require('m2'); - foo(require('m3')); - var z = { f: require('m4') } - `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { + + it("Correctly handles export import declarations", () => { + test('export import a = require("m1");', /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { 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 }, + { fileName: "m1", pos: 26, end: 28 }, ], ambientExternalModules: undefined, - isLibFile: false + isLibFile: false, }); }); + it("Correctly handles export require calls in JavaScript files", () => { + test( + ` + export import a = require("m1"); + var x = require('m2'); + 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, + }, + ); + }); it("Correctly handles dependency lists in define([deplist]) calls in JavaScript files", () => { - test(` + 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(` + 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(` + test( + ` declare module "../Observable" { interface I {} } export {} `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "../Observable", pos: 28, end: 41 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "../Observable", pos: 28, end: 41 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("correctly handles augmentations in external modules - 2", () => { - test(` + test( + ` declare module "../Observable" { interface I {} } import * as x from "m"; `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m", pos: 123, end: 124 }, - { fileName: "../Observable", pos: 28, end: 41 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m", pos: 123, end: 124 }, + { fileName: "../Observable", pos: 28, end: 41 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("correctly handles augmentations in external modules - 3", () => { - test(` + test( + ` declare module "../Observable" { interface I {} } import m = require("m"); `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m", pos: 123, end: 124 }, - { fileName: "../Observable", pos: 28, end: 41 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m", pos: 123, end: 124 }, + { fileName: "../Observable", pos: 28, end: 41 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("correctly handles augmentations in external modules - 4", () => { - test(` + test( + ` declare module "../Observable" { interface I {} } namespace N {} export = N; `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "../Observable", pos: 28, end: 41 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "../Observable", pos: 28, end: 41 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("correctly handles augmentations in external modules - 5", () => { - test(` + test( + ` declare module "../Observable" { interface I {} } namespace N {} export import IN = N; `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "../Observable", pos: 28, end: 41 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "../Observable", pos: 28, end: 41 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("correctly handles augmentations in external modules - 6", () => { - test(` + test( + ` declare module "../Observable" { interface I {} } export let x = 1; `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "../Observable", pos: 28, end: 41 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "../Observable", pos: 28, end: 41 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); - it ("correctly handles augmentations in ambient external modules - 1", () => { - test(` + it("correctly handles augmentations in ambient external modules - 1", () => { + test( + ` declare module "m1" { export * from "m2"; declare module "augmentation" { @@ -698,22 +690,24 @@ describe("unittests:: services:: PreProcessFile:", () => { } } `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m2", pos: 65, end: 67 }, - { fileName: "augmentation", pos: 102, end: 114 } - ], - ambientExternalModules: ["m1"], - isLibFile: false - }); - }); - it ("correctly handles augmentations in ambient external modules - 2", () => { - test(` + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m2", pos: 65, end: 67 }, + { fileName: "augmentation", pos: 102, end: 114 }, + ], + ambientExternalModules: ["m1"], + isLibFile: false, + }, + ); + }); + it("correctly handles augmentations in ambient external modules - 2", () => { + test( + ` namespace M { var x; } import IM = M; declare module "m1" { @@ -723,118 +717,123 @@ describe("unittests:: services:: PreProcessFile:", () => { } } `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m2", pos: 127, end: 129 }, - { fileName: "augmentation", pos: 164, end: 176 } - ], - ambientExternalModules: ["m1"], - isLibFile: false - }); - }); - it ("correctly recognizes type reference directives", () => { - test(` + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m2", pos: 127, end: 129 }, + { fileName: "augmentation", pos: 164, end: 176 }, + ], + ambientExternalModules: ["m1"], + isLibFile: false, + }, + ); + }); + it("correctly recognizes type reference directives", () => { + test( + ` /// /// /// /// `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [ - { pos: 34, end: 35, fileName: "a" }, - { pos: 112, end: 114, fileName: "a2" } - ], - typeReferenceDirectives: [ - { pos: 73, end: 75, fileName: "a1" }, - { pos: 152, end: 154, fileName: "a3" } - ], - libReferenceDirectives: [], - importedFiles: [], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [ + { pos: 34, end: 35, fileName: "a" }, + { pos: 112, end: 114, fileName: "a2" }, + ], + typeReferenceDirectives: [ + { pos: 73, end: 75, fileName: "a1" }, + { pos: 152, end: 154, fileName: "a3" }, + ], + libReferenceDirectives: [], + importedFiles: [], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); - it ("correctly recognizes lib reference directives", () => { - test(` + it("correctly recognizes lib reference directives", () => { + test( + ` /// /// /// /// `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [ - { pos: 34, end: 35, fileName: "a" }, - { pos: 110, end: 112, fileName: "a2" } - ], - typeReferenceDirectives: [ - ], - libReferenceDirectives: [ - { pos: 71, end: 73, fileName: "a1" }, - { pos: 148, end: 150, fileName: "a3" } - ], - importedFiles: [], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [ + { pos: 34, end: 35, fileName: "a" }, + { pos: 110, end: 112, fileName: "a2" }, + ], + typeReferenceDirectives: [], + libReferenceDirectives: [ + { pos: 71, end: 73, fileName: "a1" }, + { pos: 148, end: 150, fileName: "a3" }, + ], + importedFiles: [], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("Correctly handles dynamic imports with template literals", () => { - test("const m1 = import('mod1');" + "\n" + - "const m2 = import(`mod2`);" + "\n" + - "Promise.all([import('mod3'), import(`mod4`)]);" + "\n" + - "import(/* webpackChunkName: 'module5' */ `mod5`);" + "\n", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "mod1", pos: 18, end: 22 }, - { fileName: "mod2", pos: 45, end: 49 }, - { fileName: "mod3", pos: 74, end: 78 }, - { fileName: "mod4", pos: 90, end: 94 }, - { fileName: "mod5", pos: 142, end: 146 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + test( + "const m1 = import('mod1');" + "\n" + + "const m2 = import(`mod2`);" + "\n" + + "Promise.all([import('mod3'), import(`mod4`)]);" + "\n" + + "import(/* webpackChunkName: 'module5' */ `mod5`);" + "\n", + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "mod1", pos: 18, end: 22 }, + { fileName: "mod2", pos: 45, end: 49 }, + { fileName: "mod3", pos: 74, end: 78 }, + { fileName: "mod4", pos: 90, end: 94 }, + { fileName: "mod5", pos: 142, end: 146 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("Correctly handles require calls with template literals in JS files", () => { - test("const m1 = require(`mod1`);" + "\n" + - "f(require(`mod2`));" + "\n" + - "const a = { x: require(`mod3`) };" + "\n", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "mod1", pos: 19, end: 23 }, - { fileName: "mod2", pos: 38, end: 42 }, - { fileName: "mod3", pos: 71, end: 75 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + test( + "const m1 = require(`mod1`);" + "\n" + + "f(require(`mod2`));" + "\n" + + "const a = { x: require(`mod3`) };" + "\n", + /*readImportFile*/ true, + /*detectJavaScriptImports*/ true, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "mod1", pos: 19, end: 23 }, + { fileName: "mod2", pos: 38, end: 42 }, + { fileName: "mod3", pos: 71, end: 75 }, + ], + ambientExternalModules: undefined, + isLibFile: false, + }, + ); }); it("Correctly handles dependency lists in define(modName, [deplist]) calls with template literals in JS files", () => { - test("define(`mod`, [`mod1`, `mod2`], (m1, m2) => {});", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { + test("define(`mod`, [`mod1`, `mod2`], (m1, m2) => {});", /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], @@ -843,7 +842,7 @@ describe("unittests:: services:: PreProcessFile:", () => { { fileName: "mod2", pos: 23, end: 27 }, ], ambientExternalModules: undefined, - isLibFile: false + isLibFile: false, }); }); }); diff --git a/src/testRunner/unittests/services/textChanges.ts b/src/testRunner/unittests/services/textChanges.ts index 0b45e947a2e55..57b3e206ef283 100644 --- a/src/testRunner/unittests/services/textChanges.ts +++ b/src/testRunner/unittests/services/textChanges.ts @@ -1,6 +1,8 @@ import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; -import { notImplementedHost } from "./extract/helpers"; +import { + notImplementedHost, +} from "./extract/helpers"; // Some tests have trailing whitespace @@ -92,18 +94,19 @@ namespace M /*typeParameters*/ undefined, /*parameters*/ ts.emptyArray, /*type*/ ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), - /*body */ ts.factory.createBlock(statements) + /*body */ ts.factory.createBlock(statements), ); - changeTracker.insertNodeBefore(sourceFile, /*before*/findChild("M2", sourceFile), newFunction); + changeTracker.insertNodeBefore(sourceFile, /*before*/ findChild("M2", sourceFile), newFunction); // replace statements with return statement const newStatement = ts.factory.createReturnStatement( ts.factory.createCallExpression( /*expression*/ newFunction.name!, /*typeArguments*/ undefined, - /*argumentsArray*/ ts.emptyArray - )); + /*argumentsArray*/ ts.emptyArray, + ), + ); changeTracker.replaceNodeRange(sourceFile, statements[0], ts.last(statements), newStatement, { suffix: newLineCharacter }); }); } @@ -167,16 +170,13 @@ var a = 4; // comment 7 changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile)); }); runSingleFileTest("deleteNodeRange2", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude }); + changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude }); }); runSingleFileTest("deleteNodeRange3", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); + changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), { trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("deleteNodeRange4", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); + changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude }); }); } function createTestVariableDeclaration(name: string) { @@ -185,7 +185,7 @@ var a = 4; // comment 7 function createTestClass() { return ts.factory.createClassDeclaration( [ - ts.factory.createToken(ts.SyntaxKind.PublicKeyword) + ts.factory.createToken(ts.SyntaxKind.PublicKeyword), ], "class1", /*typeParameters*/ undefined, @@ -193,9 +193,9 @@ var a = 4; // comment 7 ts.factory.createHeritageClause( ts.SyntaxKind.ImplementsKeyword, [ - ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier("interface1"), /*typeArguments*/ undefined) - ] - ) + ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier("interface1"), /*typeArguments*/ undefined), + ], + ), ], [ ts.factory.createPropertyDeclaration( @@ -203,9 +203,9 @@ var a = 4; // comment 7 "property1", /*questionOrExclamationToken*/ undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword), - /*initializer*/ undefined - ) - ] + /*initializer*/ undefined, + ), + ], ); } { @@ -336,7 +336,7 @@ namespace M { const superCall = ts.factory.createCallExpression( ts.factory.createSuper(), /*typeArguments*/ undefined, - /*argumentsArray*/ ts.emptyArray + /*argumentsArray*/ ts.emptyArray, ); return ts.factory.createExpressionStatement(superCall); } @@ -615,16 +615,17 @@ import { }); } { - const runTest = (name: string, text: string) => runSingleFileTest(name, /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - for (const specifier of ["x3", "x4", "x5"]) { - changeTracker.insertNodeInListAfter(sourceFile, findChild("x2", sourceFile), ts.factory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.factory.createIdentifier(specifier))); - } - }); + const runTest = (name: string, text: string) => + runSingleFileTest(name, /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { + for (const specifier of ["x3", "x4", "x5"]) { + changeTracker.insertNodeInListAfter(sourceFile, findChild("x2", sourceFile), ts.factory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, ts.factory.createIdentifier(specifier))); + } + }); - const crlfText = "import {\r\nx1,\r\nx2\r\n} from \"bar\";"; + const crlfText = 'import {\r\nx1,\r\nx2\r\n} from "bar";'; runTest("insertNodeInListAfter19", crlfText); - const lfText = "import {\nx1,\nx2\n} from \"bar\";"; + const lfText = 'import {\nx1,\nx2\n} from "bar";'; runTest("insertNodeInListAfter20", lfText); } { @@ -636,7 +637,8 @@ class A { const newNodes = []; for (let i = 0; i < 11 /*error doesn't occur with fewer nodes*/; ++i) { newNodes.push( - ts.factory.createPropertyDeclaration(/*modifiers*/ undefined, i + "", /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + ts.factory.createPropertyDeclaration(/*modifiers*/ undefined, i + "", /*questionOrExclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined), + ); } const insertAfter = findChild("x", sourceFile); for (const newNode of newNodes) { @@ -698,7 +700,8 @@ class A { ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(1)), /*questionOrExclamationToken*/ undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), - /*initializer*/ undefined); + /*initializer*/ undefined, + ); changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode); }); } @@ -715,7 +718,8 @@ class A { ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(1)), /*questionOrExclamationToken*/ undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), - /*initializer*/ undefined); + /*initializer*/ undefined, + ); changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode); }); } @@ -731,7 +735,8 @@ interface A { ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(1)), /*questionOrExclamationToken*/ undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), - /*initializer*/ undefined); + /*initializer*/ undefined, + ); changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode); }); } @@ -747,7 +752,8 @@ interface A { ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(1)), /*questionOrExclamationToken*/ undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), - /*initializer*/ undefined); + /*initializer*/ undefined, + ); changeTracker.insertNodeAfter(sourceFile, findChild("x", sourceFile), newNode); }); } diff --git a/src/testRunner/unittests/services/transpile.ts b/src/testRunner/unittests/services/transpile.ts index ae05aaa9bcd92..ddb040d7af356 100644 --- a/src/testRunner/unittests/services/transpile.ts +++ b/src/testRunner/unittests/services/transpile.ts @@ -2,7 +2,6 @@ import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; describe("unittests:: services:: Transpile", () => { - interface TranspileTestSettings { options?: ts.TranspileOptions; noSetFileName?: boolean; @@ -10,82 +9,81 @@ describe("unittests:: services:: Transpile", () => { } function transpilesCorrectly(nameIn: string, input: string, testSettings: TranspileTestSettings) { - const runOnce = (name: string, testSettings: TranspileTestSettings) => describe(name, () => { - let transpileResult: ts.TranspileOutput; - let oldTranspileResult: string; - let oldTranspileDiagnostics: ts.Diagnostic[]; - - const transpileOptions: ts.TranspileOptions = testSettings.options || {}; - if (!transpileOptions.compilerOptions) { - transpileOptions.compilerOptions = { }; - } - if (transpileOptions.compilerOptions.target === undefined) { - transpileOptions.compilerOptions.target = ts.ScriptTarget.ES3; - } - - if (transpileOptions.compilerOptions.newLine === undefined) { - // use \r\n as default new line - transpileOptions.compilerOptions.newLine = ts.NewLineKind.CarriageReturnLineFeed; - } - - transpileOptions.compilerOptions.sourceMap = true; - - let unitName = transpileOptions.fileName; - if (!unitName) { - unitName = transpileOptions.compilerOptions.jsx ? "file.tsx" : "file.ts"; - if (!testSettings.noSetFileName) { - transpileOptions.fileName = unitName; + const runOnce = (name: string, testSettings: TranspileTestSettings) => + describe(name, () => { + let transpileResult: ts.TranspileOutput; + let oldTranspileResult: string; + let oldTranspileDiagnostics: ts.Diagnostic[]; + + const transpileOptions: ts.TranspileOptions = testSettings.options || {}; + if (!transpileOptions.compilerOptions) { + transpileOptions.compilerOptions = {}; + } + if (transpileOptions.compilerOptions.target === undefined) { + transpileOptions.compilerOptions.target = ts.ScriptTarget.ES3; } - } - - transpileOptions.reportDiagnostics = true; - const justName = "transpile/" + name.replace(/[^a-z0-9\-. ()=]/ig, "") + (transpileOptions.compilerOptions.jsx ? ts.Extension.Tsx : ts.Extension.Ts); - const toBeCompiled = [{ - unitName, - content: input - }]; - const canUseOldTranspile = !transpileOptions.renamedDependencies; + if (transpileOptions.compilerOptions.newLine === undefined) { + // use \r\n as default new line + transpileOptions.compilerOptions.newLine = ts.NewLineKind.CarriageReturnLineFeed; + } - before(() => { - transpileResult = ts.transpileModule(input, transpileOptions); + transpileOptions.compilerOptions.sourceMap = true; - if (canUseOldTranspile) { - oldTranspileDiagnostics = []; - oldTranspileResult = ts.transpile(input, transpileOptions.compilerOptions, transpileOptions.fileName, oldTranspileDiagnostics, transpileOptions.moduleName); + let unitName = transpileOptions.fileName; + if (!unitName) { + unitName = transpileOptions.compilerOptions.jsx ? "file.tsx" : "file.ts"; + if (!testSettings.noSetFileName) { + transpileOptions.fileName = unitName; + } } - }); - after(() => { - transpileResult = undefined!; - oldTranspileResult = undefined!; - oldTranspileDiagnostics = undefined!; - }); + transpileOptions.reportDiagnostics = true; - /* eslint-disable no-null/no-null */ - it("Correct errors for " + justName, () => { - Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".errors.txt"), - transpileResult.diagnostics!.length === 0 ? null : Harness.Compiler.getErrorBaseline(toBeCompiled, transpileResult.diagnostics!)); - }); + const justName = "transpile/" + name.replace(/[^a-z0-9\-. ()=]/ig, "") + (transpileOptions.compilerOptions.jsx ? ts.Extension.Tsx : ts.Extension.Ts); + const toBeCompiled = [{ + unitName, + content: input, + }]; + const canUseOldTranspile = !transpileOptions.renamedDependencies; + + before(() => { + transpileResult = ts.transpileModule(input, transpileOptions); - if (canUseOldTranspile) { - it("Correct errors (old transpile) for " + justName, () => { - Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".oldTranspile.errors.txt"), - oldTranspileDiagnostics.length === 0 ? null : Harness.Compiler.getErrorBaseline(toBeCompiled, oldTranspileDiagnostics)); + if (canUseOldTranspile) { + oldTranspileDiagnostics = []; + oldTranspileResult = ts.transpile(input, transpileOptions.compilerOptions, transpileOptions.fileName, oldTranspileDiagnostics, transpileOptions.moduleName); + } }); - } - /* eslint-enable no-null/no-null */ - it("Correct output for " + justName, () => { - Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ts.Extension.Js), transpileResult.outputText); - }); + after(() => { + transpileResult = undefined!; + oldTranspileResult = undefined!; + oldTranspileDiagnostics = undefined!; + }); - if (canUseOldTranspile) { - it("Correct output (old transpile) for " + justName, () => { - Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".oldTranspile.js"), oldTranspileResult); + /* eslint-disable no-null/no-null */ + it("Correct errors for " + justName, () => { + Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".errors.txt"), transpileResult.diagnostics!.length === 0 ? null : Harness.Compiler.getErrorBaseline(toBeCompiled, transpileResult.diagnostics!)); }); - } - }); + + if (canUseOldTranspile) { + it("Correct errors (old transpile) for " + justName, () => { + Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".oldTranspile.errors.txt"), oldTranspileDiagnostics.length === 0 ? null : Harness.Compiler.getErrorBaseline(toBeCompiled, oldTranspileDiagnostics)); + }); + } + /* eslint-enable no-null/no-null */ + + it("Correct output for " + justName, () => { + Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ts.Extension.Js), transpileResult.outputText); + }); + + if (canUseOldTranspile) { + it("Correct output (old transpile) for " + justName, () => { + Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".oldTranspile.js"), oldTranspileResult); + }); + } + }); if (testSettings.testVerbatimModuleSyntax !== "only") { runOnce(nameIn, testSettings); @@ -97,92 +95,107 @@ describe("unittests:: services:: Transpile", () => { ...testSettings.options, compilerOptions: { ...testSettings.options?.compilerOptions, - verbatimModuleSyntax: true - } - } + verbatimModuleSyntax: true, + }, + }, }); } } transpilesCorrectly("Generates no diagnostics with valid inputs", `var x = 0;`, { options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); - transpilesCorrectly("Generates no diagnostics for missing file references", `/// -var x = 0;`, { - options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: true - }); + transpilesCorrectly( + "Generates no diagnostics for missing file references", + `/// +var x = 0;`, + { + options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, + testVerbatimModuleSyntax: true, + }, + ); transpilesCorrectly("Generates no diagnostics for missing module imports", `import {a} from "module2";`, { options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Generates expected syntactic diagnostics", `a b`, { options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Does not generate semantic diagnostics", `var x: string = 0;`, { options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Generates module output", `var x = 0; export {};`, { - options: { compilerOptions: { module: ts.ModuleKind.AMD } } + options: { compilerOptions: { module: ts.ModuleKind.AMD } }, }); transpilesCorrectly("Uses correct newLine character", `var x = 0;`, { options: { compilerOptions: { module: ts.ModuleKind.CommonJS, newLine: ts.NewLineKind.LineFeed } }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Sets module name", "var x = 1; export {};", { - options: { compilerOptions: { module: ts.ModuleKind.System, newLine: ts.NewLineKind.LineFeed }, moduleName: "NamedModule" } + options: { compilerOptions: { module: ts.ModuleKind.System, newLine: ts.NewLineKind.LineFeed }, moduleName: "NamedModule" }, }); transpilesCorrectly("No extra errors for file without extension", `"use strict";\r\nvar x = 0;`, { options: { compilerOptions: { module: ts.ModuleKind.CommonJS }, fileName: "file" }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); - transpilesCorrectly("Rename dependencies - System", + transpilesCorrectly( + "Rename dependencies - System", `import {foo} from "SomeName";\n` + - `declare function use(a: any);\n` + - `use(foo);`, { - options: { compilerOptions: { module: ts.ModuleKind.System, newLine: ts.NewLineKind.LineFeed }, renamedDependencies: { SomeName: "SomeOtherName" } } - }); + `declare function use(a: any);\n` + + `use(foo);`, + { + options: { compilerOptions: { module: ts.ModuleKind.System, newLine: ts.NewLineKind.LineFeed }, renamedDependencies: { SomeName: "SomeOtherName" } }, + }, + ); - transpilesCorrectly("Rename dependencies - AMD", + transpilesCorrectly( + "Rename dependencies - AMD", `import {foo} from "SomeName";\n` + - `declare function use(a: any);\n` + - `use(foo);`, { - options: { compilerOptions: { module: ts.ModuleKind.AMD, newLine: ts.NewLineKind.LineFeed }, renamedDependencies: { SomeName: "SomeOtherName" } } - }); + `declare function use(a: any);\n` + + `use(foo);`, + { + options: { compilerOptions: { module: ts.ModuleKind.AMD, newLine: ts.NewLineKind.LineFeed }, renamedDependencies: { SomeName: "SomeOtherName" } }, + }, + ); - transpilesCorrectly("Rename dependencies - UMD", + transpilesCorrectly( + "Rename dependencies - UMD", `import {foo} from "SomeName";\n` + - `declare function use(a: any);\n` + - `use(foo);`, { - options: { compilerOptions: { module: ts.ModuleKind.UMD, newLine: ts.NewLineKind.LineFeed }, renamedDependencies: { SomeName: "SomeOtherName" } } - }); + `declare function use(a: any);\n` + + `use(foo);`, + { + options: { compilerOptions: { module: ts.ModuleKind.UMD, newLine: ts.NewLineKind.LineFeed }, renamedDependencies: { SomeName: "SomeOtherName" } }, + }, + ); - transpilesCorrectly("Transpile with emit decorators and emit metadata", + transpilesCorrectly( + "Transpile with emit decorators and emit metadata", `import {db} from './db';\n` + - `function someDecorator(target) {\n` + - ` return target;\n` + - `} \n` + - `@someDecorator\n` + - `class MyClass {\n` + - ` db: db;\n` + - ` constructor(db: db) {\n` + - ` this.db = db;\n` + - ` this.db.doSomething(); \n` + - ` }\n` + - `}\n` + - `export {MyClass}; \n`, { + `function someDecorator(target) {\n` + + ` return target;\n` + + `} \n` + + `@someDecorator\n` + + `class MyClass {\n` + + ` db: db;\n` + + ` constructor(db: db) {\n` + + ` this.db = db;\n` + + ` this.db.doSomething(); \n` + + ` }\n` + + `}\n` + + `export {MyClass}; \n`, + { options: { compilerOptions: { module: ts.ModuleKind.CommonJS, @@ -191,25 +204,26 @@ var x = 0;`, { emitDecoratorMetadata: true, experimentalDecorators: true, target: ts.ScriptTarget.ES5, - } + }, }, - testVerbatimModuleSyntax: true - }); + testVerbatimModuleSyntax: true, + }, + ); transpilesCorrectly("Supports backslashes in file name", "var x", { - options: { fileName: "a\\b.ts" } + options: { fileName: "a\\b.ts" }, }); transpilesCorrectly("transpile file as 'tsx' if 'jsx' is specified", `var x =
`, { - options: { compilerOptions: { jsx: ts.JsxEmit.React, newLine: ts.NewLineKind.LineFeed } } + options: { compilerOptions: { jsx: ts.JsxEmit.React, newLine: ts.NewLineKind.LineFeed } }, }); transpilesCorrectly("transpile .js files", "const a = 10;", { - options: { compilerOptions: { newLine: ts.NewLineKind.LineFeed, module: ts.ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { newLine: ts.NewLineKind.LineFeed, module: ts.ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true }, }); transpilesCorrectly("Supports urls in file name", "var x", { - options: { fileName: "http://somewhere/directory//directory2/file.ts" } + options: { fileName: "http://somewhere/directory//directory2/file.ts" }, }); transpilesCorrectly("Accepts string as enum values for compile-options", "export const x = 0", { @@ -217,310 +231,312 @@ var x = 0;`, { compilerOptions: { module: "es6" as any as ts.ModuleKind, // Capitalization and spaces ignored - target: " Es6 " as any as ts.ScriptTarget - } - } + target: " Es6 " as any as ts.ScriptTarget, + }, + }, }); transpilesCorrectly("Report an error when compiler-options module-kind is out-of-range", "", { - options: { compilerOptions: { module: 123 as any as ts.ModuleKind } } + options: { compilerOptions: { module: 123 as any as ts.ModuleKind } }, }); transpilesCorrectly("Report an error when compiler-options target-script is out-of-range", "", { - options: { compilerOptions: { module: 123 as any as ts.ModuleKind } } + options: { compilerOptions: { module: 123 as any as ts.ModuleKind } }, }); transpilesCorrectly("Support options with lib values", "const a = 10;", { options: { compilerOptions: { lib: ["es6", "dom"], module: ts.ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Support options with types values", "const a = 10;", { options: { compilerOptions: { types: ["jquery", "typescript"], module: ts.ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'allowJs'", "x;", { options: { compilerOptions: { allowJs: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'allowSyntheticDefaultImports'", "x;", { options: { compilerOptions: { allowSyntheticDefaultImports: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'allowUnreachableCode'", "x;", { options: { compilerOptions: { allowUnreachableCode: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'allowUnusedLabels'", "x;", { options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'alwaysStrict'", "x;", { options: { compilerOptions: { alwaysStrict: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'baseUrl'", "x;", { options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'charset'", "x;", { options: { compilerOptions: { charset: "en-us" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'declaration'", "x;", { options: { compilerOptions: { declaration: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'declarationDir'", "x;", { options: { compilerOptions: { declarationDir: "out/declarations" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'emitBOM'", "x;", { options: { compilerOptions: { emitBOM: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'emitDecoratorMetadata'", "x;", { options: { compilerOptions: { emitDecoratorMetadata: true, experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'experimentalDecorators'", "x;", { options: { compilerOptions: { experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'forceConsistentCasingInFileNames'", "x;", { options: { compilerOptions: { forceConsistentCasingInFileNames: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'isolatedModules'", "x;", { - options: { compilerOptions: { isolatedModules: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { isolatedModules: true }, fileName: "input.js", reportDiagnostics: true }, }); transpilesCorrectly("Does not support setting 'isolatedModules'", "x;", { options: { compilerOptions: { isolatedModules: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: "only" + testVerbatimModuleSyntax: "only", }); transpilesCorrectly("Supports setting 'jsx'", "x;", { options: { compilerOptions: { jsx: 1 }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'lib'", "x;", { options: { compilerOptions: { lib: ["es2015", "dom"] }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'locale'", "x;", { options: { compilerOptions: { locale: "en-us" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'module'", "x;", { options: { compilerOptions: { module: ts.ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'moduleResolution'", "x;", { options: { compilerOptions: { moduleResolution: ts.ModuleResolutionKind.Node10 }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'newLine'", "x;", { options: { compilerOptions: { newLine: ts.NewLineKind.CarriageReturnLineFeed }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noEmit'", "x;", { options: { compilerOptions: { noEmit: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noEmitHelpers'", "x;", { options: { compilerOptions: { noEmitHelpers: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noEmitOnError'", "x;", { options: { compilerOptions: { noEmitOnError: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noErrorTruncation'", "x;", { options: { compilerOptions: { noErrorTruncation: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noFallthroughCasesInSwitch'", "x;", { options: { compilerOptions: { noFallthroughCasesInSwitch: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noImplicitAny'", "x;", { options: { compilerOptions: { noImplicitAny: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noImplicitReturns'", "x;", { options: { compilerOptions: { noImplicitReturns: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noImplicitThis'", "x;", { options: { compilerOptions: { noImplicitThis: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noImplicitUseStrict'", "x;", { options: { compilerOptions: { noImplicitUseStrict: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noLib'", "x;", { options: { compilerOptions: { noLib: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'noResolve'", "x;", { options: { compilerOptions: { noResolve: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'out'", "x;", { options: { compilerOptions: { out: "./out" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'outDir'", "x;", { options: { compilerOptions: { outDir: "./outDir" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'outFile'", "x;", { options: { compilerOptions: { outFile: "./outFile" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'paths'", "x;", { options: { compilerOptions: { paths: { "*": ["./generated*"] } }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'preserveConstEnums'", "x;", { options: { compilerOptions: { preserveConstEnums: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'reactNamespace'", "x;", { options: { compilerOptions: { reactNamespace: "react" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'jsxFactory'", "x;", { options: { compilerOptions: { jsxFactory: "createElement" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'jsxFragmentFactory'", "x;", { options: { compilerOptions: { jsxFactory: "x", jsxFragmentFactory: "frag" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'removeComments'", "x;", { options: { compilerOptions: { removeComments: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'rootDir'", "x;", { options: { compilerOptions: { rootDir: "./rootDir" }, fileName: "./rootDir/input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'rootDirs'", "x;", { options: { compilerOptions: { rootDirs: ["./a", "./b"] }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'skipLibCheck'", "x;", { options: { compilerOptions: { skipLibCheck: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'skipDefaultLibCheck'", "x;", { options: { compilerOptions: { skipDefaultLibCheck: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'strictNullChecks'", "x;", { options: { compilerOptions: { strictNullChecks: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'stripInternal'", "x;", { options: { compilerOptions: { stripInternal: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'suppressExcessPropertyErrors'", "x;", { options: { compilerOptions: { suppressExcessPropertyErrors: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'suppressImplicitAnyIndexErrors'", "x;", { options: { compilerOptions: { suppressImplicitAnyIndexErrors: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'target'", "x;", { options: { compilerOptions: { target: 2 }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'types'", "x;", { options: { compilerOptions: { types: ["jquery", "jasmine"] }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'typeRoots'", "x;", { options: { compilerOptions: { typeRoots: ["./folder"] }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'incremental'", "x;", { options: { compilerOptions: { incremental: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'composite'", "x;", { options: { compilerOptions: { composite: true }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports setting 'tsbuildinfo'", "x;", { options: { compilerOptions: { incremental: true, tsBuildInfoFile: "./folder/config.tsbuildinfo" }, fileName: "input.js", reportDiagnostics: true }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); - transpilesCorrectly("Correctly serialize metadata when transpile with CommonJS option", + transpilesCorrectly( + "Correctly serialize metadata when transpile with CommonJS option", `import * as ng from "angular2/core";` + - `declare function foo(...args: any[]);` + - `@foo` + - `export class MyClass1 {` + - ` constructor(private _elementRef: ng.ElementRef){}` + - `}`, { + `declare function foo(...args: any[]);` + + `@foo` + + `export class MyClass1 {` + + ` constructor(private _elementRef: ng.ElementRef){}` + + `}`, + { options: { compilerOptions: { target: ts.ScriptTarget.ES5, @@ -528,19 +544,21 @@ var x = 0;`, { moduleResolution: ts.ModuleResolutionKind.Node10, emitDecoratorMetadata: true, experimentalDecorators: true, - } + }, }, - testVerbatimModuleSyntax: true - } + testVerbatimModuleSyntax: true, + }, ); - transpilesCorrectly("Correctly serialize metadata when transpile with System option", + transpilesCorrectly( + "Correctly serialize metadata when transpile with System option", `import * as ng from "angular2/core";` + - `declare function foo(...args: any[]);` + - `@foo` + - `export class MyClass1 {` + - ` constructor(private _elementRef: ng.ElementRef){}` + - `}`, { + `declare function foo(...args: any[]);` + + `@foo` + + `export class MyClass1 {` + + ` constructor(private _elementRef: ng.ElementRef){}` + + `}`, + { options: { compilerOptions: { target: ts.ScriptTarget.ES5, @@ -548,88 +566,100 @@ var x = 0;`, { moduleResolution: ts.ModuleResolutionKind.Node10, emitDecoratorMetadata: true, experimentalDecorators: true, - isolatedModules: true - } - } - } + isolatedModules: true, + }, + }, + }, ); transpilesCorrectly("Supports readonly keyword for arrays", "let x: readonly string[];", { options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Supports 'as const' arrays", `([] as const).forEach(k => console.log(k));`, { options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); transpilesCorrectly("Infer correct file extension", `const fn = (a: T) => a`, { noSetFileName: true, - testVerbatimModuleSyntax: true + testVerbatimModuleSyntax: true, }); - transpilesCorrectly("Export star as ns conflict does not crash", ` + transpilesCorrectly( + "Export star as ns conflict does not crash", + ` var a; export { a as alias }; -export * as alias from './file';`, { - noSetFileName: true, - testVerbatimModuleSyntax: true - }); +export * as alias from './file';`, + { + noSetFileName: true, + testVerbatimModuleSyntax: true, + }, + ); - transpilesCorrectly("Elides import equals referenced only by export type", + transpilesCorrectly( + "Elides import equals referenced only by export type", `import IFoo = Namespace.IFoo;` + - `export type { IFoo };`, { - options: { compilerOptions: { module: ts.ModuleKind.CommonJS } } - } + `export type { IFoo };`, + { + options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, + }, ); - transpilesCorrectly("Does not elide import equals referenced only by export type", + transpilesCorrectly( + "Does not elide import equals referenced only by export type", `import IFoo = Namespace.IFoo;` + - `export type { IFoo };`, { + `export type { IFoo };`, + { options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: "only" - } + testVerbatimModuleSyntax: "only", + }, ); - transpilesCorrectly("Elides import equals referenced only by type only export specifier", + transpilesCorrectly( + "Elides import equals referenced only by type only export specifier", `import IFoo = Namespace.IFoo;` + - `export { type IFoo };`, { - options: { compilerOptions: { module: ts.ModuleKind.CommonJS } } - } + `export { type IFoo };`, + { + options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, + }, ); - transpilesCorrectly("Does not elide import equals referenced only by type only export specifier", + transpilesCorrectly( + "Does not elide import equals referenced only by type only export specifier", `import IFoo = Namespace.IFoo;` + - `export { type IFoo };`, { + `export { type IFoo };`, + { options: { compilerOptions: { module: ts.ModuleKind.CommonJS } }, - testVerbatimModuleSyntax: "only" - } + testVerbatimModuleSyntax: "only", + }, ); - transpilesCorrectly("Can transpile .ts extensions without error", - `import { foo } from "./foo.ts";`, { - options: { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ESNext } }, - testVerbatimModuleSyntax: true - } - ); + transpilesCorrectly("Can transpile .ts extensions without error", `import { foo } from "./foo.ts";`, { + options: { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ESNext } }, + testVerbatimModuleSyntax: true, + }); - transpilesCorrectly("Ignores `allowImportingTsExtensions` without `noEmit` error", - `import { foo } from "./foo.ts";`, { - options: { compilerOptions: { module: ts.ModuleKind.ESNext, allowImportingTsExtensions: true, target: ts.ScriptTarget.ESNext } }, - testVerbatimModuleSyntax: true - } - ); + transpilesCorrectly("Ignores `allowImportingTsExtensions` without `noEmit` error", `import { foo } from "./foo.ts";`, { + options: { compilerOptions: { module: ts.ModuleKind.ESNext, allowImportingTsExtensions: true, target: ts.ScriptTarget.ESNext } }, + testVerbatimModuleSyntax: true, + }); - transpilesCorrectly("Preserves exported const merged with type-only import", ` + transpilesCorrectly( + "Preserves exported const merged with type-only import", + ` import fooValue from "./values"; import type {Foo} from "./types"; const Foo: Foo = fooValue as any as Foo; export {Foo}; - `, { - options: { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ESNext } }, - testVerbatimModuleSyntax: true - }); + `, + { + options: { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ESNext } }, + testVerbatimModuleSyntax: true, + }, + ); }); diff --git a/src/testRunner/unittests/services/utilities.ts b/src/testRunner/unittests/services/utilities.ts index 72c7a7e61af22..91b82462b479e 100644 --- a/src/testRunner/unittests/services/utilities.ts +++ b/src/testRunner/unittests/services/utilities.ts @@ -3,12 +3,17 @@ import * as ts from "../../_namespaces/ts"; describe("unittests:: services:: utilities", () => { describe("Test findPrecedingMatchingToken,", () => { it("should not infinite loop finding opening brace", () => { - const sourceFile = ts.createSourceFile("file.ts", `/// + const sourceFile = ts.createSourceFile( + "file.ts", + `/// (/** @window => { /** @type {Abcd123} */ const core = window.Abcd.core; -})();`, ts.ScriptTarget.ESNext, /*setParentNodes*/ true); +})();`, + ts.ScriptTarget.ESNext, + /*setParentNodes*/ true, + ); // can't use ts.getTokenAtPosition because it returns back the wrong token const param = ts.forEachChildRecursively(sourceFile, node => node.kind === ts.SyntaxKind.Parameter ? node : undefined)!; const jsDoc = param.getChildren()[0]; diff --git a/src/testRunner/unittests/transform.ts b/src/testRunner/unittests/transform.ts index aa277bd21f536..766a1d9f8ec9a 100644 --- a/src/testRunner/unittests/transform.ts +++ b/src/testRunner/unittests/transform.ts @@ -3,7 +3,11 @@ import * as evaluator from "../_namespaces/evaluator"; import * as fakes from "../_namespaces/fakes"; import * as Harness from "../_namespaces/Harness"; import * as ts from "../_namespaces/ts"; -import { NewLineKind, ScriptTarget, transpileModule } from "../_namespaces/ts"; +import { + NewLineKind, + ScriptTarget, + transpileModule, +} from "../_namespaces/ts"; import * as vfs from "../_namespaces/vfs"; describe("unittests:: TransformAPI", () => { @@ -17,8 +21,12 @@ describe("unittests:: TransformAPI", () => { ts.addSyntheticTrailingComment( ts.setTextRange( ts.factory.createVoidZero(), - node), - ts.SyntaxKind.MultiLineCommentTrivia, "undefined")); + node, + ), + ts.SyntaxKind.MultiLineCommentTrivia, + "undefined", + ), + ); } return node; }; @@ -58,20 +66,23 @@ describe("unittests:: TransformAPI", () => { } function createTaggedTemplateLiteral(): ts.Transformer { - return sourceFile => ts.factory.updateSourceFile(sourceFile, [ - ts.factory.createExpressionStatement( - ts.factory.createTaggedTemplateExpression( - ts.factory.createIdentifier("$tpl"), - /*typeArguments*/ undefined, - ts.factory.createNoSubstitutionTemplateLiteral("foo", "foo"))) - ]); + return sourceFile => + ts.factory.updateSourceFile(sourceFile, [ + ts.factory.createExpressionStatement( + ts.factory.createTaggedTemplateExpression( + ts.factory.createIdentifier("$tpl"), + /*typeArguments*/ undefined, + ts.factory.createNoSubstitutionTemplateLiteral("foo", "foo"), + ), + ), + ]); } function transformSourceFile(sourceText: string, transformers: ts.TransformerFactory[]) { const transformed = ts.transform(ts.createSourceFile("source.ts", sourceText, ts.ScriptTarget.ES2015), transformers); const printer = ts.createPrinter({ newLine: ts.NewLineKind.CarriageReturnLineFeed }, { onEmitNode: transformed.emitNodeWithNotification, - substituteNode: transformed.substituteNode + substituteNode: transformed.substituteNode, }); const result = printer.printBundle(ts.factory.createBundle(transformed.transformed)); transformed.dispose(); @@ -108,20 +119,22 @@ describe("unittests:: TransformAPI", () => { testBaseline("types", () => { return transformSourceFile(`let a: () => void`, [ - context => file => ts.visitNode(file, function visitor(node: ts.Node): ts.VisitResult { - return ts.visitEachChild(node, visitor, context); - }, ts.isSourceFile) + context => file => + ts.visitNode(file, function visitor(node: ts.Node): ts.VisitResult { + return ts.visitEachChild(node, visitor, context); + }, ts.isSourceFile), ]); }); testBaseline("transformDefiniteAssignmentAssertions", () => { return transformSourceFile(`let a!: () => void`, [ - context => file => ts.visitNode(file, function visitor(node: ts.Node): ts.VisitResult { - if (node.kind === ts.SyntaxKind.VoidKeyword) { - return ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword); - } - return ts.visitEachChild(node, visitor, context); - }, ts.isSourceFile) + context => file => + ts.visitNode(file, function visitor(node: ts.Node): ts.VisitResult { + if (node.kind === ts.SyntaxKind.VoidKeyword) { + return ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword); + } + return ts.visitEachChild(node, visitor, context); + }, ts.isSourceFile), ]); }); @@ -129,11 +142,11 @@ describe("unittests:: TransformAPI", () => { return ts.transpileModule(`var oldName = undefined;`, { transformers: { before: [replaceUndefinedWithVoid0], - after: [replaceIdentifiersNamedOldNameWithNewName] + after: [replaceIdentifiersNamedOldNameWithNewName], }, compilerOptions: { - newLine: ts.NewLineKind.CarriageReturnLineFeed - } + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }).outputText; }); @@ -144,41 +157,47 @@ describe("unittests:: TransformAPI", () => { }, compilerOptions: { target: ts.ScriptTarget.ES5, - newLine: ts.NewLineKind.CarriageReturnLineFeed - } + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }).outputText; }); testBaseline("issue27854", () => { return ts.transpileModule(`oldName<{ a: string; }>\` ... \`;`, { transformers: { - before: [replaceIdentifiersNamedOldNameWithNewName2] + before: [replaceIdentifiersNamedOldNameWithNewName2], }, compilerOptions: { newLine: ts.NewLineKind.CarriageReturnLineFeed, - target: ts.ScriptTarget.Latest - } + target: ts.ScriptTarget.Latest, + }, }).outputText; }); testBaseline("issue44068", () => { - return transformSourceFile(` + return transformSourceFile( + ` const FirstVar = null; const SecondVar = null; - `, [ - context => file => { - const firstVarName = (file.statements[0] as ts.VariableStatement) - .declarationList.declarations[0].name as ts.Identifier; - const secondVarName = (file.statements[0] as ts.VariableStatement) - .declarationList.declarations[0].name as ts.Identifier; - - return context.factory.updateSourceFile(file, file.statements.concat([ - context.factory.createExpressionStatement( - context.factory.createArrayLiteralExpression([firstVarName, secondVarName]) - ), - ])); - } - ]); + `, + [ + context => file => { + const firstVarName = (file.statements[0] as ts.VariableStatement) + .declarationList.declarations[0].name as ts.Identifier; + const secondVarName = (file.statements[0] as ts.VariableStatement) + .declarationList.declarations[0].name as ts.Identifier; + + return context.factory.updateSourceFile( + file, + file.statements.concat([ + context.factory.createExpressionStatement( + context.factory.createArrayLiteralExpression([firstVarName, secondVarName]), + ), + ]), + ); + }, + ], + ); }); testBaseline("rewrittenNamespace", () => { @@ -188,38 +207,44 @@ describe("unittests:: TransformAPI", () => { }, compilerOptions: { newLine: ts.NewLineKind.CarriageReturnLineFeed, - } + }, }).outputText; }); testBaseline("rewrittenNamespaceFollowingClass", () => { - return ts.transpileModule(` + return ts.transpileModule( + ` class C { foo = 10; static bar = 20 } namespace C { export let x = 10; } - `, { - transformers: { - before: [forceNamespaceRewrite], + `, + { + transformers: { + before: [forceNamespaceRewrite], + }, + compilerOptions: { + target: ts.ScriptTarget.ESNext, + newLine: ts.NewLineKind.CarriageReturnLineFeed, + useDefineForClassFields: false, + }, }, - compilerOptions: { - target: ts.ScriptTarget.ESNext, - newLine: ts.NewLineKind.CarriageReturnLineFeed, - useDefineForClassFields: false, - } - }).outputText; + ).outputText; }); testBaseline("transformTypesInExportDefault", () => { - return ts.transpileModule(` + return ts.transpileModule( + ` export default (foo: string) => { return 1; } - `, { - transformers: { - before: [replaceNumberWith2], + `, + { + transformers: { + before: [replaceNumberWith2], + }, + compilerOptions: { + target: ts.ScriptTarget.ESNext, + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ts.ScriptTarget.ESNext, - newLine: ts.NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); testBaseline("synthesizedClassAndNamespaceCombination", () => { @@ -230,7 +255,7 @@ describe("unittests:: TransformAPI", () => { compilerOptions: { target: ts.ScriptTarget.ESNext, newLine: ts.NewLineKind.CarriageReturnLineFeed, - } + }, }).outputText; function replaceWithClassAndNamespace() { @@ -240,8 +265,8 @@ describe("unittests:: TransformAPI", () => { sourceFile, ts.factory.createNodeArray([ ts.factory.createClassDeclaration(/*modifiers*/ undefined, "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, /*members*/ undefined!), // TODO: GH#18217 - ts.factory.createModuleDeclaration(/*modifiers*/ undefined, ts.factory.createIdentifier("Foo"), ts.factory.createModuleBlock([ts.factory.createEmptyStatement()])) - ]) + ts.factory.createModuleDeclaration(/*modifiers*/ undefined, ts.factory.createIdentifier("Foo"), ts.factory.createModuleBlock([ts.factory.createEmptyStatement()])), + ]), ); return result; }; @@ -271,7 +296,7 @@ describe("unittests:: TransformAPI", () => { compilerOptions: { target: ts.ScriptTarget.ESNext, newLine: ts.NewLineKind.CarriageReturnLineFeed, - } + }, }).outputText; function expandExportStar(context: ts.TransformationContext) { @@ -305,7 +330,7 @@ describe("unittests:: TransformAPI", () => { module: ts.ModuleKind.System, newLine: ts.NewLineKind.CarriageReturnLineFeed, moduleDetection: ts.ModuleDetectionKind.Force, - } + }, }).outputText; function transformAddImportStar(_context: ts.TransformationContext) { @@ -319,10 +344,11 @@ describe("unittests:: TransformAPI", () => { /*importClause*/ ts.factory.createImportClause( /*isTypeOnly*/ false, /*name*/ undefined, - ts.factory.createNamespaceImport(ts.factory.createIdentifier("i0")) + ts.factory.createNamespaceImport(ts.factory.createIdentifier("i0")), ), /*moduleSpecifier*/ ts.factory.createStringLiteral("./comp1"), - /*assertClause*/ undefined); + /*assertClause*/ undefined, + ); return ts.factory.updateSourceFile(sf, [importStar]); } } @@ -338,7 +364,7 @@ describe("unittests:: TransformAPI", () => { target: ScriptTarget.ES5, experimentalDecorators: true, newLine: NewLineKind.CarriageReturnLineFeed, - } + }, }).outputText; function transformAddDecoratedNode(_context: ts.TransformationContext) { @@ -348,7 +374,7 @@ describe("unittests:: TransformAPI", () => { function visitNode(sf: ts.SourceFile) { // produce `class Foo { @Bar baz() {} }`; const classDecl = ts.factory.createClassDeclaration(/*modifiers*/ undefined, "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, [ - ts.factory.createMethodDeclaration([ts.factory.createDecorator(ts.factory.createIdentifier("Bar"))], /*asteriskToken*/ undefined, "baz", /*questionToken*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.factory.createBlock([])) + ts.factory.createMethodDeclaration([ts.factory.createDecorator(ts.factory.createIdentifier("Bar"))], /*asteriskToken*/ undefined, "baz", /*questionToken*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.factory.createBlock([])), ]); return ts.factory.updateSourceFile(sf, [classDecl]); } @@ -358,12 +384,12 @@ describe("unittests:: TransformAPI", () => { testBaseline("transformDeclarationFile", () => { return baselineDeclarationTransform(`var oldName = undefined;`, { transformers: { - afterDeclarations: [replaceIdentifiersNamedOldNameWithNewName] + afterDeclarations: [replaceIdentifiersNamedOldNameWithNewName], }, compilerOptions: { newLine: ts.NewLineKind.CarriageReturnLineFeed, - declaration: true - } + declaration: true, + }, }); }); @@ -377,7 +403,7 @@ describe("unittests:: TransformAPI", () => { target: ScriptTarget.ES5, newLine: NewLineKind.CarriageReturnLineFeed, experimentalDecorators: true, - } + }, }).outputText; function transformAddParameterProperty(_context: ts.TransformationContext) { @@ -389,7 +415,8 @@ describe("unittests:: TransformAPI", () => { // The decorator is required to trigger ts.ts transformations. const classDecl = ts.factory.createClassDeclaration([], "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, [ ts.factory.createConstructorDeclaration(/*modifiers*/ undefined, [ - ts.factory.createParameterDeclaration([ts.factory.createDecorator(ts.factory.createIdentifier("Dec")), ts.factory.createModifier(ts.SyntaxKind.PrivateKeyword)], /*dotDotDotToken*/ undefined, "x")], ts.factory.createBlock([])) + ts.factory.createParameterDeclaration([ts.factory.createDecorator(ts.factory.createIdentifier("Dec")), ts.factory.createModifier(ts.SyntaxKind.PrivateKeyword)], /*dotDotDotToken*/ undefined, "x"), + ], ts.factory.createBlock([])), ]); return ts.factory.updateSourceFile(sf, [classDecl]); } @@ -421,38 +448,45 @@ describe("unittests:: TransformAPI", () => { // https://github.com/Microsoft/TypeScript/issues/24096 testBaseline("transformAddCommentToArrowReturnValue", () => { - return ts.transpileModule(`const foo = () => + return ts.transpileModule( + `const foo = () => void 0 -`, { - transformers: { - before: [addSyntheticComment(ts.isVoidExpression)], +`, + { + transformers: { + before: [addSyntheticComment(ts.isVoidExpression)], + }, + compilerOptions: { + target: ts.ScriptTarget.ES5, + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ts.ScriptTarget.ES5, - newLine: ts.NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); // https://github.com/Microsoft/TypeScript/issues/17594 testBaseline("transformAddCommentToExportedVar", () => { - return ts.transpileModule(`export const exportedDirectly = 1; + return ts.transpileModule( + `export const exportedDirectly = 1; const exportedSeparately = 2; export {exportedSeparately}; -`, { - transformers: { - before: [addSyntheticComment(ts.isVariableStatement)], +`, + { + transformers: { + before: [addSyntheticComment(ts.isVariableStatement)], + }, + compilerOptions: { + target: ts.ScriptTarget.ES5, + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ts.ScriptTarget.ES5, - newLine: ts.NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); // https://github.com/Microsoft/TypeScript/issues/17594 testBaseline("transformAddCommentToImport", () => { - return ts.transpileModule(` + return ts.transpileModule( + ` // Previous comment on import. import {Value} from 'somewhere'; import * as X from 'somewhere'; @@ -460,20 +494,23 @@ import * as X from 'somewhere'; export { /* specifier comment */ X, Y} from 'somewhere'; export * from 'somewhere'; export {Value}; -`, { - transformers: { - before: [addSyntheticComment(n => ts.isImportDeclaration(n) || ts.isExportDeclaration(n) || ts.isImportSpecifier(n) || ts.isExportSpecifier(n))], +`, + { + transformers: { + before: [addSyntheticComment(n => ts.isImportDeclaration(n) || ts.isExportDeclaration(n) || ts.isImportSpecifier(n) || ts.isExportSpecifier(n))], + }, + compilerOptions: { + target: ts.ScriptTarget.ES5, + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ts.ScriptTarget.ES5, - newLine: ts.NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); // https://github.com/Microsoft/TypeScript/issues/17594 testBaseline("transformAddCommentToProperties", () => { - return ts.transpileModule(` + return ts.transpileModule( + ` // class comment. class Clazz { // original comment 1. @@ -483,19 +520,22 @@ class Clazz { // original comment 3. constructor(readonly field = 1) {} } -`, { - transformers: { - before: [addSyntheticComment(n => ts.isPropertyDeclaration(n) || ts.isParameterPropertyDeclaration(n, n.parent) || ts.isClassDeclaration(n) || ts.isConstructorDeclaration(n))], +`, + { + transformers: { + before: [addSyntheticComment(n => ts.isPropertyDeclaration(n) || ts.isParameterPropertyDeclaration(n, n.parent) || ts.isClassDeclaration(n) || ts.isConstructorDeclaration(n))], + }, + compilerOptions: { + target: ts.ScriptTarget.ES2015, + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ts.ScriptTarget.ES2015, - newLine: ts.NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); testBaseline("transformAddCommentToNamespace", () => { - return ts.transpileModule(` + return ts.transpileModule( + ` // namespace comment. namespace Foo { export const x = 1; @@ -504,43 +544,48 @@ namespace Foo { namespace Foo { export const y = 1; } -`, { - transformers: { - before: [addSyntheticComment(n => ts.isModuleDeclaration(n))], +`, + { + transformers: { + before: [addSyntheticComment(n => ts.isModuleDeclaration(n))], + }, + compilerOptions: { + target: ts.ScriptTarget.ES2015, + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ts.ScriptTarget.ES2015, - newLine: ts.NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); testBaseline("transformUpdateModuleMember", () => { - return ts.transpileModule(` + return ts.transpileModule( + ` module MyModule { const myVariable = 1; function foo(param: string) {} } -`, { - transformers: { - before: [renameVariable], +`, + { + transformers: { + before: [renameVariable], + }, + compilerOptions: { + target: ts.ScriptTarget.ES2015, + newLine: ts.NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ts.ScriptTarget.ES2015, - newLine: ts.NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; function renameVariable(context: ts.TransformationContext) { - return (sourceFile: ts.SourceFile): ts.SourceFile => { - return ts.visitNode(sourceFile, rootTransform, ts.isSourceFile); - }; - function rootTransform(node: T): ts.Node { - if (ts.isVariableDeclaration(node)) { - return ts.factory.updateVariableDeclaration(node, ts.factory.createIdentifier("newName"), /*exclamationToken*/ undefined, /*type*/ undefined, node.initializer); - } - return ts.visitEachChild(node, rootTransform, context); + return (sourceFile: ts.SourceFile): ts.SourceFile => { + return ts.visitNode(sourceFile, rootTransform, ts.isSourceFile); + }; + function rootTransform(node: T): ts.Node { + if (ts.isVariableDeclaration(node)) { + return ts.factory.updateVariableDeclaration(node, ts.factory.createIdentifier("newName"), /*exclamationToken*/ undefined, /*type*/ undefined, node.initializer); } + return ts.visitEachChild(node, rootTransform, context); + } } }); @@ -555,7 +600,7 @@ module MyModule { const program = ts.createProgram(["source.ts"], { target: ts.ScriptTarget.ES3, module: ts.ModuleKind.None, - noLib: true + noLib: true, }, host); program.emit(transformedSourceFile, (_p, s, b) => host.writeFile("source.js", s, b)); return host.readFile("source.js")!.toString(); @@ -579,7 +624,6 @@ module MyModule { }; return (node: ts.SourceFile) => ts.visitNode(node, visitor, ts.isSourceFile); } - }); testBaselineAndEvaluate("templateSpans", () => { @@ -589,8 +633,8 @@ module MyModule { newLine: ts.NewLineKind.CarriageReturnLineFeed, }, transformers: { - before: [transformSourceFile] - } + before: [transformSourceFile], + }, }).outputText; function transformSourceFile(context: ts.TransformationContext): ts.Transformer { @@ -623,51 +667,59 @@ module MyModule { node.name, node.typeParameters, node.heritageClauses, - newMembers) : + newMembers, + ) : ts.factory.updateClassExpression( node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, - newMembers); + newMembers, + ); } return ts.visitEachChild(node, rootTransform, context); } } testBaseline("transformSyntheticCommentOnStaticFieldInClassDeclaration", () => { - return ts.transpileModule(` + return ts.transpileModule( + ` declare const Decorator: any; @Decorator class MyClass { } -`, { - transformers: { - before: [addStaticFieldWithComment], +`, + { + transformers: { + before: [addStaticFieldWithComment], + }, + compilerOptions: { + target: ScriptTarget.ES2015, + experimentalDecorators: true, + newLine: NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ScriptTarget.ES2015, - experimentalDecorators: true, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); testBaseline("transformSyntheticCommentOnStaticFieldInClassExpression", () => { - return ts.transpileModule(` + return ts.transpileModule( + ` const MyClass = class { }; -`, { - transformers: { - before: [addStaticFieldWithComment], +`, + { + transformers: { + before: [addStaticFieldWithComment], + }, + compilerOptions: { + target: ScriptTarget.ES2015, + experimentalDecorators: true, + newLine: NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - target: ScriptTarget.ES2015, - experimentalDecorators: true, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); testBaseline("jsxExpression", () => { @@ -678,23 +730,25 @@ const MyClass = class { return (node: ts.SourceFile) => ts.visitNode(node, visitor, ts.isSourceFile); } - return ts.transpileModule(` + return ts.transpileModule( + ` function test () { return <> {/* This comment breaks the transformer */} } -`, { - transformers: { - before: [doNothing], +`, + { + transformers: { + before: [doNothing], + }, + compilerOptions: { + jsx: ts.JsxEmit.React, + target: ScriptTarget.ES2015, + experimentalDecorators: true, + newLine: NewLineKind.CarriageReturnLineFeed, + }, }, - compilerOptions: { - jsx: ts.JsxEmit.React, - target: ScriptTarget.ES2015, - experimentalDecorators: true, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + ).outputText; }); }); - diff --git a/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts b/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts index 848b58933edef..cb1f7ba78a9a1 100644 --- a/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts +++ b/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts @@ -13,7 +13,7 @@ import { enableStrict, loadProjectFromDisk, removeRest, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => { @@ -34,7 +34,7 @@ describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => { function verifyOutFileScenario({ subScenario, modifyFs, - modifyAgainFs + modifyAgainFs, }: VerifyOutFileScenarioInput) { verifyTsc({ scenario: "amdModulesWithOut", @@ -46,13 +46,13 @@ describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => { edits: [ { caption: "incremental-declaration-doesnt-change", - edit: fs => appendText(fs, "/src/lib/file1.ts", "console.log(x);") + edit: fs => appendText(fs, "/src/lib/file1.ts", "console.log(x);"), }, ...(modifyAgainFs ? [{ caption: "incremental-headers-change-without-dts-changes", - edit: modifyAgainFs + edit: modifyAgainFs, }] : ts.emptyArray), - ] + ], }); } @@ -79,7 +79,7 @@ describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => { addTestPrologue(fs, "/src/app/file3.ts", `"myPrologue"`); addTestPrologue(fs, "/src/app/file4.ts", `"myPrologue2";`); }, - modifyAgainFs: fs => addTestPrologue(fs, "/src/lib/file1.ts", `"myPrologue5"`) + modifyAgainFs: fs => addTestPrologue(fs, "/src/lib/file1.ts", `"myPrologue5"`), }); }); @@ -106,7 +106,7 @@ describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => { addRest(fs, "app", "file3"); addSpread(fs, "app", "file4"); }, - modifyAgainFs: fs => removeRest(fs, "lib", "file1") + modifyAgainFs: fs => removeRest(fs, "lib", "file1"), }); }); @@ -118,17 +118,25 @@ describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => { modifyFs: fs => { addTripleSlashRef(fs, "lib", "file0"); addTripleSlashRef(fs, "app", "file4"); - } + }, }); }); describe("stripInternal", () => { function stripInternalScenario(fs: vfs.FileSystem) { const internal = "/*@internal*/"; - replaceText(fs, "/src/app/tsconfig.json", `"composite": true,`, `"composite": true, -"stripInternal": true,`); + replaceText( + fs, + "/src/app/tsconfig.json", + `"composite": true,`, + `"composite": true, +"stripInternal": true,`, + ); replaceText(fs, "/src/lib/file0.ts", "const", `${internal} const`); - appendText(fs, "/src/lib/file1.ts", ` + appendText( + fs, + "/src/lib/file1.ts", + ` export class normalC { ${internal} constructor() { } ${internal} prop: string; @@ -153,7 +161,8 @@ ${internal} export namespace internalOther.something { export class someClass {} ${internal} export import internalImport = internalNamespace.someClass; ${internal} export type internalType = internalC; ${internal} export const internalConst = 10; -${internal} export enum internalEnum { a, b, c }`); +${internal} export enum internalEnum { a, b, c }`, + ); } // Verify initial + incremental edits diff --git a/src/testRunner/unittests/tsbuild/clean.ts b/src/testRunner/unittests/tsbuild/clean.ts index 6b181ac59b381..e5643f4c39052 100644 --- a/src/testRunner/unittests/tsbuild/clean.ts +++ b/src/testRunner/unittests/tsbuild/clean.ts @@ -1,19 +1,22 @@ import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsbuild - clean", () => { verifyTsc({ scenario: "clean", subScenario: `file name and output name clashing`, commandLineArgs: ["--b", "/src/tsconfig.json", "-clean"], - fs: () => loadProjectFromFiles({ - "/src/index.js": "", - "/src/bar.ts": "", - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { allowJs: true }, + fs: () => + loadProjectFromFiles({ + "/src/index.js": "", + "/src/bar.ts": "", + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { allowJs: true }, + }), }), - }), }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuild/commandLine.ts b/src/testRunner/unittests/tsbuild/commandLine.ts index 6ad3d9a8ac5d9..56f7aa0d988ce 100644 --- a/src/testRunner/unittests/tsbuild/commandLine.ts +++ b/src/testRunner/unittests/tsbuild/commandLine.ts @@ -1,5 +1,7 @@ import * as ts from "../../_namespaces/ts"; -import { compilerOptionsToConfigJson } from "../helpers/contents"; +import { + compilerOptionsToConfigJson, +} from "../helpers/contents"; import { noChangeRun, TestTscEdit, @@ -7,7 +9,8 @@ import { } from "../helpers/tsc"; import { appendText, - loadProjectFromFiles, replaceText + loadProjectFromFiles, + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: commandLine::", () => { @@ -16,7 +19,7 @@ describe("unittests:: tsbuild:: commandLine::", () => { return { caption, edit: ts.noop, - commandLineArgs: ["--b", "/src/project", "--verbose", ...options] + commandLineArgs: ["--b", "/src/project", "--verbose", ...options], }; } function noChangeWithSubscenario(caption: string): TestTscEdit { @@ -28,7 +31,7 @@ describe("unittests:: tsbuild:: commandLine::", () => { discrepancyExplanation: () => [ `Clean build tsbuildinfo will have compilerOptions with composite and ${option.replace(/-/g, "")}`, `Incremental build will detect that it doesnt need to rebuild so tsbuild info is from before which has option composite only`, - ] + ], }; } function withEmitDeclarationOnlyChangeAndDiscrepancyExplanation(caption: string): TestTscEdit { @@ -37,7 +40,7 @@ describe("unittests:: tsbuild:: commandLine::", () => { edit.discrepancyExplanation = () => [ ...discrepancyExplanation(), `Clean build info does not have js section because its fresh build`, - `Incremental build info has js section from old build` + `Incremental build info has js section from old build`, ]; return edit; } @@ -207,7 +210,7 @@ describe("unittests:: tsbuild:: commandLine::", () => { discrepancyExplanation: () => [ `Clean build tsbuildinfo for both projects will have compilerOptions with composite and emitDeclarationOnly`, `Incremental build will detect that it doesnt need to rebuild so tsbuild info for projects is from before which has option composite only`, - ] + ], }, { caption: "js emit with change without emitDeclarationOnly", @@ -256,7 +259,7 @@ describe("unittests:: tsbuild:: commandLine::", () => { discrepancyExplanation: () => [ `Clean build tsbuildinfo for both projects will have compilerOptions with composite and emitDeclarationOnly`, `Incremental build will detect that it doesnt need to rebuild so tsbuild info for projects is from before which has option composite as true but emitDeclrationOnly as false`, - ] + ], }, { caption: "no change run with js emit", diff --git a/src/testRunner/unittests/tsbuild/configFileErrors.ts b/src/testRunner/unittests/tsbuild/configFileErrors.ts index 63d9c2bb70dd2..57d74d9f34fd1 100644 --- a/src/testRunner/unittests/tsbuild/configFileErrors.ts +++ b/src/testRunner/unittests/tsbuild/configFileErrors.ts @@ -1,4 +1,6 @@ -import { dedent } from "../../_namespaces/Utils"; +import { + dedent, +} from "../../_namespaces/Utils"; import { noChangeRun, verifyTsc, @@ -6,7 +8,8 @@ import { import { appendText, loadProjectFromDisk, - loadProjectFromFiles, replaceText + loadProjectFromFiles, + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: configFileErrors:: when tsconfig extends the missing file", () => { @@ -22,10 +25,11 @@ describe("unittests:: tsbuild:: configFileErrors:: reports syntax errors in conf verifyTsc({ scenario: "configFileErrors", subScenario: "reports syntax errors in config file", - fs: () => loadProjectFromFiles({ - "/src/a.ts": "export function foo() { }", - "/src/b.ts": "export function bar() { }", - "/src/tsconfig.json": dedent` + fs: () => + loadProjectFromFiles({ + "/src/a.ts": "export function foo() { }", + "/src/b.ts": "export function bar() { }", + "/src/tsconfig.json": dedent` { "compilerOptions": { "composite": true, @@ -34,13 +38,19 @@ describe("unittests:: tsbuild:: configFileErrors:: reports syntax errors in conf "a.ts" "b.ts" ] -}` - }), +}`, + }), commandLineArgs: ["--b", "/src/tsconfig.json"], edits: [ { - edit: fs => replaceText(fs, "/src/tsconfig.json", ",", `, - "declaration": true,`), + edit: fs => + replaceText( + fs, + "/src/tsconfig.json", + ",", + `, + "declaration": true,`, + ), caption: "reports syntax errors after change to config file", discrepancyExplanation: () => [ "During incremental build, tsbuildinfo is not emitted, so declaration option is not present", @@ -53,15 +63,16 @@ describe("unittests:: tsbuild:: configFileErrors:: reports syntax errors in conf }, noChangeRun, { - edit: fs => fs.writeFileSync( - "/src/tsconfig.json", - JSON.stringify({ - compilerOptions: { composite: true, declaration: true }, - files: ["a.ts", "b.ts"] - }) - ), - caption: "builds after fixing config file errors" + edit: fs => + fs.writeFileSync( + "/src/tsconfig.json", + JSON.stringify({ + compilerOptions: { composite: true, declaration: true }, + files: ["a.ts", "b.ts"], + }), + ), + caption: "builds after fixing config file errors", }, - ] + ], }); }); diff --git a/src/testRunner/unittests/tsbuild/configFileExtends.ts b/src/testRunner/unittests/tsbuild/configFileExtends.ts index 0344e78889721..ce0ac78d971ae 100644 --- a/src/testRunner/unittests/tsbuild/configFileExtends.ts +++ b/src/testRunner/unittests/tsbuild/configFileExtends.ts @@ -1,7 +1,9 @@ import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsbuild:: configFileExtends:: when tsconfig extends another config", () => { function getConfigExtendsWithIncludeFs() { @@ -9,12 +11,12 @@ describe("unittests:: tsbuild:: configFileExtends:: when tsconfig extends anothe "/src/tsconfig.json": JSON.stringify({ references: [ { path: "./shared/tsconfig.json" }, - { path: "./webpack/tsconfig.json" } + { path: "./webpack/tsconfig.json" }, ], - files: [] + files: [], }), "/src/shared/tsconfig-base.json": JSON.stringify({ - include: ["./typings-base/"] + include: ["./typings-base/"], }), "/src/shared/typings-base/globals.d.ts": `type Unrestricted = any;`, "/src/shared/tsconfig.json": JSON.stringify({ @@ -22,9 +24,9 @@ describe("unittests:: tsbuild:: configFileExtends:: when tsconfig extends anothe compilerOptions: { composite: true, outDir: "../target-tsc-build/", - rootDir: ".." + rootDir: "..", }, - files: ["./index.ts"] + files: ["./index.ts"], }), "/src/shared/index.ts": `export const a: Unrestricted = 1;`, "/src/webpack/tsconfig.json": JSON.stringify({ @@ -32,10 +34,10 @@ describe("unittests:: tsbuild:: configFileExtends:: when tsconfig extends anothe compilerOptions: { composite: true, outDir: "../target-tsc-build/", - rootDir: ".." + rootDir: "..", }, files: ["./index.ts"], - references: [{ path: "../shared/tsconfig.json" }] + references: [{ path: "../shared/tsconfig.json" }], }), "/src/webpack/index.ts": `export const b: Unrestricted = 1;`, }); @@ -52,4 +54,4 @@ describe("unittests:: tsbuild:: configFileExtends:: when tsconfig extends anothe fs: getConfigExtendsWithIncludeFs, commandLineArgs: ["--b", "/src/webpack/tsconfig.json", "--v", "--listFiles"], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts b/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts index 7936c58b6672e..27fa3377b9780 100644 --- a/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts +++ b/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts @@ -4,7 +4,8 @@ import { } from "../helpers/tsc"; import { loadProjectFromDisk, - loadProjectFromFiles, replaceText + loadProjectFromFiles, + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: when containerOnly project is referenced", () => { @@ -13,33 +14,34 @@ describe("unittests:: tsbuild:: when containerOnly project is referenced", () => subScenario: "verify that subsequent builds after initial build doesnt build anything", fs: () => loadProjectFromDisk("tests/projects/containerOnlyReferenced"), commandLineArgs: ["--b", "/src", "--verbose"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); verifyTsc({ scenario: "containerOnlyReferenced", subScenario: "when solution is referenced indirectly", - fs: () => loadProjectFromFiles({ - "/src/project1/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true }, - references: [], + fs: () => + loadProjectFromFiles({ + "/src/project1/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + references: [], + }), + "/src/project2/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + references: [], + }), + "/src/project2/src/b.ts": "export const b = 10;", + "/src/project3/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + references: [{ path: "../project1" }, { path: "../project2" }], + }), + "/src/project3/src/c.ts": "export const c = 10;", + "/src/project4/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + references: [{ path: "../project3" }], + }), + "/src/project4/src/d.ts": "export const d = 10;", }), - "/src/project2/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true }, - references: [], - }), - "/src/project2/src/b.ts": "export const b = 10;", - "/src/project3/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true }, - references: [{ path: "../project1", }, { path: "../project2" }], - }), - "/src/project3/src/c.ts": "export const c = 10;", - "/src/project4/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true }, - references: [{ path: "../project3" }] - }), - "/src/project4/src/d.ts": "export const d = 10;", - }), commandLineArgs: ["--b", "/src/project4", "--verbose", "--explainFiles"], edits: [{ caption: "modify project3 file", diff --git a/src/testRunner/unittests/tsbuild/declarationEmit.ts b/src/testRunner/unittests/tsbuild/declarationEmit.ts index 30c28dafd7c6f..acc0e3efadcfc 100644 --- a/src/testRunner/unittests/tsbuild/declarationEmit.ts +++ b/src/testRunner/unittests/tsbuild/declarationEmit.ts @@ -3,7 +3,9 @@ import * as vfs from "../../_namespaces/vfs"; import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsbuild:: declarationEmit", () => { function getFiles(): vfs.FileSet { @@ -11,24 +13,24 @@ describe("unittests:: tsbuild:: declarationEmit", () => { "/src/solution/tsconfig.base.json": JSON.stringify({ compilerOptions: { rootDir: "./", - outDir: "lib" - } + outDir: "lib", + }, }), "/src/solution/tsconfig.json": JSON.stringify({ compilerOptions: { composite: true }, references: [{ path: "./src" }], - include: [] + include: [], }), "/src/solution/src/tsconfig.json": JSON.stringify({ compilerOptions: { composite: true }, references: [{ path: "./subProject" }, { path: "./subProject2" }], - include: [] + include: [], }), "/src/solution/src/subProject/tsconfig.json": JSON.stringify({ extends: "../../tsconfig.base.json", compilerOptions: { composite: true }, references: [{ path: "../common" }], - include: ["./index.ts"] + include: ["./index.ts"], }), "/src/solution/src/subProject/index.ts": Utils.dedent` import { Nominal } from '../common/nominal'; @@ -37,7 +39,7 @@ export type MyNominal = Nominal;`, extends: "../../tsconfig.base.json", compilerOptions: { composite: true }, references: [{ path: "../subProject" }], - include: ["./index.ts"] + include: ["./index.ts"], }), "/src/solution/src/subProject2/index.ts": Utils.dedent` import { MyNominal } from '../subProject/index'; @@ -50,7 +52,7 @@ export function getVar(): keyof typeof variable { "/src/solution/src/common/tsconfig.json": JSON.stringify({ extends: "../../tsconfig.base.json", compilerOptions: { composite: true }, - include: ["./nominal.ts"] + include: ["./nominal.ts"], }), "/src/solution/src/common/nominal.ts": Utils.dedent` /// @@ -65,59 +67,61 @@ declare type MyNominal = T & { scenario: "declarationEmit", subScenario: "when declaration file is referenced through triple slash", fs: () => loadProjectFromFiles(getFiles()), - commandLineArgs: ["--b", "/src/solution/tsconfig.json", "--verbose"] + commandLineArgs: ["--b", "/src/solution/tsconfig.json", "--verbose"], }); verifyTsc({ scenario: "declarationEmit", subScenario: "when declaration file is referenced through triple slash but uses no references", - fs: () => loadProjectFromFiles({ - ...getFiles(), - "/src/solution/tsconfig.json": JSON.stringify({ - extends: "./tsconfig.base.json", - compilerOptions: { composite: true }, - include: ["./src/**/*.ts"] + fs: () => + loadProjectFromFiles({ + ...getFiles(), + "/src/solution/tsconfig.json": JSON.stringify({ + extends: "./tsconfig.base.json", + compilerOptions: { composite: true }, + include: ["./src/**/*.ts"], + }), }), - }), - commandLineArgs: ["--b", "/src/solution/tsconfig.json", "--verbose"] + commandLineArgs: ["--b", "/src/solution/tsconfig.json", "--verbose"], }); verifyTsc({ scenario: "declarationEmit", subScenario: "when declaration file used inferred type from referenced project", - fs: () => loadProjectFromFiles({ - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { - composite: true, - baseUrl: ".", - paths: { "@fluentui/*": ["packages/*/src"] } - } - }), - "/src/packages/pkg1/src/index.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { + composite: true, + baseUrl: ".", + paths: { "@fluentui/*": ["packages/*/src"] }, + }, + }), + "/src/packages/pkg1/src/index.ts": Utils.dedent` export interface IThing { a: string; } export interface IThings { thing1: IThing; }`, - "/src/packages/pkg1/tsconfig.json": JSON.stringify({ - extends: "../../tsconfig", - compilerOptions: { outDir: "lib" }, - include: ["src"] - }), - "/src/packages/pkg2/src/index.ts": Utils.dedent` + "/src/packages/pkg1/tsconfig.json": JSON.stringify({ + extends: "../../tsconfig", + compilerOptions: { outDir: "lib" }, + include: ["src"], + }), + "/src/packages/pkg2/src/index.ts": Utils.dedent` import { IThings } from '@fluentui/pkg1'; export function fn4() { const a: IThings = { thing1: { a: 'b' } }; return a.thing1; }`, - "/src/packages/pkg2/tsconfig.json": JSON.stringify({ - extends: "../../tsconfig", - compilerOptions: { outDir: "lib" }, - include: ["src"], - references: [{ path: "../pkg1" }] + "/src/packages/pkg2/tsconfig.json": JSON.stringify({ + extends: "../../tsconfig", + compilerOptions: { outDir: "lib" }, + include: ["src"], + references: [{ path: "../pkg1" }], + }), }), - }), - commandLineArgs: ["--b", "/src/packages/pkg2/tsconfig.json", "--verbose"] + commandLineArgs: ["--b", "/src/packages/pkg2/tsconfig.json", "--verbose"], }); }); diff --git a/src/testRunner/unittests/tsbuild/demo.ts b/src/testRunner/unittests/tsbuild/demo.ts index c05cff7be93d1..4c1def473bb8e 100644 --- a/src/testRunner/unittests/tsbuild/demo.ts +++ b/src/testRunner/unittests/tsbuild/demo.ts @@ -5,7 +5,7 @@ import { import { loadProjectFromDisk, prependText, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: on demo project", () => { @@ -22,7 +22,7 @@ describe("unittests:: tsbuild:: on demo project", () => { scenario: "demo", subScenario: "in master branch with everything setup correctly and reports no error", fs: () => projFs, - commandLineArgs: ["--b", "/src/tsconfig.json", "--verbose"] + commandLineArgs: ["--b", "/src/tsconfig.json", "--verbose"], }); verifyTsc({ @@ -30,28 +30,30 @@ describe("unittests:: tsbuild:: on demo project", () => { subScenario: "in circular branch reports the error about it by stopping build", fs: () => projFs, commandLineArgs: ["--b", "/src/tsconfig.json", "--verbose"], - modifyFs: fs => replaceText( - fs, - "/src/core/tsconfig.json", - "}", - `}, + modifyFs: fs => + replaceText( + fs, + "/src/core/tsconfig.json", + "}", + `}, "references": [ { "path": "../zoo" } - ]` - ) + ]`, + ), }); verifyTsc({ scenario: "demo", subScenario: "in bad-ref branch reports the error about files not in rootDir at the import location", fs: () => projFs, commandLineArgs: ["--b", "/src/tsconfig.json", "--verbose"], - modifyFs: fs => prependText( - fs, - "/src/core/utilities.ts", - `import * as A from '../animals'; -` - ) + modifyFs: fs => + prependText( + fs, + "/src/core/utilities.ts", + `import * as A from '../animals'; +`, + ), }); }); diff --git a/src/testRunner/unittests/tsbuild/emitDeclarationOnly.ts b/src/testRunner/unittests/tsbuild/emitDeclarationOnly.ts index 5c4324e80a360..a6ad5a3198433 100644 --- a/src/testRunner/unittests/tsbuild/emitDeclarationOnly.ts +++ b/src/testRunner/unittests/tsbuild/emitDeclarationOnly.ts @@ -4,7 +4,7 @@ import { } from "../helpers/tsc"; import { loadProjectFromDisk, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: on project with emitDeclarationOnly set to true", () => { @@ -46,9 +46,14 @@ describe("unittests:: tsbuild:: on project with emitDeclarationOnly set to true" edits: [ { caption: "incremental-declaration-doesnt-change", - edit: fs => replaceText(fs, "/src/src/a.ts", "export interface A {", `class C { } -export interface A {`), - + edit: fs => + replaceText( + fs, + "/src/src/a.ts", + "export interface A {", + `class C { } +export interface A {`, + ), }, { caption: "incremental-declaration-changes", diff --git a/src/testRunner/unittests/tsbuild/emptyFiles.ts b/src/testRunner/unittests/tsbuild/emptyFiles.ts index 0c97fb04c10c8..db36b9f88cd28 100644 --- a/src/testRunner/unittests/tsbuild/emptyFiles.ts +++ b/src/testRunner/unittests/tsbuild/emptyFiles.ts @@ -2,7 +2,9 @@ import * as vfs from "../../_namespaces/vfs"; import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromDisk } from "../helpers/vfs"; +import { + loadProjectFromDisk, +} from "../helpers/vfs"; describe("unittests:: tsbuild - empty files option in tsconfig", () => { let projFs: vfs.FileSystem; diff --git a/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts b/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts index 7bdf03df92d98..1346f4e251400 100644 --- a/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts +++ b/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts @@ -1,7 +1,9 @@ import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; // https://github.com/microsoft/TypeScript/issues/33849 describe("unittests:: tsbuild:: exitCodeOnBogusFile:: test exit code", () => { @@ -9,6 +11,6 @@ describe("unittests:: tsbuild:: exitCodeOnBogusFile:: test exit code", () => { scenario: "exitCodeOnBogusFile", subScenario: `test exit code`, fs: () => loadProjectFromFiles({}), - commandLineArgs: ["-b", "bogus.json"] + commandLineArgs: ["-b", "bogus.json"], }); }); diff --git a/src/testRunner/unittests/tsbuild/extends.ts b/src/testRunner/unittests/tsbuild/extends.ts index 196561d58b00e..8605d1e8fbd43 100644 --- a/src/testRunner/unittests/tsbuild/extends.ts +++ b/src/testRunner/unittests/tsbuild/extends.ts @@ -1,5 +1,9 @@ -import { getSymlinkedExtendsSys } from "../helpers/extends"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + getSymlinkedExtendsSys, +} from "../helpers/extends"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; describe("unittests:: tsbuild:: extends::", () => { verifyTscWatch({ @@ -8,4 +12,4 @@ describe("unittests:: tsbuild:: extends::", () => { sys: getSymlinkedExtendsSys, commandLineArgs: ["-b", "src", "--extendedDiagnostics"], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuild/fileDelete.ts b/src/testRunner/unittests/tsbuild/fileDelete.ts index e8768911cad33..c748507ff6267 100644 --- a/src/testRunner/unittests/tsbuild/fileDelete.ts +++ b/src/testRunner/unittests/tsbuild/fileDelete.ts @@ -1,12 +1,16 @@ import * as ts from "../../_namespaces/ts"; import { - dedent + dedent, } from "../../_namespaces/Utils"; -import { compilerOptionsToConfigJson } from "../helpers/contents"; +import { + compilerOptionsToConfigJson, +} from "../helpers/contents"; import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsbuild:: fileDelete::", () => { function fs(childOptions: ts.CompilerOptions, mainOptions?: ts.CompilerOptions) { @@ -54,7 +58,7 @@ describe("unittests:: tsbuild:: fileDelete::", () => { discrepancyExplanation: () => [ "Clean build will not have latestChangedDtsFile as there was no emit and emitSignatures as undefined for files", "Incremental will store the past latestChangedDtsFile and emitSignatures", - ] + ], }], }); @@ -65,7 +69,7 @@ describe("unittests:: tsbuild:: fileDelete::", () => { fs: () => fs({ composite: true, outFile: "../childResult.js", module: ts.ModuleKind.AMD }, { composite: true, outFile: "../mainResult.js", module: ts.ModuleKind.AMD }), edits: [{ caption: "delete child2 file", - edit: fs => fs.rimrafSync("/src/child/child2.ts") + edit: fs => fs.rimrafSync("/src/child/child2.ts"), }], }); @@ -79,7 +83,7 @@ describe("unittests:: tsbuild:: fileDelete::", () => { edit: fs => { fs.rimrafSync("/src/child/child2.ts"); fs.rimrafSync("/src/child/child2.js"); - } + }, }], }); @@ -93,4 +97,4 @@ describe("unittests:: tsbuild:: fileDelete::", () => { edit: fs => fs.rimrafSync("/src/child/child2.ts"), }], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuild/graphOrdering.ts b/src/testRunner/unittests/tsbuild/graphOrdering.ts index b5fefcf3386a7..0adf5d3b26903 100644 --- a/src/testRunner/unittests/tsbuild/graphOrdering.ts +++ b/src/testRunner/unittests/tsbuild/graphOrdering.ts @@ -15,7 +15,7 @@ describe("unittests:: tsbuild - graph-ordering", () => { ["H", "I"], ["I", "J"], ["J", "H"], - ["J", "E"] + ["J", "E"], ]; before(() => { @@ -80,11 +80,15 @@ describe("unittests:: tsbuild - graph-ordering", () => { fileSystem.mkdirpSync(`/project/${proj}`); fileSystem.writeFileSync(`/project/${proj}/${proj}.ts`, "export {}"); const configFileName = getProjectFileName(proj); - const configContent = JSON.stringify({ - compilerOptions: { composite: true }, - files: [`./${proj}.ts`], - references: deps.filter(d => d[0] === proj).map(d => ({ path: `../${d[1]}` })) - }, undefined, 2); + const configContent = JSON.stringify( + { + compilerOptions: { composite: true }, + files: [`./${proj}.ts`], + references: deps.filter(d => d[0] === proj).map(d => ({ path: `../${d[1]}` })), + }, + undefined, + 2, + ); fileSystem.writeFileSync(configFileName, configContent); projFileNames.push(configFileName); } diff --git a/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts b/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts index 2c120f994aefe..52ac511c51769 100644 --- a/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts +++ b/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts @@ -5,7 +5,7 @@ import { import { appendText, loadProjectFromDisk, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: inferredTypeFromTransitiveModule::", () => { @@ -43,13 +43,13 @@ describe("unittests:: tsbuild:: inferredTypeFromTransitiveModule::", () => { edits: [ { caption: "incremental-declaration-changes", - edit: changeBarParam + edit: changeBarParam, }, { caption: "incremental-declaration-changes", edit: changeBarParamBack, }, - ] + ], }); verifyTsc({ @@ -59,14 +59,18 @@ describe("unittests:: tsbuild:: inferredTypeFromTransitiveModule::", () => { commandLineArgs: ["--b", "/src", "--verbose"], modifyFs: fs => { changeToIsolatedModules(fs); - appendText(fs, "/src/lazyIndex.ts", ` + appendText( + fs, + "/src/lazyIndex.ts", + ` import { default as bar } from './bar'; -bar("hello");`); +bar("hello");`, + ); }, edits: [ { caption: "incremental-declaration-changes", - edit: changeBarParam + edit: changeBarParam, }, { caption: "incremental-declaration-changes", @@ -74,13 +78,13 @@ bar("hello");`); }, { caption: "incremental-declaration-changes", - edit: changeBarParam + edit: changeBarParam, }, { caption: "Fix Error", - edit: fs => replaceText(fs, "/src/lazyIndex.ts", `bar("hello")`, "bar()") + edit: fs => replaceText(fs, "/src/lazyIndex.ts", `bar("hello")`, "bar()"), }, - ] + ], }); }); diff --git a/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts b/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts index d07751ec262d8..0dd59b5a0e800 100644 --- a/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts +++ b/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts @@ -1,26 +1,29 @@ import * as Utils from "../../_namespaces/Utils"; -import { symbolLibContent } from "../helpers/contents"; +import { + symbolLibContent, +} from "../helpers/contents"; import { verifyTsc, } from "../helpers/tsc"; import { loadProjectFromFiles, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { verifyTsc({ scenario: "javascriptProjectEmit", subScenario: `loads js-based projects and emits them correctly`, - fs: () => loadProjectFromFiles({ - "/src/common/nominal.js": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/common/nominal.js": Utils.dedent` /** * @template T, Name * @typedef {T & {[Symbol.species]: Name}} Nominal */ module.exports = {}; `, - "/src/common/tsconfig.json": Utils.dedent` + "/src/common/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -28,14 +31,14 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { }, "include": ["nominal.js"] }`, - "/src/sub-project/index.js": Utils.dedent` + "/src/sub-project/index.js": Utils.dedent` import { Nominal } from '../common/nominal'; /** * @typedef {Nominal} MyNominal */ `, - "/src/sub-project/tsconfig.json": Utils.dedent` + "/src/sub-project/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -46,7 +49,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": ["./index.js"] }`, - "/src/sub-project-2/index.js": Utils.dedent` + "/src/sub-project-2/index.js": Utils.dedent` import { MyNominal } from '../sub-project/index'; const variable = { @@ -60,7 +63,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { return 'key'; } `, - "/src/sub-project-2/tsconfig.json": Utils.dedent` + "/src/sub-project-2/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -71,7 +74,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": ["./index.js"] }`, - "/src/tsconfig.json": Utils.dedent` + "/src/tsconfig.json": Utils.dedent` { "compilerOptions": { "composite": true @@ -82,7 +85,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": [] }`, - "/src/tsconfig.base.json": Utils.dedent` + "/src/tsconfig.base.json": Utils.dedent` { "compilerOptions": { "skipLibCheck": true, @@ -93,21 +96,22 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { "declaration": true } }`, - }, symbolLibContent), - commandLineArgs: ["-b", "/src"] + }, symbolLibContent), + commandLineArgs: ["-b", "/src"], }); verifyTsc({ scenario: "javascriptProjectEmit", subScenario: `modifies outfile js projects and concatenates them correctly`, - fs: () => loadProjectFromFiles({ - "/src/common/nominal.js": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/common/nominal.js": Utils.dedent` /** * @template T, Name * @typedef {T & {[Symbol.species]: Name}} Nominal */ `, - "/src/common/tsconfig.json": Utils.dedent` + "/src/common/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -117,13 +121,13 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { }, "include": ["nominal.js"] }`, - "/src/sub-project/index.js": Utils.dedent` + "/src/sub-project/index.js": Utils.dedent` /** * @typedef {Nominal} MyNominal */ const c = /** @type {*} */(null); `, - "/src/sub-project/tsconfig.json": Utils.dedent` + "/src/sub-project/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -137,7 +141,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": ["./index.js"] }`, - "/src/sub-project-2/index.js": Utils.dedent` + "/src/sub-project-2/index.js": Utils.dedent` const variable = { key: /** @type {MyNominal} */('value'), }; @@ -149,7 +153,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { return 'key'; } `, - "/src/sub-project-2/tsconfig.json": Utils.dedent` + "/src/sub-project-2/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -163,7 +167,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": ["./index.js"] }`, - "/src/tsconfig.json": Utils.dedent` + "/src/tsconfig.json": Utils.dedent` { "compilerOptions": { "ignoreDeprecations":"5.0", @@ -176,7 +180,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": [] }`, - "/src/tsconfig.base.json": Utils.dedent` + "/src/tsconfig.base.json": Utils.dedent` { "compilerOptions": { "skipLibCheck": true, @@ -186,27 +190,28 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { "declaration": true } }`, - }, symbolLibContent), + }, symbolLibContent), commandLineArgs: ["-b", "/src"], edits: [{ caption: "incremental-declaration-doesnt-change", - edit: fs => replaceText(fs, "/src/sub-project/index.js", "null", "undefined") - }] + edit: fs => replaceText(fs, "/src/sub-project/index.js", "null", "undefined"), + }], }); verifyTsc({ scenario: "javascriptProjectEmit", subScenario: `loads js-based projects with non-moved json files and emits them correctly`, - fs: () => loadProjectFromFiles({ - "/src/common/obj.json": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/common/obj.json": Utils.dedent` { "val": 42 }`, - "/src/common/index.ts": Utils.dedent` + "/src/common/index.ts": Utils.dedent` import x = require("./obj.json"); export = x; `, - "/src/common/tsconfig.json": Utils.dedent` + "/src/common/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -215,12 +220,12 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { }, "include": ["index.ts", "obj.json"] }`, - "/src/sub-project/index.js": Utils.dedent` + "/src/sub-project/index.js": Utils.dedent` import mod from '../common'; export const m = mod; `, - "/src/sub-project/tsconfig.json": Utils.dedent` + "/src/sub-project/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -231,7 +236,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": ["./index.js"] }`, - "/src/sub-project-2/index.js": Utils.dedent` + "/src/sub-project-2/index.js": Utils.dedent` import { m } from '../sub-project/index'; const variable = { @@ -242,7 +247,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { return variable; } `, - "/src/sub-project-2/tsconfig.json": Utils.dedent` + "/src/sub-project-2/tsconfig.json": Utils.dedent` { "extends": "../tsconfig.base.json", "compilerOptions": { @@ -253,7 +258,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": ["./index.js"] }`, - "/src/tsconfig.json": Utils.dedent` + "/src/tsconfig.json": Utils.dedent` { "compilerOptions": { "composite": true @@ -264,7 +269,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ], "include": [] }`, - "/src/tsconfig.base.json": Utils.dedent` + "/src/tsconfig.base.json": Utils.dedent` { "compilerOptions": { "skipLibCheck": true, @@ -277,7 +282,7 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { "declaration": true } }`, - }, symbolLibContent), - commandLineArgs: ["-b", "/src"] + }, symbolLibContent), + commandLineArgs: ["-b", "/src"], }); }); diff --git a/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts b/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts index bee588739366e..3d47aaad0207d 100644 --- a/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts +++ b/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts @@ -4,7 +4,7 @@ import { import { appendText, loadProjectFromDisk, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: lateBoundSymbol:: interface is merged and contains late bound member", () => { @@ -22,6 +22,6 @@ describe("unittests:: tsbuild:: lateBoundSymbol:: interface is merged and contai caption: "incremental-declaration-doesnt-change", edit: fs => appendText(fs, "/src/src/main.ts", "const x = 10;"), }, - ] + ], }); }); diff --git a/src/testRunner/unittests/tsbuild/libraryResolution.ts b/src/testRunner/unittests/tsbuild/libraryResolution.ts index ed854616c3ac2..4fe269a2ea0fc 100644 --- a/src/testRunner/unittests/tsbuild/libraryResolution.ts +++ b/src/testRunner/unittests/tsbuild/libraryResolution.ts @@ -1,5 +1,9 @@ -import { getFsForLibResolution } from "../helpers/libraryResolution"; -import { verifyTsc } from "../helpers/tsc"; +import { + getFsForLibResolution, +} from "../helpers/libraryResolution"; +import { + verifyTsc, +} from "../helpers/tsc"; describe("unittests:: tsbuild:: libraryResolution:: library file resolution", () => { function verify(libRedirection?: true) { diff --git a/src/testRunner/unittests/tsbuild/moduleResolution.ts b/src/testRunner/unittests/tsbuild/moduleResolution.ts index e6e718526c94d..2a239547eef3e 100644 --- a/src/testRunner/unittests/tsbuild/moduleResolution.ts +++ b/src/testRunner/unittests/tsbuild/moduleResolution.ts @@ -4,8 +4,12 @@ import { noChangeOnlyRuns, verifyTsc, } from "../helpers/tsc"; -import { verifyTscWatch } from "../helpers/tscWatch"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; import { createWatchedSystem, libFile, @@ -18,22 +22,22 @@ describe("unittests:: tsbuild:: moduleResolution:: handles the modules and optio path: `/user/username/projects/myproject/packages/pkg1/index.ts`, content: Utils.dedent` import type { TheNum } from 'pkg2' - export const theNum: TheNum = 42;` + export const theNum: TheNum = 42;`, }, { path: `/user/username/projects/myproject/packages/pkg1/tsconfig.json`, content: JSON.stringify({ compilerOptions: { outDir: "build", ...optionsToExtend }, - references: [{ path: "../pkg2" }] - }) + references: [{ path: "../pkg2" }], + }), }, { path: `/user/username/projects/myproject/packages/pkg2/const.ts`, - content: `export type TheNum = 42;` + content: `export type TheNum = 42;`, }, { path: `/user/username/projects/myproject/packages/pkg2/index.ts`, - content: `export type { TheNum } from 'const';` + content: `export type { TheNum } from 'const';`, }, { path: `/user/username/projects/myproject/packages/pkg2/tsconfig.json`, @@ -42,9 +46,9 @@ describe("unittests:: tsbuild:: moduleResolution:: handles the modules and optio composite: true, outDir: "build", baseUrl: ".", - ...optionsToExtend - } - }) + ...optionsToExtend, + }, + }), }, { path: `/user/username/projects/myproject/packages/pkg2/package.json`, @@ -52,13 +56,13 @@ describe("unittests:: tsbuild:: moduleResolution:: handles the modules and optio name: "pkg2", version: "1.0.0", main: "build/index.js", - }) + }), }, { path: `/user/username/projects/myproject/node_modules/pkg2`, symLink: `/user/username/projects/myproject/packages/pkg2`, }, - libFile + libFile, ], { currentDirectory: "/user/username/projects/myproject" }); } @@ -79,20 +83,21 @@ describe("unittests:: tsbuild:: moduleResolution:: handles the modules and optio verifyTsc({ scenario: "moduleResolution", subScenario: `type reference resolution uses correct options for different resolution options referenced project`, - fs: () => loadProjectFromFiles({ - "/src/packages/pkg1_index.ts": `export const theNum: TheNum = "type1";`, - "/src/packages/pkg1.tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true, typeRoots: ["./typeroot1"] }, - files: ["./pkg1_index.ts"] + fs: () => + loadProjectFromFiles({ + "/src/packages/pkg1_index.ts": `export const theNum: TheNum = "type1";`, + "/src/packages/pkg1.tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true, typeRoots: ["./typeroot1"] }, + files: ["./pkg1_index.ts"], + }), + "/src/packages/typeroot1/sometype/index.d.ts": Utils.dedent`declare type TheNum = "type1";`, + "/src/packages/pkg2_index.ts": `export const theNum: TheNum2 = "type2";`, + "/src/packages/pkg2.tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true, typeRoots: ["./typeroot2"] }, + files: ["./pkg2_index.ts"], + }), + "/src/packages/typeroot2/sometype/index.d.ts": Utils.dedent`declare type TheNum2 = "type2";`, }), - "/src/packages/typeroot1/sometype/index.d.ts": Utils.dedent`declare type TheNum = "type1";`, - "/src/packages/pkg2_index.ts": `export const theNum: TheNum2 = "type2";`, - "/src/packages/pkg2.tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true, typeRoots: ["./typeroot2"] }, - files: ["./pkg2_index.ts"] - }), - "/src/packages/typeroot2/sometype/index.d.ts": Utils.dedent`declare type TheNum2 = "type2";`, - }), commandLineArgs: ["-b", "/src/packages/pkg1.tsconfig.json", "/src/packages/pkg2.tsconfig.json", "--verbose", "--traceResolution"], }); }); @@ -101,30 +106,31 @@ describe("unittests:: tsbuild:: moduleResolution:: impliedNodeFormat differs bet verifyTsc({ scenario: "moduleResolution", subScenario: "impliedNodeFormat differs between projects for shared file", - fs: () => loadProjectFromFiles({ - "/src/projects/a/src/index.ts": "", - "/src/projects/a/tsconfig.json": JSON.stringify({ - compilerOptions: { strict: true } - }), - "/src/projects/b/src/index.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/projects/a/src/index.ts": "", + "/src/projects/a/tsconfig.json": JSON.stringify({ + compilerOptions: { strict: true }, + }), + "/src/projects/b/src/index.ts": Utils.dedent` import pg from "pg"; pg.foo(); `, - "/src/projects/b/tsconfig.json": JSON.stringify({ - compilerOptions: { strict: true, module: "node16" } + "/src/projects/b/tsconfig.json": JSON.stringify({ + compilerOptions: { strict: true, module: "node16" }, + }), + "/src/projects/b/package.json": JSON.stringify({ + name: "b", + type: "module", + }), + "/src/projects/node_modules/@types/pg/index.d.ts": "export function foo(): void;", + "/src/projects/node_modules/@types/pg/package.json": JSON.stringify({ + name: "@types/pg", + types: "index.d.ts", + }), }), - "/src/projects/b/package.json": JSON.stringify({ - name: "b", - type: "module" - }), - "/src/projects/node_modules/@types/pg/index.d.ts": "export function foo(): void;", - "/src/projects/node_modules/@types/pg/package.json": JSON.stringify({ - name: "@types/pg", - types: "index.d.ts", - }), - }), modifyFs: fs => fs.writeFileSync("/lib/lib.es2022.full.d.ts", libFile.content), commandLineArgs: ["-b", "/src/projects/a", "/src/projects/b", "--verbose", "--traceResolution", "--explainFiles"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuild/moduleSpecifiers.ts b/src/testRunner/unittests/tsbuild/moduleSpecifiers.ts index b42439f099569..0a872a15f2696 100644 --- a/src/testRunner/unittests/tsbuild/moduleSpecifiers.ts +++ b/src/testRunner/unittests/tsbuild/moduleSpecifiers.ts @@ -1,23 +1,30 @@ import * as Utils from "../../_namespaces/Utils"; -import { symbolLibContent } from "../helpers/contents"; +import { + symbolLibContent, +} from "../helpers/contents"; import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; -import { libFile } from "../helpers/virtualFileSystemWithWatch"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; +import { + libFile, +} from "../helpers/virtualFileSystemWithWatch"; // https://github.com/microsoft/TypeScript/issues/31696 describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers to referenced projects resolve correctly", () => { verifyTsc({ scenario: "moduleSpecifiers", subScenario: `synthesized module specifiers resolve correctly`, - fs: () => loadProjectFromFiles({ - "/src/solution/common/nominal.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/solution/common/nominal.ts": Utils.dedent` export declare type Nominal = T & { [Symbol.species]: Name; }; `, - "/src/solution/common/tsconfig.json": Utils.dedent` + "/src/solution/common/tsconfig.json": Utils.dedent` { "extends": "../../tsconfig.base.json", "compilerOptions": { @@ -25,12 +32,12 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers }, "include": ["nominal.ts"] }`, - "/src/solution/sub-project/index.ts": Utils.dedent` + "/src/solution/sub-project/index.ts": Utils.dedent` import { Nominal } from '../common/nominal'; export type MyNominal = Nominal; `, - "/src/solution/sub-project/tsconfig.json": Utils.dedent` + "/src/solution/sub-project/tsconfig.json": Utils.dedent` { "extends": "../../tsconfig.base.json", "compilerOptions": { @@ -41,7 +48,7 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers ], "include": ["./index.ts"] }`, - "/src/solution/sub-project-2/index.ts": Utils.dedent` + "/src/solution/sub-project-2/index.ts": Utils.dedent` import { MyNominal } from '../sub-project/index'; const variable = { @@ -52,7 +59,7 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers return 'key'; } `, - "/src/solution/sub-project-2/tsconfig.json": Utils.dedent` + "/src/solution/sub-project-2/tsconfig.json": Utils.dedent` { "extends": "../../tsconfig.base.json", "compilerOptions": { @@ -63,7 +70,7 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers ], "include": ["./index.ts"] }`, - "/src/solution/tsconfig.json": Utils.dedent` + "/src/solution/tsconfig.json": Utils.dedent` { "compilerOptions": { "composite": true @@ -74,7 +81,7 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers ], "include": [] }`, - "/src/tsconfig.base.json": Utils.dedent` + "/src/tsconfig.base.json": Utils.dedent` { "compilerOptions": { "skipLibCheck": true, @@ -82,7 +89,7 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers "outDir": "lib", } }`, - "/src/tsconfig.json": Utils.dedent`{ + "/src/tsconfig.json": Utils.dedent`{ "compilerOptions": { "composite": true }, @@ -90,9 +97,9 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers { "path": "./solution" } ], "include": [] - }` - }, symbolLibContent), - commandLineArgs: ["-b", "/src", "--verbose"] + }`, + }, symbolLibContent), + commandLineArgs: ["-b", "/src", "--verbose"], }); }); @@ -101,25 +108,26 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers verifyTsc({ scenario: "moduleSpecifiers", subScenario: `synthesized module specifiers across projects resolve correctly`, - fs: () => loadProjectFromFiles({ - "/src/src-types/index.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/src-types/index.ts": Utils.dedent` export * from './dogconfig.js';`, - "/src/src-types/dogconfig.ts": Utils.dedent` + "/src/src-types/dogconfig.ts": Utils.dedent` export interface DogConfig { name: string; }`, - "/src/src-dogs/index.ts": Utils.dedent` + "/src/src-dogs/index.ts": Utils.dedent` export * from 'src-types'; export * from './lassie/lassiedog.js'; `, - "/src/src-dogs/dogconfig.ts": Utils.dedent` + "/src/src-dogs/dogconfig.ts": Utils.dedent` import { DogConfig } from 'src-types'; export const DOG_CONFIG: DogConfig = { name: 'Default dog', }; `, - "/src/src-dogs/dog.ts": Utils.dedent` + "/src/src-dogs/dog.ts": Utils.dedent` import { DogConfig } from 'src-types'; import { DOG_CONFIG } from './dogconfig.js'; @@ -130,7 +138,7 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers } } `, - "/src/src-dogs/lassie/lassiedog.ts": Utils.dedent` + "/src/src-dogs/lassie/lassiedog.ts": Utils.dedent` import { Dog } from '../dog.js'; import { LASSIE_CONFIG } from './lassieconfig.js'; @@ -138,29 +146,29 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers protected static getDogConfig = () => LASSIE_CONFIG; } `, - "/src/src-dogs/lassie/lassieconfig.ts": Utils.dedent` + "/src/src-dogs/lassie/lassieconfig.ts": Utils.dedent` import { DogConfig } from 'src-types'; export const LASSIE_CONFIG: DogConfig = { name: 'Lassie' }; `, - "/src/tsconfig-base.json": Utils.dedent` + "/src/tsconfig-base.json": Utils.dedent` { "compilerOptions": { "declaration": true, "module": "node16" } }`, - "/src/src-types/package.json": Utils.dedent` + "/src/src-types/package.json": Utils.dedent` { "type": "module", "exports": "./index.js" }`, - "/src/src-dogs/package.json": Utils.dedent` + "/src/src-dogs/package.json": Utils.dedent` { "type": "module", "exports": "./index.js" }`, - "/src/src-types/tsconfig.json": Utils.dedent` + "/src/src-types/tsconfig.json": Utils.dedent` { "extends": "../tsconfig-base.json", "compilerOptions": { @@ -170,7 +178,7 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers "**/*" ] }`, - "/src/src-dogs/tsconfig.json": Utils.dedent` + "/src/src-dogs/tsconfig.json": Utils.dedent` { "extends": "../tsconfig-base.json", "compilerOptions": { @@ -183,12 +191,12 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers "**/*" ] }`, - }, ""), + }, ""), modifyFs: fs => { fs.writeFileSync("/lib/lib.es2022.full.d.ts", libFile.content); fs.symlinkSync("/src", "/src/src-types/node_modules"); fs.symlinkSync("/src", "/src/src-dogs/node_modules"); }, - commandLineArgs: ["-b", "src/src-types", "src/src-dogs", "--verbose"] + commandLineArgs: ["-b", "src/src-types", "src/src-dogs", "--verbose"], }); }); diff --git a/src/testRunner/unittests/tsbuild/noEmit.ts b/src/testRunner/unittests/tsbuild/noEmit.ts index 3f0e6f278d949..39b1282c8e003 100644 --- a/src/testRunner/unittests/tsbuild/noEmit.ts +++ b/src/testRunner/unittests/tsbuild/noEmit.ts @@ -2,19 +2,22 @@ import { noChangeRun, verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsbuild:: noEmit", () => { function verifyNoEmitWorker(subScenario: string, aTsContent: string, commandLineArgs: readonly string[]) { verifyTsc({ scenario: "noEmit", subScenario, - fs: () => loadProjectFromFiles({ - "/src/a.ts": aTsContent, - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { noEmit: true } - }) - }), + fs: () => + loadProjectFromFiles({ + "/src/a.ts": aTsContent, + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { noEmit: true }, + }), + }), commandLineArgs, edits: [ noChangeRun, @@ -35,4 +38,4 @@ describe("unittests:: tsbuild:: noEmit", () => { verifyNoEmit("syntax errors", `const a = "hello`); verifyNoEmit("semantic errors", `const a: number = "hello"`); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuild/noEmitOnError.ts b/src/testRunner/unittests/tsbuild/noEmitOnError.ts index 10fb8ebd0e8d9..182e6322ab5e3 100644 --- a/src/testRunner/unittests/tsbuild/noEmitOnError.ts +++ b/src/testRunner/unittests/tsbuild/noEmitOnError.ts @@ -3,7 +3,9 @@ import { noChangeRun, verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromDisk } from "../helpers/vfs"; +import { + loadProjectFromDisk, +} from "../helpers/vfs"; describe("unittests:: tsbuild - with noEmitOnError", () => { let projFs: vfs.FileSystem; @@ -23,10 +25,15 @@ describe("unittests:: tsbuild - with noEmitOnError", () => { noChangeRun, { caption: "Fix error", - edit: fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; + edit: fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; const a = { lastName: 'sdsd' -};`, "utf-8"), +};`, + "utf-8", + ), }, noChangeRun, ], @@ -42,10 +49,15 @@ const a = { noChangeRun, { caption: "Fix error", - edit: fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; + edit: fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; const a = { lastName: 'sdsd' -};`, "utf-8"), +};`, + "utf-8", + ), }, noChangeRun, ], @@ -56,15 +68,25 @@ const a = { scenario: "noEmitOnError", subScenario: "semantic errors", fs: () => projFs, - modifyFs: fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; -const a: string = 10;`, "utf-8"), + modifyFs: fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; +const a: string = 10;`, + "utf-8", + ), commandLineArgs: ["--b", "/src/tsconfig.json"], edits: [ noChangeRun, { caption: "Fix error", - edit: fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; -const a: string = "hello";`, "utf-8"), + edit: fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; +const a: string = "hello";`, + "utf-8", + ), }, noChangeRun, ], @@ -75,15 +97,25 @@ const a: string = "hello";`, "utf-8"), scenario: "noEmitOnError", subScenario: "semantic errors with incremental", fs: () => projFs, - modifyFs: fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; -const a: string = 10;`, "utf-8"), + modifyFs: fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; +const a: string = 10;`, + "utf-8", + ), commandLineArgs: ["--b", "/src/tsconfig.json", "--incremental"], edits: [ noChangeRun, { caption: "Fix error", - edit: fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; -const a: string = "hello";`, "utf-8"), + edit: fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; +const a: string = "hello";`, + "utf-8", + ), }, noChangeRun, ], diff --git a/src/testRunner/unittests/tsbuild/outFile.ts b/src/testRunner/unittests/tsbuild/outFile.ts index 1c5a46885fee4..92df313b09741 100644 --- a/src/testRunner/unittests/tsbuild/outFile.ts +++ b/src/testRunner/unittests/tsbuild/outFile.ts @@ -1,7 +1,9 @@ import * as fakes from "../../_namespaces/fakes"; import * as ts from "../../_namespaces/ts"; import * as vfs from "../../_namespaces/vfs"; -import { createSolutionBuilderHostForBaseline } from "../helpers/solutionBuilder"; +import { + createSolutionBuilderHostForBaseline, +} from "../helpers/solutionBuilder"; import { noChangeOnlyRuns, testTscCompileLike, @@ -18,10 +20,12 @@ import { addTestPrologue, addTripleSlashRef, appendText, - changeStubToRest, enableStrict, - loadProjectFromDisk, prependText, + changeStubToRest, + enableStrict, + loadProjectFromDisk, + prependText, removeRest, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: outFile::", () => { @@ -70,7 +74,7 @@ describe("unittests:: tsbuild:: outFile::", () => { if (modifyAgainFs) { (edits ??= []).push({ caption: "incremental-headers-change-without-dts-changes", - edit: modifyAgainFs + edit: modifyAgainFs, }); } verifyTsc({ @@ -93,7 +97,7 @@ describe("unittests:: tsbuild:: outFile::", () => { verifyOutFileScenario({ subScenario: "explainFiles", additionalCommandLineArgs: ["--explainFiles"], - baselineOnly: true + baselineOnly: true, }); // Verify baseline with build info + dts unChanged @@ -101,7 +105,7 @@ describe("unittests:: tsbuild:: outFile::", () => { subScenario: "when final project is not composite but uses project references", modifyFs: fs => replaceText(fs, "/src/third/tsconfig.json", `"composite": true,`, ""), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify baseline with build info @@ -110,17 +114,23 @@ describe("unittests:: tsbuild:: outFile::", () => { modifyFs: fs => replaceText(fs, "/src/third/tsconfig.json", `"composite": true,`, `"incremental": true,`), ignoreDtsChanged: true, ignoreDtsUnchanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify baseline with build info verifyOutFileScenario({ subScenario: "when final project specifies tsBuildInfoFile", - modifyFs: fs => replaceText(fs, "/src/third/tsconfig.json", `"composite": true,`, `"composite": true, - "tsBuildInfoFile": "./thirdjs/output/third.tsbuildinfo",`), + modifyFs: fs => + replaceText( + fs, + "/src/third/tsconfig.json", + `"composite": true,`, + `"composite": true, + "tsBuildInfoFile": "./thirdjs/output/third.tsbuildinfo",`, + ), ignoreDtsChanged: true, ignoreDtsUnchanged: true, - baselineOnly: true + baselineOnly: true, }); function getOutFileFsAfterBuild() { @@ -139,7 +149,7 @@ describe("unittests:: tsbuild:: outFile::", () => { subScenario: "clean projects", fs: getOutFileFsAfterBuild, commandLineArgs: ["--b", "/src/third", "--clean"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); verifyTsc({ @@ -168,7 +178,7 @@ describe("unittests:: tsbuild:: outFile::", () => { const buildHost = createSolutionBuilderHostForBaseline(sys, "FakeTSCurrentVersion"); const builder = ts.createSolutionBuilder(buildHost, ["/src/third"], { verbose: true }); sys.exit(builder.build()); - } + }, }); verifyTsc({ @@ -189,8 +199,8 @@ describe("unittests:: tsbuild:: outFile::", () => { caption: "Make incremental build with change in file that doesnt affect dts", edit: fs => appendText(fs, "/src/first/first_PART1.ts", "console.log(s);"), commandLineArgs: ["--b", "/src/third", "--verbose", "--incremental"], - } - ] + }, + ], }); verifyTsc({ @@ -206,7 +216,7 @@ describe("unittests:: tsbuild:: outFile::", () => { fs.utimesSync("/src/first/first_PART1.ts", time, time); }, }, - ] + ], }); verifyTscCompileLike(testTscCompileLike, { @@ -218,7 +228,7 @@ describe("unittests:: tsbuild:: outFile::", () => { const buildHost = createSolutionBuilderHostForBaseline(sys); const builder = ts.createSolutionBuilder(buildHost, ["/src/third/tsconfig.json"], {}); sys.exit(builder.build("/src/second/tsconfig.json")); - } + }, }); verifyTscCompileLike(testTscCompileLike, { @@ -230,7 +240,7 @@ describe("unittests:: tsbuild:: outFile::", () => { const buildHost = createSolutionBuilderHostForBaseline(sys); const builder = ts.createSolutionBuilder(buildHost, ["/src/third/tsconfig.json"], { verbose: true }); sys.exit(builder.clean("/src/second/tsconfig.json")); - } + }, }); describe("Prepend output with .tsbuildinfo", () => { @@ -244,7 +254,7 @@ describe("unittests:: tsbuild:: outFile::", () => { enableStrict(fs, "/src/second/tsconfig.json"); enableStrict(fs, "/src/third/tsconfig.json"); }, - modifyAgainFs: fs => addTestPrologue(fs, "/src/first/first_PART1.ts", `"myPrologue"`) + modifyAgainFs: fs => addTestPrologue(fs, "/src/first/first_PART1.ts", `"myPrologue"`), }); // Verify ignore dtsChanged @@ -253,7 +263,7 @@ describe("unittests:: tsbuild:: outFile::", () => { modifyFs: fs => enableStrict(fs, "/src/second/tsconfig.json"), modifyAgainFs: fs => addTestPrologue(fs, "src/first/first_PART1.ts", `"myPrologue"`), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify initial + incremental edits - sourcemap verification @@ -269,7 +279,7 @@ describe("unittests:: tsbuild:: outFile::", () => { addTestPrologue(fs, "/src/third/third_part1.ts", `"myPrologue";`); addTestPrologue(fs, "/src/third/third_part1.ts", `"myPrologue3";`); }, - modifyAgainFs: fs => addTestPrologue(fs, "/src/first/first_PART1.ts", `"myPrologue5"`) + modifyAgainFs: fs => addTestPrologue(fs, "/src/first/first_PART1.ts", `"myPrologue5"`), }); // Verify ignore dtsChanged @@ -283,7 +293,7 @@ describe("unittests:: tsbuild:: outFile::", () => { }, modifyAgainFs: fs => addTestPrologue(fs, "/src/first/first_PART1.ts", `"myPrologue5"`), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); }); @@ -306,7 +316,7 @@ describe("unittests:: tsbuild:: outFile::", () => { subScenario: "shebang in only one dependency project", modifyFs: fs => addShebang(fs, "second", "second_part1"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); }); @@ -320,7 +330,7 @@ describe("unittests:: tsbuild:: outFile::", () => { addRest(fs, "second", "second_part1"); addRest(fs, "third", "third_part1"); }, - modifyAgainFs: fs => removeRest(fs, "first", "first_PART1") + modifyAgainFs: fs => removeRest(fs, "first", "first_PART1"), }); // Verify ignore dtsChanged @@ -332,7 +342,7 @@ describe("unittests:: tsbuild:: outFile::", () => { }, modifyAgainFs: fs => changeStubToRest(fs, "first", "first_PART1"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify ignore dtsChanged @@ -348,7 +358,7 @@ describe("unittests:: tsbuild:: outFile::", () => { }, modifyAgainFs: fs => removeRest(fs, "first", "first_PART1"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify ignore dtsChanged @@ -361,7 +371,7 @@ describe("unittests:: tsbuild:: outFile::", () => { }, modifyAgainFs: fs => removeRest(fs, "first", "first_PART1"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); }); @@ -375,7 +385,7 @@ describe("unittests:: tsbuild:: outFile::", () => { addTripleSlashRef(fs, "first", "first_part2"); addTripleSlashRef(fs, "second", "second_part1"); addTripleSlashRef(fs, "third", "third_part1"); - } + }, }); // Verify ignore dtsChanged @@ -383,7 +393,7 @@ describe("unittests:: tsbuild:: outFile::", () => { subScenario: "triple slash refs in one project", modifyFs: fs => addTripleSlashRef(fs, "second", "second_part1"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); }); @@ -399,8 +409,13 @@ describe("unittests:: tsbuild:: outFile::", () => { } function stripInternalOfThird(fs: vfs.FileSystem) { - replaceText(fs, "/src/third/tsconfig.json", `"declaration": true,`, `"declaration": true, - "stripInternal": true,`); + replaceText( + fs, + "/src/third/tsconfig.json", + `"declaration": true,`, + `"declaration": true, + "stripInternal": true,`, + ); } function stripInternalScenario(fs: vfs.FileSystem, removeCommentsDisabled?: boolean, jsDocStyle?: boolean) { @@ -410,7 +425,10 @@ describe("unittests:: tsbuild:: outFile::", () => { } stripInternalOfThird(fs); replaceText(fs, "/src/first/first_PART1.ts", "interface", `${internal} interface`); - appendText(fs, "/src/second/second_part1.ts", ` + appendText( + fs, + "/src/second/second_part1.ts", + ` class normalC { ${internal} constructor() { } ${internal} prop: string; @@ -435,7 +453,8 @@ ${internal} namespace internalOther.something { export class someClass {} } ${internal} import internalImport = internalNamespace.someClass; ${internal} type internalType = internalC; ${internal} const internalConst = 10; -${internal} enum internalEnum { a, b, c }`); +${internal} enum internalEnum { a, b, c }`, + ); } // Verify initial + incremental edits @@ -451,7 +470,7 @@ ${internal} enum internalEnum { a, b, c }`); modifyFs: fs => stripInternalScenario(fs, /*removeCommentsDisabled*/ true), modifyAgainFs: fs => replaceText(fs, "/src/first/first_PART1.ts", `/*@internal*/ interface`, "interface"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify ignore dtsChanged @@ -460,7 +479,7 @@ ${internal} enum internalEnum { a, b, c }`); modifyFs: fs => stripInternalScenario(fs, /*removeCommentsDisabled*/ false, /*jsDocStyle*/ true), modifyAgainFs: fs => replaceText(fs, "/src/first/first_PART1.ts", `/**@internal*/ interface`, "interface"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify ignore dtsChanged @@ -468,13 +487,18 @@ ${internal} enum internalEnum { a, b, c }`); subScenario: "stripInternal jsdoc style with comments emit enabled", modifyFs: fs => stripInternalScenario(fs, /*removeCommentsDisabled*/ true, /*jsDocStyle*/ true), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); describe("with three levels of project dependency", () => { function makeOneTwoThreeDependOrder(fs: vfs.FileSystem) { - replaceText(fs, "/src/second/tsconfig.json", "[", `[ - { "path": "../first", "prepend": true }`); + replaceText( + fs, + "/src/second/tsconfig.json", + "[", + `[ + { "path": "../first", "prepend": true }`, + ); replaceText(fs, "/src/third/tsconfig.json", `{ "path": "../first", "prepend": true },`, ""); } @@ -496,7 +520,7 @@ ${internal} enum internalEnum { a, b, c }`); modifyFs: fs => stripInternalWithDependentOrder(fs, /*removeCommentsDisabled*/ true), modifyAgainFs: fs => replaceText(fs, "/src/first/first_PART1.ts", `/*@internal*/ interface`, "interface"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify ignore dtsChanged @@ -505,7 +529,7 @@ ${internal} enum internalEnum { a, b, c }`); modifyFs: fs => stripInternalWithDependentOrder(fs, /*removeCommentsDisabled*/ false, /*jsDocStyle*/ true), modifyAgainFs: fs => replaceText(fs, "/src/first/first_PART1.ts", `/**@internal*/ interface`, "interface"), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // Verify ignore dtsChanged @@ -513,7 +537,7 @@ ${internal} enum internalEnum { a, b, c }`); subScenario: "stripInternal jsdoc style with comments emit enabled when one-two-three are prepended in order", modifyFs: fs => stripInternalWithDependentOrder(fs, /*removeCommentsDisabled*/ true, /*jsDocStyle*/ true), ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); }); @@ -522,7 +546,10 @@ ${internal} enum internalEnum { a, b, c }`); subScenario: "stripInternal baseline when internal is inside another internal", modifyFs: fs => { stripInternalOfThird(fs); - prependText(fs, "/src/first/first_PART1.ts", `namespace ts { + prependText( + fs, + "/src/first/first_PART1.ts", + `namespace ts { /* @internal */ /** * Subset of properties from SourceFile that are used in multiple utility functions @@ -549,11 +576,12 @@ ${internal} enum internalEnum { a, b, c }`); export interface SourceFile { someProp: string; } -}`); +}`, + ); }, ignoreDtsChanged: true, ignoreDtsUnchanged: true, - baselineOnly: true + baselineOnly: true, }); // only baseline @@ -561,7 +589,10 @@ ${internal} enum internalEnum { a, b, c }`); subScenario: "stripInternal when few members of enum are internal", modifyFs: fs => { stripInternalOfThird(fs); - prependText(fs, "/src/first/first_PART1.ts", `enum TokenFlags { + prependText( + fs, + "/src/first/first_PART1.ts", + `enum TokenFlags { None = 0, /* @internal */ PrecedingLineBreak = 1 << 0, @@ -583,11 +614,12 @@ ${internal} enum internalEnum { a, b, c }`); /* @internal */ NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator } -`); +`, + ); }, ignoreDtsChanged: true, ignoreDtsUnchanged: true, - baselineOnly: true + baselineOnly: true, }); verifyOutFileScenario({ @@ -598,31 +630,37 @@ ${internal} enum internalEnum { a, b, c }`); modifyFs: fs => { fs.writeFileSync("/src/first/first_PART1.ts", "/* @internal */ const A = 1;"); fs.writeFileSync("/src/third/third_part1.ts", "const B = 2;"); - fs.writeFileSync("/src/first/tsconfig.json", JSON.stringify({ - compilerOptions: { - composite: true, - declaration: true, - declarationMap: true, - skipDefaultLibCheck: true, - sourceMap: true, - outFile: "./bin/first-output.js" - }, - files: ["/src/first/first_PART1.ts"] - })); - fs.writeFileSync("/src/third/tsconfig.json", JSON.stringify({ - compilerOptions: { - ignoreDeprecations: "5.0", - composite: true, - declaration: true, - declarationMap: false, - stripInternal: true, - sourceMap: true, - outFile: "./thirdjs/output/third-output.js", - }, - references: [{ path: "../first", prepend: true }], - files: ["/src/third/third_part1.ts"] - })); - } + fs.writeFileSync( + "/src/first/tsconfig.json", + JSON.stringify({ + compilerOptions: { + composite: true, + declaration: true, + declarationMap: true, + skipDefaultLibCheck: true, + sourceMap: true, + outFile: "./bin/first-output.js", + }, + files: ["/src/first/first_PART1.ts"], + }), + ); + fs.writeFileSync( + "/src/third/tsconfig.json", + JSON.stringify({ + compilerOptions: { + ignoreDeprecations: "5.0", + composite: true, + declaration: true, + declarationMap: false, + stripInternal: true, + sourceMap: true, + outFile: "./thirdjs/output/third-output.js", + }, + references: [{ path: "../first", prepend: true }], + files: ["/src/third/third_part1.ts"], + }), + ); + }, }); }); @@ -636,7 +674,7 @@ ${internal} enum internalEnum { a, b, c }`); subScenario: "when source files are empty in the own file", modifyFs: makeThirdEmptySourceFile, ignoreDtsChanged: true, - baselineOnly: true + baselineOnly: true, }); // only baseline @@ -650,7 +688,7 @@ ${internal} enum internalEnum { a, b, c }`); }, ignoreDtsChanged: true, ignoreDtsUnchanged: true, - baselineOnly: true + baselineOnly: true, }); }); }); diff --git a/src/testRunner/unittests/tsbuild/outputPaths.ts b/src/testRunner/unittests/tsbuild/outputPaths.ts index 15686987c2239..5383e9129db69 100644 --- a/src/testRunner/unittests/tsbuild/outputPaths.ts +++ b/src/testRunner/unittests/tsbuild/outputPaths.ts @@ -7,7 +7,9 @@ import { verifyTsc, VerifyTscWithEditsInput, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsbuild - output file paths", () => { const noChangeProject: TestTscEdit = { @@ -24,7 +26,7 @@ describe("unittests:: tsbuild - output file paths", () => { verifyTsc({ scenario: "outputPaths", commandLineArgs: ["--b", "/src/tsconfig.json", "-v"], - ...input + ...input, }); it("verify getOutputFileNames", () => { @@ -34,82 +36,87 @@ describe("unittests:: tsbuild - output file paths", () => { ts.getOutputFileNames( ts.parseConfigFileWithSystem("/src/tsconfig.json", {}, /*extendedConfigCache*/ undefined, {}, sys, ts.noop)!, "/src/src/index.ts", - /*ignoreCase*/ false + /*ignoreCase*/ false, ), - expectedOuptutNames + expectedOuptutNames, ); }); } verify({ subScenario: "when rootDir is not specified", - fs: () => loadProjectFromFiles({ - "/src/src/index.ts": "export const x = 10;", - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { - outDir: "dist" - } - }) - }), + fs: () => + loadProjectFromFiles({ + "/src/src/index.ts": "export const x = 10;", + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { + outDir: "dist", + }, + }), + }), edits, }, ["/src/dist/index.js"]); verify({ subScenario: "when rootDir is not specified and is composite", - fs: () => loadProjectFromFiles({ - "/src/src/index.ts": "export const x = 10;", - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { - outDir: "dist", - composite: true - } - }) - }), + fs: () => + loadProjectFromFiles({ + "/src/src/index.ts": "export const x = 10;", + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { + outDir: "dist", + composite: true, + }, + }), + }), edits, }, ["/src/dist/src/index.js", "/src/dist/src/index.d.ts"]); verify({ subScenario: "when rootDir is specified", - fs: () => loadProjectFromFiles({ - "/src/src/index.ts": "export const x = 10;", - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { - outDir: "dist", - rootDir: "src" - } - }) - }), + fs: () => + loadProjectFromFiles({ + "/src/src/index.ts": "export const x = 10;", + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { + outDir: "dist", + rootDir: "src", + }, + }), + }), edits, }, ["/src/dist/index.js"]); verify({ subScenario: "when rootDir is specified but not all files belong to rootDir", - fs: () => loadProjectFromFiles({ - "/src/src/index.ts": "export const x = 10;", - "/src/types/type.ts": "export type t = string;", - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { - outDir: "dist", - rootDir: "src" - } - }) - }), + fs: () => + loadProjectFromFiles({ + "/src/src/index.ts": "export const x = 10;", + "/src/types/type.ts": "export type t = string;", + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { + outDir: "dist", + rootDir: "src", + }, + }), + }), edits, }, ["/src/dist/index.js"]); verify({ subScenario: "when rootDir is specified but not all files belong to rootDir and is composite", - fs: () => loadProjectFromFiles({ - "/src/src/index.ts": "export const x = 10;", - "/src/types/type.ts": "export type t = string;", - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { - outDir: "dist", - rootDir: "src", - composite: true - } - }) - }), + fs: () => + loadProjectFromFiles({ + "/src/src/index.ts": "export const x = 10;", + "/src/types/type.ts": "export type t = string;", + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { + outDir: "dist", + rootDir: "src", + composite: true, + }, + }), + }), edits, }, ["/src/dist/index.js", "/src/dist/index.d.ts"]); }); diff --git a/src/testRunner/unittests/tsbuild/publicApi.ts b/src/testRunner/unittests/tsbuild/publicApi.ts index 0359a62a7a42a..5c9f03001d789 100644 --- a/src/testRunner/unittests/tsbuild/publicApi.ts +++ b/src/testRunner/unittests/tsbuild/publicApi.ts @@ -10,7 +10,9 @@ import { TscCompileSystem, verifyTscBaseline, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsbuild:: Public API with custom transformers when passed to build", () => { let sys: TscCompileSystem; @@ -19,9 +21,9 @@ describe("unittests:: tsbuild:: Public API with custom transformers when passed "/src/tsconfig.json": JSON.stringify({ references: [ { path: "./shared/tsconfig.json" }, - { path: "./webpack/tsconfig.json" } + { path: "./webpack/tsconfig.json" }, ], - files: [] + files: [], }), "/src/shared/tsconfig.json": JSON.stringify({ compilerOptions: { composite: true }, @@ -35,7 +37,7 @@ export function f2() { } // trailing`, compilerOptions: { composite: true, }, - references: [{ path: "../shared/tsconfig.json" }] + references: [{ path: "../shared/tsconfig.json" }], }), "/src/webpack/index.ts": `export function f2() { } export class c2 { } @@ -62,10 +64,10 @@ export function f22() { } // trailing`, const { cb, getPrograms } = commandLineCallbacks(sys, /*originalReadCall*/ undefined); const buildHost = ts.createSolutionBuilderHost( sys, - /*createProgram*/ undefined, + /*createProgram*/ undefined, ts.createDiagnosticReporter(sys, /*pretty*/ true), ts.createBuilderStatusReporter(sys, /*pretty*/ true), - (errorCount, filesInError) => sys.write(ts.getErrorSummaryText(errorCount, filesInError, sys.newLine, sys)) + (errorCount, filesInError) => sys.write(ts.getErrorSummaryText(errorCount, filesInError, sys.newLine, sys)), ); buildHost.afterProgramEmitAndDiagnostics = cb; buildHost.afterEmitBundle = cb; @@ -88,7 +90,7 @@ ${baseFsPatch ? vfs.formatPatch(baseFsPatch) : ""} Output:: ${sys.output.join("")} -${patch ? vfs.formatPatch(patch) : ""}` +${patch ? vfs.formatPatch(patch) : ""}`, }; }; diff --git a/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts b/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts index 63d2fbaa35286..db3a0bcda429e 100644 --- a/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts +++ b/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts @@ -4,7 +4,7 @@ import { } from "../helpers/tsc"; import { loadProjectFromDisk, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsbuild:: with rootDir of project reference in parentDirectory", () => { @@ -38,13 +38,19 @@ describe("unittests:: tsbuild:: with rootDir of project reference in parentDirec fs: () => projFs, commandLineArgs: ["--b", "/src/src/main", "--verbose"], modifyFs: fs => { - fs.writeFileSync("/src/src/main/tsconfig.json", JSON.stringify({ - compilerOptions: { composite: true, outDir: "../../dist/" }, - references: [{ path: "../other" }] - })); - fs.writeFileSync("/src/src/other/tsconfig.json", JSON.stringify({ - compilerOptions: { composite: true, outDir: "../../dist/" }, - })); + fs.writeFileSync( + "/src/src/main/tsconfig.json", + JSON.stringify({ + compilerOptions: { composite: true, outDir: "../../dist/" }, + references: [{ path: "../other" }], + }), + ); + fs.writeFileSync( + "/src/src/other/tsconfig.json", + JSON.stringify({ + compilerOptions: { composite: true, outDir: "../../dist/" }, + }), + ); }, }); @@ -56,13 +62,19 @@ describe("unittests:: tsbuild:: with rootDir of project reference in parentDirec modifyFs: fs => { fs.renameSync("/src/src/main/tsconfig.json", "/src/src/main/tsconfig.main.json"); fs.renameSync("/src/src/other/tsconfig.json", "/src/src/other/tsconfig.other.json"); - fs.writeFileSync("/src/src/main/tsconfig.main.json", JSON.stringify({ - compilerOptions: { composite: true, outDir: "../../dist/" }, - references: [{ path: "../other/tsconfig.other.json" }] - })); - fs.writeFileSync("/src/src/other/tsconfig.other.json", JSON.stringify({ - compilerOptions: { composite: true, outDir: "../../dist/" }, - })); + fs.writeFileSync( + "/src/src/main/tsconfig.main.json", + JSON.stringify({ + compilerOptions: { composite: true, outDir: "../../dist/" }, + references: [{ path: "../other/tsconfig.other.json" }], + }), + ); + fs.writeFileSync( + "/src/src/other/tsconfig.other.json", + JSON.stringify({ + compilerOptions: { composite: true, outDir: "../../dist/" }, + }), + ); }, }); }); diff --git a/src/testRunner/unittests/tsbuild/resolveJsonModule.ts b/src/testRunner/unittests/tsbuild/resolveJsonModule.ts index 7275c671f83ad..ceac563a00a7f 100644 --- a/src/testRunner/unittests/tsbuild/resolveJsonModule.ts +++ b/src/testRunner/unittests/tsbuild/resolveJsonModule.ts @@ -3,7 +3,10 @@ import { noChangeOnlyRuns, verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromDisk, replaceText } from "../helpers/vfs"; +import { + loadProjectFromDisk, + replaceText, +} from "../helpers/vfs"; describe("unittests:: tsbuild:: with resolveJsonModule option on project resolveJsonModuleAndComposite", () => { let projFs: vfs.FileSystem; @@ -37,9 +40,12 @@ describe("unittests:: tsbuild:: with resolveJsonModule option on project resolve modifyFs: fs => { fs.rimrafSync("/src/src/hello.json"); fs.writeFileSync("/src/src/index.json", JSON.stringify({ hello: "world" })); - fs.writeFileSync("/src/src/index.ts", `import hello from "./index.json" + fs.writeFileSync( + "/src/src/index.ts", + `import hello from "./index.json" -export default hello.hello`); +export default hello.hello`, + ); }, }); @@ -63,7 +69,7 @@ export default hello.hello`); fs: () => projFs, commandLineArgs: ["--b", "src/tsconfig_withFiles.json", "--verbose", "--explainFiles"], modifyFs: fs => replaceText(fs, "src/tsconfig_withFiles.json", `"composite": true,`, `"composite": true, "sourceMap": true,`), - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); verifyTsc({ @@ -72,7 +78,7 @@ export default hello.hello`); fs: () => projFs, commandLineArgs: ["--b", "src/tsconfig_withFiles.json", "--verbose"], modifyFs: fs => replaceText(fs, "src/tsconfig_withFiles.json", `"outDir": "dist",`, ""), - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); }); @@ -82,6 +88,6 @@ describe("unittests:: tsbuild:: with resolveJsonModule option on project importJ subScenario: "importing json module from project reference", fs: () => loadProjectFromDisk("tests/projects/importJsonFromProjectReference"), commandLineArgs: ["--b", "src/tsconfig.json", "--verbose", "--explainFiles"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); }); diff --git a/src/testRunner/unittests/tsbuild/roots.ts b/src/testRunner/unittests/tsbuild/roots.ts index 6d824635fc08d..0be83bc907af9 100644 --- a/src/testRunner/unittests/tsbuild/roots.ts +++ b/src/testRunner/unittests/tsbuild/roots.ts @@ -1,22 +1,27 @@ -import { dedent } from "../../_namespaces/Utils"; +import { + dedent, +} from "../../_namespaces/Utils"; import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsbuild:: roots::", () => { verifyTsc({ scenario: "roots", subScenario: `when two root files are consecutive`, commandLineArgs: ["--b", "/src/tsconfig.json", "-v"], - fs: () => loadProjectFromFiles({ - "/src/file1.ts": `export const x = "hello";`, - "/src/file2.ts": `export const y = "world";`, - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true }, - include: ["*.ts"] - }) - }), + fs: () => + loadProjectFromFiles({ + "/src/file1.ts": `export const x = "hello";`, + "/src/file2.ts": `export const y = "world";`, + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + include: ["*.ts"], + }), + }), edits: [{ caption: "delete file1", edit: fs => { @@ -31,16 +36,17 @@ describe("unittests:: tsbuild:: roots::", () => { scenario: "roots", subScenario: `when multiple root files are consecutive`, commandLineArgs: ["--b", "/src/tsconfig.json", "-v"], - fs: () => loadProjectFromFiles({ - "/src/file1.ts": `export const x = "hello";`, - "/src/file2.ts": `export const y = "world";`, - "/src/file3.ts": `export const y = "world";`, - "/src/file4.ts": `export const y = "world";`, - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true }, - include: ["*.ts"] - }) - }), + fs: () => + loadProjectFromFiles({ + "/src/file1.ts": `export const x = "hello";`, + "/src/file2.ts": `export const y = "world";`, + "/src/file3.ts": `export const y = "world";`, + "/src/file4.ts": `export const y = "world";`, + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + include: ["*.ts"], + }), + }), edits: [{ caption: "delete file1", edit: fs => { @@ -55,18 +61,19 @@ describe("unittests:: tsbuild:: roots::", () => { scenario: "roots", subScenario: `when files are not consecutive`, commandLineArgs: ["--b", "/src/tsconfig.json", "-v"], - fs: () => loadProjectFromFiles({ - "/src/file1.ts": `export const x = "hello";`, - "/src/random.d.ts": `export const random = "world";`, - "/src/file2.ts": dedent` + fs: () => + loadProjectFromFiles({ + "/src/file1.ts": `export const x = "hello";`, + "/src/random.d.ts": `export const random = "world";`, + "/src/file2.ts": dedent` import { random } from "./random"; export const y = "world"; `, - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true }, - include: ["file*.ts"] - }) - }), + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + include: ["file*.ts"], + }), + }), edits: [{ caption: "delete file1", edit: fs => { @@ -81,31 +88,32 @@ describe("unittests:: tsbuild:: roots::", () => { scenario: "roots", subScenario: `when consecutive and non consecutive are mixed`, commandLineArgs: ["--b", "/src/tsconfig.json", "-v"], - fs: () => loadProjectFromFiles({ - "/src/file1.ts": `export const x = "hello";`, - "/src/file2.ts": `export const y = "world";`, - "/src/random.d.ts": `export const random = "hello";`, - "/src/nonconsecutive.ts": dedent` + fs: () => + loadProjectFromFiles({ + "/src/file1.ts": `export const x = "hello";`, + "/src/file2.ts": `export const y = "world";`, + "/src/random.d.ts": `export const random = "hello";`, + "/src/nonconsecutive.ts": dedent` import { random } from "./random"; export const nonConsecutive = "hello"; `, - "/src/random1.d.ts": `export const random = "hello";`, - "/src/asArray1.ts": dedent` + "/src/random1.d.ts": `export const random = "hello";`, + "/src/asArray1.ts": dedent` import { random } from "./random1"; export const x = "hello"; `, - "/src/asArray2.ts": `export const x = "hello";`, - "/src/asArray3.ts": `export const x = "hello";`, - "/src/random2.d.ts": `export const random = "hello";`, - "/src/anotherNonConsecutive.ts": dedent` + "/src/asArray2.ts": `export const x = "hello";`, + "/src/asArray3.ts": `export const x = "hello";`, + "/src/random2.d.ts": `export const random = "hello";`, + "/src/anotherNonConsecutive.ts": dedent` import { random } from "./random2"; export const nonConsecutive = "hello"; `, - "/src/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true }, - include: ["file*.ts", "nonconsecutive*.ts", "asArray*.ts", "anotherNonConsecutive.ts"] - }) - }), + "/src/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + include: ["file*.ts", "nonconsecutive*.ts", "asArray*.ts", "anotherNonConsecutive.ts"], + }), + }), edits: [{ caption: "delete file1", edit: fs => { @@ -115,4 +123,4 @@ describe("unittests:: tsbuild:: roots::", () => { }, }], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuild/sample.ts b/src/testRunner/unittests/tsbuild/sample.ts index 3eb0f4595bb2f..6bea86bc8f002 100644 --- a/src/testRunner/unittests/tsbuild/sample.ts +++ b/src/testRunner/unittests/tsbuild/sample.ts @@ -2,8 +2,12 @@ import * as fakes from "../../_namespaces/fakes"; import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; import * as vfs from "../../_namespaces/vfs"; -import { libContent } from "../helpers/contents"; -import { createSolutionBuilderHostForBaseline } from "../helpers/solutionBuilder"; +import { + libContent, +} from "../helpers/contents"; +import { + createSolutionBuilderHostForBaseline, +} from "../helpers/solutionBuilder"; import { noChangeOnlyRuns, noChangeRun, @@ -14,9 +18,11 @@ import { verifyTscCompileLike, } from "../helpers/tsc"; import { - appendText, loadProjectFromDisk, - loadProjectFromFiles, prependText, - replaceText + appendText, + loadProjectFromDisk, + loadProjectFromFiles, + prependText, + replaceText, } from "../helpers/vfs"; import { changeToHostTrackingWrittenFiles, @@ -42,7 +48,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { function getTsBuildProjectFile(project: string, file: string): File { return { path: getTsBuildProjectFilePath(project, file), - content: projFs.readFileSync(`/src/${project}/${file}`, "utf8")! + content: projFs.readFileSync(`/src/${project}/${file}`, "utf8")!, }; } @@ -63,10 +69,14 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { subScenario: "builds correctly when outDir is specified", fs: () => projFs, commandLineArgs: ["--b", "/src/tests"], - modifyFs: fs => fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ - compilerOptions: { composite: true, declaration: true, sourceMap: true, outDir: "outDir" }, - references: [{ path: "../core" }] - })), + modifyFs: fs => + fs.writeFileSync( + "/src/logic/tsconfig.json", + JSON.stringify({ + compilerOptions: { composite: true, declaration: true, sourceMap: true, outDir: "outDir" }, + references: [{ path: "../core" }], + }), + ), }); verifyTsc({ @@ -74,10 +84,14 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { subScenario: "builds correctly when declarationDir is specified", fs: () => projFs, commandLineArgs: ["--b", "/src/tests"], - modifyFs: fs => fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ - compilerOptions: { composite: true, declaration: true, sourceMap: true, declarationDir: "out/decls" }, - references: [{ path: "../core" }] - })), + modifyFs: fs => + fs.writeFileSync( + "/src/logic/tsconfig.json", + JSON.stringify({ + compilerOptions: { composite: true, declaration: true, sourceMap: true, declarationDir: "out/decls" }, + references: [{ path: "../core" }], + }), + ), }); verifyTsc({ @@ -104,7 +118,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { subScenario: "removes all files it built", fs: getSampleFsAfterBuild, commandLineArgs: ["--b", "/src/tests", "--clean"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); verifyTscCompileLike(testTscCompileLike, { @@ -116,7 +130,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const buildHost = createSolutionBuilderHostForBaseline(sys); const builder = ts.createSolutionBuilder(buildHost, ["/src/third/tsconfig.json"], {}); sys.exit(builder.clean("/src/logic")); - } + }, }); verifyTscCompileLike(testTscCompileLike, { @@ -128,7 +142,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const buildHost = createSolutionBuilderHostForBaseline(sys); const builder = ts.createSolutionBuilder(buildHost, ["/src/third/tsconfig.json"], {}); sys.exit(builder.clean("/src/logic2")); - } + }, }); }); @@ -138,7 +152,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { subScenario: "always builds under with force option", fs: () => projFs, commandLineArgs: ["--b", "/src/tests", "--force"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); }); @@ -166,7 +180,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { fs.writeFileSync("/lib/lib.es2020.full.d.ts", libContent); }, }, - ] + ], }); verifyTsc({ @@ -182,7 +196,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { fs.utimesSync("/src/core/index.ts", time, time); }, }, - ] + ], }); verifyTsc({ @@ -199,7 +213,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { caption: "Enable declarationMap", edit: fs => replaceText(fs, "/src/core/tsconfig.json", `"declarationMap": false,`, `"declarationMap": true,`), }, - ] + ], }); verifyTsc({ @@ -219,16 +233,17 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { verifyTsc({ scenario: "sample1", subScenario: "tsbuildinfo has error", - fs: () => loadProjectFromFiles({ - "/src/project/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": "{}", - "/src/project/tsconfig.tsbuildinfo": "Some random string", - }), + fs: () => + loadProjectFromFiles({ + "/src/project/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": "{}", + "/src/project/tsconfig.tsbuildinfo": "Some random string", + }), commandLineArgs: ["--b", "src/project", "-i", "-v"], edits: [{ caption: "tsbuildinfo written has error", edit: fs => prependText(fs, "/src/project/tsconfig.tsbuildinfo", "Some random string"), - }] + }], }); verifyTscCompileLike(testTscCompileLike, { @@ -241,7 +256,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const buildHost = createSolutionBuilderHostForBaseline(sys, "FakeTSCurrentVersion"); const builder = ts.createSolutionBuilder(buildHost, ["/src/tests"], { verbose: true }); sys.exit(builder.build()); - } + }, }); verifyTscCompileLike(testTscCompileLike, { @@ -275,8 +290,8 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { }, edits: [{ caption: "incremental-declaration-changes", - edit: fs => fs.writeFileSync("/src/tests/tsconfig.base.json", JSON.stringify({ compilerOptions: {} })) - }] + edit: fs => fs.writeFileSync("/src/tests/tsconfig.base.json", JSON.stringify({ compilerOptions: {} })), + }], }); verifyTscCompileLike(testTscCompileLike, { @@ -288,7 +303,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const buildHost = createSolutionBuilderHostForBaseline(sys); const builder = ts.createSolutionBuilder(buildHost, ["/src/tests"], {}); sys.exit(builder.build("/src/logic/tsconfig.json")); - } + }, }); verifyTscCompileLike(testTscCompileLike, { @@ -300,7 +315,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const buildHost = createSolutionBuilderHostForBaseline(sys); const builder = ts.createSolutionBuilder(buildHost, ["/src/tests"], {}); sys.exit(builder.build("/src/logic2/tsconfig.json")); - } + }, }); it("building using getNextInvalidatedProject", () => { @@ -317,12 +332,17 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const system = changeToHostTrackingWrittenFiles( fakes.patchHostForBuildInfoReadWrite( createWatchedSystem([ - coreConfig, coreIndex, coreDecl, coreAnotherModule, - logicConfig, logicIndex, - testsConfig, testsIndex, - libFile - ]) - ) + coreConfig, + coreIndex, + coreDecl, + coreAnotherModule, + logicConfig, + logicIndex, + testsConfig, + testsIndex, + libFile, + ]), + ), ); const host = createSolutionBuilderHostForBaseline(system); @@ -331,7 +351,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { baselineState(); verifyBuildNextResult(); // core verifyBuildNextResult(); // logic - verifyBuildNextResult();// tests + verifyBuildNextResult(); // tests verifyBuildNextResult(); // All Done Harness.Baseline.runBaseline(`tsbuild/sample1/building-using-getNextInvalidatedProject.js`, baseline.join("\r\n")); @@ -359,7 +379,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const buildHost = createSolutionBuilderHostForBaseline(sys); const builder = ts.createSolutionBuilder(buildHost, ["/src/tests"], { verbose: true }); sys.exit(builder.buildReferences("/src/tests")); - } + }, }); }); @@ -370,7 +390,7 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { fs: () => projFs, commandLineArgs: ["--b", "/src/tests", "--verbose"], modifyFs: fs => replaceText(fs, "/src/logic/index.ts", "c.multiply(10, 15)", `c.muitply()`), - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); }); @@ -389,12 +409,17 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const system = changeToHostTrackingWrittenFiles( fakes.patchHostForBuildInfoReadWrite( createWatchedSystem([ - coreConfig, coreIndex, coreDecl, coreAnotherModule, - logicConfig, logicIndex, - testsConfig, testsIndex, - libFile - ]) - ) + coreConfig, + coreIndex, + coreDecl, + coreAnotherModule, + logicConfig, + logicIndex, + testsConfig, + testsIndex, + libFile, + ]), + ), ); const host = createSolutionBuilderHostForBaseline(system); @@ -439,13 +464,23 @@ describe("unittests:: tsbuild:: on 'sample1' project", () => { const coreChanges: TestTscEdit[] = [ { caption: "incremental-declaration-changes", - edit: fs => appendText(fs, "/src/core/index.ts", ` -export class someClass { }`), + edit: fs => + appendText( + fs, + "/src/core/index.ts", + ` +export class someClass { }`, + ), }, { caption: "incremental-declaration-doesnt-change", - edit: fs => appendText(fs, "/src/core/index.ts", ` -class someClass2 { }`), + edit: fs => + appendText( + fs, + "/src/core/index.ts", + ` +class someClass2 { }`, + ), }, noChangeRun, ]; @@ -456,21 +491,21 @@ class someClass2 { }`), subScenario: "listFiles", fs: () => projFs, commandLineArgs: ["--b", "/src/tests", "--listFiles"], - edits: coreChanges + edits: coreChanges, }); verifyTsc({ scenario: "sample1", subScenario: "listEmittedFiles", fs: () => projFs, commandLineArgs: ["--b", "/src/tests", "--listEmittedFiles"], - edits: coreChanges + edits: coreChanges, }); verifyTsc({ scenario: "sample1", subScenario: "explainFiles", fs: () => projFs, commandLineArgs: ["--b", "/src/tests", "--explainFiles", "--v"], - edits: coreChanges + edits: coreChanges, }); }); @@ -486,8 +521,14 @@ class someClass2 { }`), ...coreChanges, { caption: "when logic config changes declaration dir", - edit: fs => replaceText(fs, "/src/logic/tsconfig.json", `"declaration": true,`, `"declaration": true, - "declarationDir": "decls",`), + edit: fs => + replaceText( + fs, + "/src/logic/tsconfig.json", + `"declaration": true,`, + `"declaration": true, + "declarationDir": "decls",`, + ), }, noChangeRun, ], @@ -497,11 +538,17 @@ class someClass2 { }`), scenario: "sample1", subScenario: "when logic specifies tsBuildInfoFile", fs: () => projFs, - modifyFs: fs => replaceText(fs, "/src/logic/tsconfig.json", `"composite": true,`, `"composite": true, - "tsBuildInfoFile": "ownFile.tsbuildinfo",`), + modifyFs: fs => + replaceText( + fs, + "/src/logic/tsconfig.json", + `"composite": true,`, + `"composite": true, + "tsBuildInfoFile": "ownFile.tsbuildinfo",`, + ), commandLineArgs: ["--b", "/src/tests", "--verbose"], baselineSourceMap: true, - baselineReadFileCalls: true + baselineReadFileCalls: true, }); verifyTsc({ @@ -509,12 +556,16 @@ class someClass2 { }`), fs: () => projFs, scenario: "sample1", commandLineArgs: ["--b", "/src/core", "--verbose"], - modifyFs: fs => fs.writeFileSync("/src/core/tsconfig.json", `{ + modifyFs: fs => + fs.writeFileSync( + "/src/core/tsconfig.json", + `{ "compilerOptions": { "incremental": true, "skipDefaultLibCheck": true } -}`), +}`, + ), edits: [{ caption: "incremental-declaration-changes", edit: fs => replaceText(fs, "/src/core/tsconfig.json", `"incremental": true,`, `"incremental": true, "declaration": true,`), @@ -527,19 +578,28 @@ class someClass2 { }`), scenario: "sample1", commandLineArgs: ["--b", "/src/core", "--verbose"], modifyFs: fs => { - fs.writeFileSync("/lib/lib.esnext.full.d.ts", `/// -/// `); + fs.writeFileSync( + "/lib/lib.esnext.full.d.ts", + `/// +/// `, + ); fs.writeFileSync("/lib/lib.esnext.d.ts", libContent); - fs.writeFileSync("/lib/lib.d.ts", `/// -/// `); - fs.writeFileSync("/src/core/tsconfig.json", `{ + fs.writeFileSync( + "/lib/lib.d.ts", + `/// +/// `, + ); + fs.writeFileSync( + "/src/core/tsconfig.json", + `{ "compilerOptions": { "incremental": true, "listFiles": true, "listEmittedFiles": true, "target": "esnext", } -}`); +}`, + ); }, edits: [{ caption: "incremental-declaration-changes", @@ -552,12 +612,16 @@ class someClass2 { }`), fs: () => projFs, scenario: "sample1", commandLineArgs: ["--b", "/src/core", "--verbose"], - modifyFs: fs => fs.writeFileSync("/src/core/tsconfig.json", `{ + modifyFs: fs => + fs.writeFileSync( + "/src/core/tsconfig.json", + `{ "compilerOptions": { "incremental": true, "module": "commonjs" } -}`), +}`, + ), edits: [{ caption: "incremental-declaration-changes", edit: fs => replaceText(fs, "/src/core/tsconfig.json", `"module": "commonjs"`, `"module": "amd"`), @@ -569,7 +633,10 @@ class someClass2 { }`), fs: () => projFs, scenario: "sample1", commandLineArgs: ["--b", "/src/tests", "--verbose"], - modifyFs: fs => fs.writeFileSync("/src/tests/tsconfig.json", `{ + modifyFs: fs => + fs.writeFileSync( + "/src/tests/tsconfig.json", + `{ "references": [ { "path": "../core" }, { "path": "../logic" } @@ -582,7 +649,8 @@ class someClass2 { }`), "skipDefaultLibCheck": true, "esModuleInterop": false } -}`), +}`, + ), edits: [{ caption: "incremental-declaration-changes", edit: fs => replaceText(fs, "/src/tests/tsconfig.json", `"esModuleInterop": false`, `"esModuleInterop": true`), @@ -595,12 +663,15 @@ class someClass2 { }`), fs: () => projFs, commandLineArgs: ["--b", "/src/tests", "--v"], modifyFs: fs => { - fs.writeFileSync("/src/core/tsconfig.json", JSON.stringify({ - compilerOptions: { composite: true }, - files: ["anotherModule.ts", "index.ts", "some_decl.d.ts"] - })); + fs.writeFileSync( + "/src/core/tsconfig.json", + JSON.stringify({ + compilerOptions: { composite: true }, + files: ["anotherModule.ts", "index.ts", "some_decl.d.ts"], + }), + ); fs.unlinkSync("/src/core/anotherModule.ts"); - } + }, }); verifyTsc({ @@ -609,12 +680,15 @@ class someClass2 { }`), fs: () => projFs, commandLineArgs: ["--b", "/src/tests", "--v", "--f"], modifyFs: fs => { - fs.writeFileSync("/src/core/tsconfig.json", JSON.stringify({ - compilerOptions: { composite: true }, - files: ["anotherModule.ts", "index.ts", "some_decl.d.ts"] - })); + fs.writeFileSync( + "/src/core/tsconfig.json", + JSON.stringify({ + compilerOptions: { composite: true }, + files: ["anotherModule.ts", "index.ts", "some_decl.d.ts"], + }), + ); fs.unlinkSync("/src/core/anotherModule.ts"); - } + }, }); }); }); diff --git a/src/testRunner/unittests/tsbuild/transitiveReferences.ts b/src/testRunner/unittests/tsbuild/transitiveReferences.ts index 37693c8eb5d5a..b75a98f0df8a1 100644 --- a/src/testRunner/unittests/tsbuild/transitiveReferences.ts +++ b/src/testRunner/unittests/tsbuild/transitiveReferences.ts @@ -2,7 +2,9 @@ import * as vfs from "../../_namespaces/vfs"; import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromDisk } from "../helpers/vfs"; +import { + loadProjectFromDisk, +} from "../helpers/vfs"; describe("unittests:: tsbuild:: when project reference is referenced transitively", () => { let projFs: vfs.FileSystem; @@ -14,16 +16,22 @@ describe("unittests:: tsbuild:: when project reference is referenced transitivel }); function modifyFsBTsToNonRelativeImport(fs: vfs.FileSystem, moduleResolution: "node" | "classic") { - fs.writeFileSync("/src/b.ts", `import {A} from 'a'; -export const b = new A();`); - fs.writeFileSync("/src/tsconfig.b.json", JSON.stringify({ - compilerOptions: { - composite: true, - moduleResolution - }, - files: ["b.ts"], - references: [{ path: "tsconfig.a.json" }] - })); + fs.writeFileSync( + "/src/b.ts", + `import {A} from 'a'; +export const b = new A();`, + ); + fs.writeFileSync( + "/src/tsconfig.b.json", + JSON.stringify({ + compilerOptions: { + composite: true, + moduleResolution, + }, + files: ["b.ts"], + references: [{ path: "tsconfig.a.json" }], + }), + ); } verifyTsc({ diff --git a/src/testRunner/unittests/tsbuildWatch/configFileErrors.ts b/src/testRunner/unittests/tsbuildWatch/configFileErrors.ts index 4059cfce11477..1c47250803a00 100644 --- a/src/testRunner/unittests/tsbuildWatch/configFileErrors.ts +++ b/src/testRunner/unittests/tsbuildWatch/configFileErrors.ts @@ -1,5 +1,9 @@ -import { dedent } from "../../_namespaces/Utils"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + dedent, +} from "../../_namespaces/Utils"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { createWatchedSystem, libFile, @@ -9,13 +13,14 @@ describe("unittests:: tsbuildWatch:: watchMode:: configFileErrors:: reports synt verifyTscWatch({ scenario: "configFileErrors", subScenario: "reports syntax errors in config file", - sys: () => createWatchedSystem( - [ - { path: `/user/username/projects/myproject/a.ts`, content: "export function foo() { }" }, - { path: `/user/username/projects/myproject/b.ts`, content: "export function bar() { }" }, - { - path: `/user/username/projects/myproject/tsconfig.json`, - content: dedent` + sys: () => + createWatchedSystem( + [ + { path: `/user/username/projects/myproject/a.ts`, content: "export function foo() { }" }, + { path: `/user/username/projects/myproject/b.ts`, content: "export function bar() { }" }, + { + path: `/user/username/projects/myproject/tsconfig.json`, + content: dedent` { "compilerOptions": { "composite": true, @@ -24,18 +29,23 @@ describe("unittests:: tsbuildWatch:: watchMode:: configFileErrors:: reports synt "a.ts" "b.ts" ] -}` - }, - libFile - ], - { currentDirectory: "/user/username/projects/myproject" } - ), +}`, + }, + libFile, + ], + { currentDirectory: "/user/username/projects/myproject" }, + ), commandLineArgs: ["--b", "-w"], edits: [ { caption: "reports syntax errors after change to config file", - edit: sys => sys.replaceFileText(`/user/username/projects/myproject/tsconfig.json`, ",", `, - "declaration": true,`), + edit: sys => + sys.replaceFileText( + `/user/username/projects/myproject/tsconfig.json`, + ",", + `, + "declaration": true,`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // build the project }, { @@ -50,12 +60,16 @@ describe("unittests:: tsbuildWatch:: watchMode:: configFileErrors:: reports synt }, { caption: "builds after fixing config file errors", - edit: sys => sys.writeFile(`/user/username/projects/myproject/tsconfig.json`, JSON.stringify({ - compilerOptions: { composite: true, declaration: true }, - files: ["a.ts", "b.ts"] - })), + edit: sys => + sys.writeFile( + `/user/username/projects/myproject/tsconfig.json`, + JSON.stringify({ + compilerOptions: { composite: true, declaration: true }, + files: ["a.ts", "b.ts"], + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // build the project - } - ] + }, + ], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/demo.ts b/src/testRunner/unittests/tsbuildWatch/demo.ts index 03b36bcd39cb4..891c57e593fa7 100644 --- a/src/testRunner/unittests/tsbuildWatch/demo.ts +++ b/src/testRunner/unittests/tsbuildWatch/demo.ts @@ -1,5 +1,9 @@ -import { libContent } from "../helpers/contents"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + libContent, +} from "../helpers/contents"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { createWatchedSystem, File, @@ -39,15 +43,18 @@ describe("unittests:: tsbuildWatch:: watchMode:: with demo project", () => { commandLineArgs: ["-b", "-w", "-verbose"], sys: () => { const sys = createWatchedSystem(allFiles, { currentDirectory: projectLocation }); - sys.writeFile(coreFiles[0].path, coreFiles[0].content.replace( - "}", - `}, + sys.writeFile( + coreFiles[0].path, + coreFiles[0].content.replace( + "}", + `}, "references": [ { "path": "../zoo" } - ]` - )); + ]`, + ), + ); return sys; }, edits: [ @@ -58,8 +65,8 @@ describe("unittests:: tsbuildWatch:: watchMode:: with demo project", () => { sys.runQueuedTimeoutCallbacks(); // build core sys.runQueuedTimeoutCallbacks(); // build animals, zoo and solution }, - } - ] + }, + ], }); verifyTscWatch({ @@ -68,20 +75,27 @@ describe("unittests:: tsbuildWatch:: watchMode:: with demo project", () => { commandLineArgs: ["-b", "-w", "-verbose"], sys: () => { const sys = createWatchedSystem(allFiles, { currentDirectory: projectLocation }); - sys.writeFile(coreFiles[1].path, `import * as A from '../animals'; -${coreFiles[1].content}`); + sys.writeFile( + coreFiles[1].path, + `import * as A from '../animals'; +${coreFiles[1].content}`, + ); return sys; }, edits: [ { caption: "Prepend a line", - edit: sys => sys.writeFile(coreFiles[1].path, ` + edit: sys => + sys.writeFile( + coreFiles[1].path, + ` import * as A from '../animals'; -${coreFiles[1].content}`), +${coreFiles[1].content}`, + ), // build core timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); function subProjectFiles(subProject: string, fileNames: readonly string[]): File[] { @@ -91,4 +105,4 @@ ${coreFiles[1].content}`), function projectFile(fileName: string): File { return getTsBuildProjectFile("demo", fileName); } -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/libraryResolution.ts b/src/testRunner/unittests/tsbuildWatch/libraryResolution.ts index a6391cdb9b7ee..dd2c4f0e2ac2e 100644 --- a/src/testRunner/unittests/tsbuildWatch/libraryResolution.ts +++ b/src/testRunner/unittests/tsbuildWatch/libraryResolution.ts @@ -1,5 +1,9 @@ -import { getSysForLibResolution } from "../helpers/libraryResolution"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + getSysForLibResolution, +} from "../helpers/libraryResolution"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; describe("unittests:: tsbuildWatch:: watchMode:: libraryResolution:: library file resolution", () => { function verify(libRedirection?: true) { diff --git a/src/testRunner/unittests/tsbuildWatch/moduleResolution.ts b/src/testRunner/unittests/tsbuildWatch/moduleResolution.ts index 141494295eb71..9c2a9a7281456 100644 --- a/src/testRunner/unittests/tsbuildWatch/moduleResolution.ts +++ b/src/testRunner/unittests/tsbuildWatch/moduleResolution.ts @@ -1,5 +1,9 @@ -import { dedent } from "../../_namespaces/Utils"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + dedent, +} from "../../_namespaces/Utils"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { createWatchedSystem, libFile, @@ -9,42 +13,43 @@ describe("unittests:: tsbuildWatch:: watchMode:: moduleResolution", () => { verifyTscWatch({ scenario: "moduleResolutionCache", subScenario: "handles the cache correctly when two projects use different module resolution settings", - sys: () => createWatchedSystem( - [ - { path: `/user/username/projects/myproject/project1/index.ts`, content: `import { foo } from "file";` }, - { path: `/user/username/projects/myproject/project1/node_modules/file/index.d.ts`, content: "export const foo = 10;" }, - { - path: `/user/username/projects/myproject/project1/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { composite: true, types: ["foo", "bar"] }, - files: ["index.ts"] - }) - }, - { path: `/user/username/projects/myproject/project2/index.ts`, content: `import { foo } from "file";` }, - { path: `/user/username/projects/myproject/project2/file.d.ts`, content: "export const foo = 10;" }, - { - path: `/user/username/projects/myproject/project2/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { composite: true, types: ["foo"], moduleResolution: "classic" }, - files: ["index.ts"] - }) - }, - { path: `/user/username/projects/myproject/node_modules/@types/foo/index.d.ts`, content: "export const foo = 10;" }, - { path: `/user/username/projects/myproject/node_modules/@types/bar/index.d.ts`, content: "export const bar = 10;" }, - { - path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ - files: [], - references: [ - { path: "./project1" }, - { path: "./project2" } - ] - }) - }, - libFile - ], - { currentDirectory: "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + [ + { path: `/user/username/projects/myproject/project1/index.ts`, content: `import { foo } from "file";` }, + { path: `/user/username/projects/myproject/project1/node_modules/file/index.d.ts`, content: "export const foo = 10;" }, + { + path: `/user/username/projects/myproject/project1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, types: ["foo", "bar"] }, + files: ["index.ts"], + }), + }, + { path: `/user/username/projects/myproject/project2/index.ts`, content: `import { foo } from "file";` }, + { path: `/user/username/projects/myproject/project2/file.d.ts`, content: "export const foo = 10;" }, + { + path: `/user/username/projects/myproject/project2/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, types: ["foo"], moduleResolution: "classic" }, + files: ["index.ts"], + }), + }, + { path: `/user/username/projects/myproject/node_modules/@types/foo/index.d.ts`, content: "export const foo = 10;" }, + { path: `/user/username/projects/myproject/node_modules/@types/bar/index.d.ts`, content: "export const bar = 10;" }, + { + path: `/user/username/projects/myproject/tsconfig.json`, + content: JSON.stringify({ + files: [], + references: [ + { path: "./project1" }, + { path: "./project2" }, + ], + }), + }, + libFile, + ], + { currentDirectory: "/user/username/projects/myproject" }, + ), commandLineArgs: ["--b", "-w", "-v"], edits: [ { @@ -52,71 +57,72 @@ describe("unittests:: tsbuildWatch:: watchMode:: moduleResolution", () => { edit: sys => sys.appendFile(`/user/username/projects/myproject/project1/index.ts`, "const bar = 10;"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // build project1 and solution }, - ] + ], }); verifyTscWatch({ scenario: "moduleResolution", subScenario: `resolves specifier in output declaration file from referenced project correctly with cts and mts extensions`, - sys: () => createWatchedSystem([ - { - path: `/user/username/projects/myproject/packages/pkg1/package.json`, - content: JSON.stringify({ - name: "pkg1", - version: "1.0.0", - main: "build/index.js", - type: "module" - }) - }, - { - path: `/user/username/projects/myproject/packages/pkg1/index.ts`, - content: dedent` + sys: () => + createWatchedSystem([ + { + path: `/user/username/projects/myproject/packages/pkg1/package.json`, + content: JSON.stringify({ + name: "pkg1", + version: "1.0.0", + main: "build/index.js", + type: "module", + }), + }, + { + path: `/user/username/projects/myproject/packages/pkg1/index.ts`, + content: dedent` import type { TheNum } from 'pkg2' - export const theNum: TheNum = 42;` - }, - { - path: `/user/username/projects/myproject/packages/pkg1/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { - outDir: "build", - module: "node16", - }, - references: [{ path: "../pkg2" }] - }) - }, - { - path: `/user/username/projects/myproject/packages/pkg2/const.cts`, - content: `export type TheNum = 42;` - }, - { - path: `/user/username/projects/myproject/packages/pkg2/index.ts`, - content: `export type { TheNum } from './const.cjs';` - }, - { - path: `/user/username/projects/myproject/packages/pkg2/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { - composite: true, - outDir: "build", - module: "node16", - } - }) - }, - { - path: `/user/username/projects/myproject/packages/pkg2/package.json`, - content: JSON.stringify({ - name: "pkg2", - version: "1.0.0", - main: "build/index.js", - type: "module" - }) - }, - { - path: `/user/username/projects/myproject/node_modules/pkg2`, - symLink: `/user/username/projects/myproject/packages/pkg2`, - }, - { ...libFile, path: `/a/lib/lib.es2022.full.d.ts` } - ], { currentDirectory: "/user/username/projects/myproject" }), + export const theNum: TheNum = 42;`, + }, + { + path: `/user/username/projects/myproject/packages/pkg1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + outDir: "build", + module: "node16", + }, + references: [{ path: "../pkg2" }], + }), + }, + { + path: `/user/username/projects/myproject/packages/pkg2/const.cts`, + content: `export type TheNum = 42;`, + }, + { + path: `/user/username/projects/myproject/packages/pkg2/index.ts`, + content: `export type { TheNum } from './const.cjs';`, + }, + { + path: `/user/username/projects/myproject/packages/pkg2/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + composite: true, + outDir: "build", + module: "node16", + }, + }), + }, + { + path: `/user/username/projects/myproject/packages/pkg2/package.json`, + content: JSON.stringify({ + name: "pkg2", + version: "1.0.0", + main: "build/index.js", + type: "module", + }), + }, + { + path: `/user/username/projects/myproject/node_modules/pkg2`, + symLink: `/user/username/projects/myproject/packages/pkg2`, + }, + { ...libFile, path: `/a/lib/lib.es2022.full.d.ts` }, + ], { currentDirectory: "/user/username/projects/myproject" }), commandLineArgs: ["-b", "packages/pkg1", "-w", "--verbose", "--traceResolution"], edits: [ { @@ -132,7 +138,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: moduleResolution", () => { { caption: "reports import errors after change to package file", edit: sys => sys.replaceFileText(`/user/username/projects/myproject/packages/pkg1/package.json`, `"module"`, `"commonjs"`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "removes those errors when a package file is changed to cjs extensions", @@ -145,72 +151,73 @@ describe("unittests:: tsbuildWatch:: watchMode:: moduleResolution", () => { sys.runQueuedTimeoutCallbacks(); // building pkg1 }, }, - ] + ], }); verifyTscWatch({ scenario: "moduleResolution", subScenario: `build mode watches for changes to package-json main fields`, - sys: () => createWatchedSystem([ - { - path: `/user/username/projects/myproject/packages/pkg1/package.json`, - content: JSON.stringify({ - name: "pkg1", - version: "1.0.0", - main: "build/index.js", - }) - }, - { - path: `/user/username/projects/myproject/packages/pkg1/index.ts`, - content: dedent` + sys: () => + createWatchedSystem([ + { + path: `/user/username/projects/myproject/packages/pkg1/package.json`, + content: JSON.stringify({ + name: "pkg1", + version: "1.0.0", + main: "build/index.js", + }), + }, + { + path: `/user/username/projects/myproject/packages/pkg1/index.ts`, + content: dedent` import type { TheNum } from 'pkg2' - export const theNum: TheNum = 42;` - }, - { - path: `/user/username/projects/myproject/packages/pkg1/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { - outDir: "build", - }, - references: [{ path: "../pkg2" }] - }) - }, - { - path: `/user/username/projects/myproject/packages/pkg2/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { - composite: true, - outDir: "build", - baseUrl: ".", - } - }) - }, - { - path: `/user/username/projects/myproject/packages/pkg2/const.ts`, - content: `export type TheNum = 42;` - }, - { - path: `/user/username/projects/myproject/packages/pkg2/index.ts`, - content: `export type { TheNum } from './const.js';` - }, - { - path: `/user/username/projects/myproject/packages/pkg2/other.ts`, - content: `export type TheStr = string;` - }, - { - path: `/user/username/projects/myproject/packages/pkg2/package.json`, - content: JSON.stringify({ - name: "pkg2", - version: "1.0.0", - main: "build/index.js", - }) - }, - { - path: `/user/username/projects/myproject/node_modules/pkg2`, - symLink: `/user/username/projects/myproject/packages/pkg2`, - }, - libFile - ], { currentDirectory: "/user/username/projects/myproject" }), + export const theNum: TheNum = 42;`, + }, + { + path: `/user/username/projects/myproject/packages/pkg1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + outDir: "build", + }, + references: [{ path: "../pkg2" }], + }), + }, + { + path: `/user/username/projects/myproject/packages/pkg2/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + composite: true, + outDir: "build", + baseUrl: ".", + }, + }), + }, + { + path: `/user/username/projects/myproject/packages/pkg2/const.ts`, + content: `export type TheNum = 42;`, + }, + { + path: `/user/username/projects/myproject/packages/pkg2/index.ts`, + content: `export type { TheNum } from './const.js';`, + }, + { + path: `/user/username/projects/myproject/packages/pkg2/other.ts`, + content: `export type TheStr = string;`, + }, + { + path: `/user/username/projects/myproject/packages/pkg2/package.json`, + content: JSON.stringify({ + name: "pkg2", + version: "1.0.0", + main: "build/index.js", + }), + }, + { + path: `/user/username/projects/myproject/node_modules/pkg2`, + symLink: `/user/username/projects/myproject/packages/pkg2`, + }, + libFile, + ], { currentDirectory: "/user/username/projects/myproject" }), commandLineArgs: ["-b", "packages/pkg1", "--verbose", "-w", "--traceResolution"], edits: [ { @@ -223,6 +230,6 @@ describe("unittests:: tsbuildWatch:: watchMode:: moduleResolution", () => { edit: sys => sys.replaceFileText(`/user/username/projects/myproject/packages/pkg2/package.json`, `other.js`, `index.js`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/noEmit.ts b/src/testRunner/unittests/tsbuildWatch/noEmit.ts index 68ebaa759e024..161f6dbefcd40 100644 --- a/src/testRunner/unittests/tsbuildWatch/noEmit.ts +++ b/src/testRunner/unittests/tsbuildWatch/noEmit.ts @@ -1,5 +1,9 @@ -import { libContent } from "../helpers/contents"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + libContent, +} from "../helpers/contents"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { createWatchedSystem, libFile, @@ -10,15 +14,16 @@ describe("unittests:: tsbuildWatch:: watchMode:: with noEmit", () => { scenario: "noEmit", subScenario: "does not go in loop when watching when no files are emitted", commandLineArgs: ["-b", "-w", "-verbose"], - sys: () => createWatchedSystem( - [ - { path: libFile.path, content: libContent }, - { path: `/user/username/projects/myproject/a.js`, content: "" }, - { path: `/user/username/projects/myproject/b.ts`, content: "" }, - { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { allowJs: true, noEmit: true } }) }, - ], - { currentDirectory: "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + [ + { path: libFile.path, content: libContent }, + { path: `/user/username/projects/myproject/a.js`, content: "" }, + { path: `/user/username/projects/myproject/b.ts`, content: "" }, + { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { allowJs: true, noEmit: true } }) }, + ], + { currentDirectory: "/user/username/projects/myproject" }, + ), edits: [ { caption: "No change", @@ -33,6 +38,6 @@ describe("unittests:: tsbuildWatch:: watchMode:: with noEmit", () => { timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], - baselineIncremental: true + baselineIncremental: true, }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/noEmitOnError.ts b/src/testRunner/unittests/tsbuildWatch/noEmitOnError.ts index 5a08e0cdbbdc2..22e5a713141a7 100644 --- a/src/testRunner/unittests/tsbuildWatch/noEmitOnError.ts +++ b/src/testRunner/unittests/tsbuildWatch/noEmitOnError.ts @@ -1,4 +1,6 @@ -import { libContent } from "../helpers/contents"; +import { + libContent, +} from "../helpers/contents"; import { TscWatchCompileChange, verifyTscWatch, @@ -29,27 +31,37 @@ describe("unittests:: tsbuildWatch:: watchMode:: with noEmitOnError", () => { scenario: "noEmitOnError", subScenario: "does not emit any files on error", commandLineArgs: ["-b", "-w", "-verbose"], - sys: () => createWatchedSystem( - [ - ...["tsconfig.json", "shared/types/db.ts", "src/main.ts", "src/other.ts"] - .map(f => getTsBuildProjectFile("noEmitOnError", f)), - { path: libFile.path, content: libContent } - ], - { currentDirectory: `/user/username/projects/noEmitOnError` } - ), + sys: () => + createWatchedSystem( + [ + ...["tsconfig.json", "shared/types/db.ts", "src/main.ts", "src/other.ts"] + .map(f => getTsBuildProjectFile("noEmitOnError", f)), + { path: libFile.path, content: libContent }, + ], + { currentDirectory: `/user/username/projects/noEmitOnError` }, + ), edits: [ noChange, - change("Fix Syntax error", `import { A } from "../shared/types/db"; + change( + "Fix Syntax error", + `import { A } from "../shared/types/db"; const a = { lastName: 'sdsd' -};`), - change("Semantic Error", `import { A } from "../shared/types/db"; -const a: string = 10;`), +};`, + ), + change( + "Semantic Error", + `import { A } from "../shared/types/db"; +const a: string = 10;`, + ), noChange, - change("Fix Semantic Error", `import { A } from "../shared/types/db"; -const a: string = "hello";`), + change( + "Fix Semantic Error", + `import { A } from "../shared/types/db"; +const a: string = "hello";`, + ), noChange, ], - baselineIncremental: true + baselineIncremental: true, }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/programUpdates.ts b/src/testRunner/unittests/tsbuildWatch/programUpdates.ts index 0352a1b571147..6e418029d90b8 100644 --- a/src/testRunner/unittests/tsbuildWatch/programUpdates.ts +++ b/src/testRunner/unittests/tsbuildWatch/programUpdates.ts @@ -22,7 +22,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: program updates", () => { core = "core", logic = "logic", tests = "tests", - ui = "ui" + ui = "ui", } type ReadonlyFile = Readonly; /** [tsconfig, index] | [tsconfig, index, anotherModule, someDecl] */ @@ -100,7 +100,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: program updates", () => { baseline, oldSnap, getPrograms, - watchOrSolution: solutionBuilder + watchOrSolution: solutionBuilder, }); }); @@ -108,7 +108,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: program updates", () => { const newFileWithoutExtension = "newFile"; const newFile: File = { path: projectFilePath(SubProject.core, `${newFileWithoutExtension}.ts`), - content: `export const newFileConst = 30;` + content: `export const newFileConst = 30;`, }; function verifyProjectChanges(subScenario: string, allFilesGetter: () => readonly File[]) { @@ -122,12 +122,14 @@ describe("unittests:: tsbuildWatch:: watchMode:: program updates", () => { scenario: "programUpdates", subScenario: `${subScenario}/change builds changes and reports found errors message`, commandLineArgs: ["-b", "-w", `sample1/${SubProject.tests}`], - sys: () => createWatchedSystem( - allFilesGetter(), - { currentDirectory: "/user/username/projects" } - ), + sys: () => + createWatchedSystem( + allFilesGetter(), + { currentDirectory: "/user/username/projects" }, + ), edits: [ - changeCore(() => `${core[1].content} + changeCore(() => + `${core[1].content} export class someClass { }`, "Make change to core"), buildLogicAndTests, // Another change requeues and builds it @@ -141,27 +143,32 @@ export class someClass { }`; sys.writeFile(core[1].path, change1); assert.equal(sys.writtenFiles.size, 1); sys.writtenFiles.clear(); - sys.writeFile(core[1].path, `${change1} -export class someClass2 { }`); + sys.writeFile( + core[1].path, + `${change1} +export class someClass2 { }`, + ); }, timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Builds core }, buildLogicAndTests, - ] + ], }); verifyTscWatch({ scenario: "programUpdates", subScenario: `${subScenario}/non local change does not start build of referencing projects`, commandLineArgs: ["-b", "-w", `sample1/${SubProject.tests}`], - sys: () => createWatchedSystem( - allFilesGetter(), - { currentDirectory: "/user/username/projects" } - ), + sys: () => + createWatchedSystem( + allFilesGetter(), + { currentDirectory: "/user/username/projects" }, + ), edits: [ - changeCore(() => `${core[1].content} + changeCore(() => + `${core[1].content} function foo() { }`, "Make local change to core"), - ] + ], }); function changeNewFile(newFileContent: string) { @@ -171,24 +178,25 @@ function foo() { }`, "Make local change to core"), scenario: "programUpdates", subScenario: `${subScenario}/builds when new file is added, and its subsequent updates`, commandLineArgs: ["-b", "-w", `sample1/${SubProject.tests}`], - sys: () => createWatchedSystem( - allFilesGetter(), - { currentDirectory: "/user/username/projects" } - ), + sys: () => + createWatchedSystem( + allFilesGetter(), + { currentDirectory: "/user/username/projects" }, + ), edits: [ changeNewFile(newFile.content), buildLogicAndTests, changeNewFile(`${newFile.content} export class someClass2 { }`), buildLogicAndTests, - ] + ], }); } describe("with simple project reference graph", () => { verifyProjectChanges( "with simple project reference graph", - () => allFiles + () => allFiles, ); }); @@ -201,11 +209,11 @@ export class someClass2 { }`), path: coreTsconfig.path, content: JSON.stringify({ compilerOptions: { composite: true, declaration: true }, - references: [{ path: "../tests", circular: true }] - }) + references: [{ path: "../tests", circular: true }], + }), }; return [libFile, circularCoreConfig, ...otherCoreFiles, ...logic, ...tests]; - } + }, ); }); }); @@ -214,10 +222,11 @@ export class someClass2 { }`), scenario: "programUpdates", subScenario: "watches config files that are not present", commandLineArgs: ["-b", "-w", `sample1/${SubProject.tests}`], - sys: () => createWatchedSystem( - [libFile, ...core, logic[1], ...tests], - { currentDirectory: "/user/username/projects" } - ), + sys: () => + createWatchedSystem( + [libFile, ...core, logic[1], ...tests], + { currentDirectory: "/user/username/projects" }, + ), edits: [ { caption: "Write logic tsconfig and build logic", @@ -229,8 +238,8 @@ export class someClass2 { }`), edit: ts.noop, // Build tests timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); describe("when referenced using prepend, builds referencing project even for non local change", () => { @@ -238,7 +247,7 @@ export class someClass2 { }`), before(() => { coreIndex = { path: core[1].path, - content: `function foo() { return 10; }` + content: `function foo() { return 10; }`, }; }); after(() => { @@ -258,30 +267,32 @@ export class someClass2 { }`), const coreTsConfig: File = { path: core[0].path, content: JSON.stringify({ - compilerOptions: { composite: true, declaration: true, outFile: "index.js" } - }) + compilerOptions: { composite: true, declaration: true, outFile: "index.js" }, + }), }; const logicTsConfig: File = { path: logic[0].path, content: JSON.stringify({ compilerOptions: { ignoreDeprecations: "5.0", composite: true, declaration: true, outFile: "index.js" }, - references: [{ path: "../core", prepend: true }] - }) + references: [{ path: "../core", prepend: true }], + }), }; const logicIndex: File = { path: logic[1].path, - content: `function bar() { return foo() + 1 };` + content: `function bar() { return foo() + 1 };`, }; return createWatchedSystem([libFile, coreTsConfig, coreIndex, logicTsConfig, logicIndex], { currentDirectory: "/user/username/projects" }); }, edits: [ - changeCore(() => `${coreIndex.content} + changeCore(() => + `${coreIndex.content} function myFunc() { return 10; }`, "Make non local change and build core"), buildLogic, - changeCore(() => `${coreIndex.content} + changeCore(() => + `${coreIndex.content} function myFunc() { return 100; }`, "Make local change and build core"), buildLogic, - ] + ], }); }); @@ -300,7 +311,7 @@ export function createSomeObject(): SomeObject return { message: "new Object" }; -}` +}`, }; verifyTscWatch({ scenario: "programUpdates", @@ -309,17 +320,17 @@ export function createSomeObject(): SomeObject sys: () => { const libraryTsconfig: File = { path: `${subProjectLibrary}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { composite: true } }) + content: JSON.stringify({ compilerOptions: { composite: true } }), }; const subProjectApp = `${"/user/username/projects"}/sample1/App`; const appTs: File = { path: `${subProjectApp}/app.ts`, content: `import { createSomeObject } from "../Library/library"; -createSomeObject().message;` +createSomeObject().message;`, }; const appTsconfig: File = { path: `${subProjectApp}/tsconfig.json`, - content: JSON.stringify({ references: [{ path: "../Library" }] }) + content: JSON.stringify({ references: [{ path: "../Library" }] }), }; const files = [libFile, libraryTs, libraryTsconfig, appTs, appTsconfig]; @@ -344,9 +355,8 @@ createSomeObject().message;` sys.runQueuedTimeoutCallbacks(); // Build App }, }, - ] + ], }); - }); describe("reports errors in all projects on incremental compile", () => { @@ -359,19 +369,27 @@ createSomeObject().message;` edits: [ { caption: "change logic", - edit: sys => sys.writeFile(logic[1].path, `${logic[1].content} -let y: string = 10;`), + edit: sys => + sys.writeFile( + logic[1].path, + `${logic[1].content} +let y: string = 10;`, + ), // Builds logic timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "change core", - edit: sys => sys.writeFile(core[1].path, `${core[1].content} -let x: string = 10;`), + edit: sys => + sys.writeFile( + core[1].path, + `${core[1].content} +let x: string = 10;`, + ), // Builds core timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); } verifyIncrementalErrors("when preserveWatchOutput is not used", ts.emptyArray); @@ -386,19 +404,19 @@ let x: string = 10;`), content: `export var myClassWithError = class { tags() { } private p = 12 - };` + };`, }; const fileWithFixedError: File = { path: fileWithError.path, - content: fileWithError.content.replace("private p = 12", "") + content: fileWithError.content.replace("private p = 12", ""), }; const fileWithoutError: File = { path: `${subProjectLocation}/fileWithoutError.ts`, - content: `export class myClass { }` + content: `export class myClass { }`, }; const tsconfig: File = { path: `${subProjectLocation}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { composite: true } }) + content: JSON.stringify({ compilerOptions: { composite: true } }), }; const fixError: TscWatchCompileChange = { @@ -418,26 +436,28 @@ let x: string = 10;`), scenario: "programUpdates", subScenario: "reportErrors/declarationEmitErrors/when fixing error files all files are emitted", commandLineArgs: ["-b", "-w", subProject], - sys: () => createWatchedSystem( - [libFile, fileWithError, fileWithoutError, tsconfig], - { currentDirectory: `${"/user/username/projects"}/${solution}` } - ), + sys: () => + createWatchedSystem( + [libFile, fileWithError, fileWithoutError, tsconfig], + { currentDirectory: `${"/user/username/projects"}/${solution}` }, + ), edits: [ - fixError - ] + fixError, + ], }); verifyTscWatch({ scenario: "programUpdates", subScenario: "reportErrors/declarationEmitErrors/when file with no error changes", commandLineArgs: ["-b", "-w", subProject], - sys: () => createWatchedSystem( - [libFile, fileWithError, fileWithoutError, tsconfig], - { currentDirectory: `${"/user/username/projects"}/${solution}` } - ), + sys: () => + createWatchedSystem( + [libFile, fileWithError, fileWithoutError, tsconfig], + { currentDirectory: `${"/user/username/projects"}/${solution}` }, + ), edits: [ - changeFileWithoutError - ] + changeFileWithoutError, + ], }); describe("when reporting errors on introducing error", () => { @@ -451,28 +471,30 @@ let x: string = 10;`), scenario: "programUpdates", subScenario: "reportErrors/declarationEmitErrors/introduceError/when fixing errors only changed file is emitted", commandLineArgs: ["-b", "-w", subProject], - sys: () => createWatchedSystem( - [libFile, fileWithFixedError, fileWithoutError, tsconfig], - { currentDirectory: `${"/user/username/projects"}/${solution}` } - ), + sys: () => + createWatchedSystem( + [libFile, fileWithFixedError, fileWithoutError, tsconfig], + { currentDirectory: `${"/user/username/projects"}/${solution}` }, + ), edits: [ introduceError, - fixError - ] + fixError, + ], }); verifyTscWatch({ scenario: "programUpdates", subScenario: "reportErrors/declarationEmitErrors/introduceError/when file with no error changes", commandLineArgs: ["-b", "-w", subProject], - sys: () => createWatchedSystem( - [libFile, fileWithFixedError, fileWithoutError, tsconfig], - { currentDirectory: `${"/user/username/projects"}/${solution}` } - ), + sys: () => + createWatchedSystem( + [libFile, fileWithFixedError, fileWithoutError, tsconfig], + { currentDirectory: `${"/user/username/projects"}/${solution}` }, + ), edits: [ introduceError, - changeFileWithoutError - ] + changeFileWithoutError, + ], }); }); }); @@ -486,19 +508,27 @@ let x: string = 10;`), edits: [ { caption: "Make non dts change", - edit: sys => sys.writeFile(logic[1].path, `${logic[1].content} -function someFn() { }`), + edit: sys => + sys.writeFile( + logic[1].path, + `${logic[1].content} +function someFn() { }`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // build logic and updates tests }, { caption: "Make dts change", - edit: sys => sys.writeFile(logic[1].path, `${logic[1].content} -export function someFn() { }`), + edit: sys => + sys.writeFile( + logic[1].path, + `${logic[1].content} +export function someFn() { }`, + ), timeouts: sys => { sys.runQueuedTimeoutCallbacks(); // build logic sys.runQueuedTimeoutCallbacks(); // build tests }, - } + }, ], }); @@ -509,29 +539,33 @@ export function someFn() { }`), sys: () => { const index: File = { path: `/user/username/projects/myproject/index.ts`, - content: `const fn = (a: string, b: string) => b;` + content: `const fn = (a: string, b: string) => b;`, }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - noUnusedParameters: true - } - }) + noUnusedParameters: true, + }, + }), }; return createWatchedSystem([index, configFile, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, edits: [ { caption: "Change tsconfig to set noUnusedParameters to false", - edit: sys => sys.writeFile(`/user/username/projects/myproject/tsconfig.json`, JSON.stringify({ - compilerOptions: { - noUnusedParameters: false - } - })), + edit: sys => + sys.writeFile( + `/user/username/projects/myproject/tsconfig.json`, + JSON.stringify({ + compilerOptions: { + noUnusedParameters: false, + }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -544,10 +578,10 @@ export function someFn() { }`), { caption: "Add new file", edit: sys => sys.writeFile(`sample1/${SubProject.core}/file3.ts`, `export const y = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, noopChange, - ] + ], }); verifyTscWatch({ @@ -564,10 +598,10 @@ export function someFn() { }`), { caption: "Add new file", edit: sys => sys.writeFile(`sample1/${SubProject.core}/file3.ts`, `export const y = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - noopChange - ] + noopChange, + ], }); verifyTscWatch({ @@ -577,7 +611,7 @@ export function someFn() { }`), sys: () => { const alphaExtendedConfigFile: File = { path: "/a/b/alpha.tsconfig.json", - content: "{}" + content: "{}", }; const project1Config: File = { path: "/a/b/project1.tsconfig.json", @@ -586,14 +620,14 @@ export function someFn() { }`), compilerOptions: { composite: true, }, - files: [commonFile1.path, commonFile2.path] - }) + files: [commonFile1.path, commonFile2.path], + }), }; const bravoExtendedConfigFile: File = { path: "/a/b/bravo.tsconfig.json", content: JSON.stringify({ - extends: "./alpha.tsconfig.json" - }) + extends: "./alpha.tsconfig.json", + }), }; const otherFile: File = { path: "/a/b/other.ts", @@ -606,8 +640,8 @@ export function someFn() { }`), compilerOptions: { composite: true, }, - files: [otherFile.path] - }) + files: [otherFile.path], + }), }; const otherFile2: File = { path: "/a/b/other2.ts", @@ -618,24 +652,24 @@ export function someFn() { }`), content: JSON.stringify({ compilerOptions: { composite: true, - } - }) + }, + }), }; const extendsConfigFile2: File = { path: "/a/b/extendsConfig2.tsconfig.json", content: JSON.stringify({ compilerOptions: { strictNullChecks: false, - } - }) + }, + }), }; const extendsConfigFile3: File = { path: "/a/b/extendsConfig3.tsconfig.json", content: JSON.stringify({ compilerOptions: { noImplicitAny: true, - } - }) + }, + }), }; const project3Config: File = { path: "/a/b/project3.tsconfig.json", @@ -644,23 +678,36 @@ export function someFn() { }`), compilerOptions: { composite: false, }, - files: [otherFile2.path] - }) + files: [otherFile2.path], + }), }; return createWatchedSystem([ libFile, - alphaExtendedConfigFile, project1Config, commonFile1, commonFile2, - bravoExtendedConfigFile, project2Config, otherFile, otherFile2, - extendsConfigFile1, extendsConfigFile2, extendsConfigFile3, project3Config + alphaExtendedConfigFile, + project1Config, + commonFile1, + commonFile2, + bravoExtendedConfigFile, + project2Config, + otherFile, + otherFile2, + extendsConfigFile1, + extendsConfigFile2, + extendsConfigFile3, + project3Config, ], { currentDirectory: "/a/b" }); }, edits: [ { caption: "Modify alpha config", - edit: sys => sys.writeFile("/a/b/alpha.tsconfig.json", JSON.stringify({ - compilerOptions: { strict: true } - })), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build project1 + edit: sys => + sys.writeFile( + "/a/b/alpha.tsconfig.json", + JSON.stringify({ + compilerOptions: { strict: true }, + }), + ), + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build project1 }, { caption: "Build project 2", @@ -669,17 +716,25 @@ export function someFn() { }`), }, { caption: "change bravo config", - edit: sys => sys.writeFile("/a/b/bravo.tsconfig.json", JSON.stringify({ - extends: "./alpha.tsconfig.json", - compilerOptions: { strict: false } - })), + edit: sys => + sys.writeFile( + "/a/b/bravo.tsconfig.json", + JSON.stringify({ + extends: "./alpha.tsconfig.json", + compilerOptions: { strict: false }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build project2 }, { caption: "project 2 extends alpha", - edit: sys => sys.writeFile("/a/b/project2.tsconfig.json", JSON.stringify({ - extends: "./alpha.tsconfig.json", - })), + edit: sys => + sys.writeFile( + "/a/b/project2.tsconfig.json", + JSON.stringify({ + extends: "./alpha.tsconfig.json", + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build project2 }, { @@ -694,25 +749,33 @@ export function someFn() { }`), }, { caption: "Modify extendsConfigFile2", - edit: sys => sys.writeFile("/a/b/extendsConfig2.tsconfig.json", JSON.stringify({ - compilerOptions: { strictNullChecks: true } - })), + edit: sys => + sys.writeFile( + "/a/b/extendsConfig2.tsconfig.json", + JSON.stringify({ + compilerOptions: { strictNullChecks: true }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build project3 }, { caption: "Modify project 3", - edit: sys => sys.writeFile("/a/b/project3.tsconfig.json", JSON.stringify({ - extends: ["./extendsConfig1.tsconfig.json", "./extendsConfig2.tsconfig.json"], - compilerOptions: { composite: false }, - files: ["/a/b/other2.ts"] - })), + edit: sys => + sys.writeFile( + "/a/b/project3.tsconfig.json", + JSON.stringify({ + extends: ["./extendsConfig1.tsconfig.json", "./extendsConfig2.tsconfig.json"], + compilerOptions: { composite: false }, + files: ["/a/b/other2.ts"], + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build project3 }, { caption: "Delete extendedConfigFile2 and report error", edit: sys => sys.deleteFile("./extendsConfig2.tsconfig.json"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build project3 - } + }, ], }); @@ -725,9 +788,9 @@ export function someFn() { }`), path: "/a/b/alpha.tsconfig.json", content: JSON.stringify({ compilerOptions: { - strict: true - } - }) + strict: true, + }, + }), }; const project1Config: File = { path: "/a/b/project1.tsconfig.json", @@ -736,16 +799,16 @@ export function someFn() { }`), compilerOptions: { composite: true, }, - files: [commonFile1.path, commonFile2.path] - }) + files: [commonFile1.path, commonFile2.path], + }), }; const bravoExtendedConfigFile: File = { path: "/a/b/bravo.tsconfig.json", content: JSON.stringify({ compilerOptions: { - strict: true - } - }) + strict: true, + }, + }), }; const otherFile: File = { path: "/a/b/other.ts", @@ -758,8 +821,8 @@ export function someFn() { }`), compilerOptions: { composite: true, }, - files: [otherFile.path] - }) + files: [otherFile.path], + }), }; const configFile: File = { path: "/a/b/tsconfig.json", @@ -773,39 +836,50 @@ export function someFn() { }`), }, ], files: [], - }) + }), }; return createWatchedSystem([ - libFile, configFile, - alphaExtendedConfigFile, project1Config, commonFile1, commonFile2, - bravoExtendedConfigFile, project2Config, otherFile + libFile, + configFile, + alphaExtendedConfigFile, + project1Config, + commonFile1, + commonFile2, + bravoExtendedConfigFile, + project2Config, + otherFile, ], { currentDirectory: "/a/b" }); }, edits: [ { caption: "Remove project2 from base config", - edit: sys => sys.modifyFile("/a/b/tsconfig.json", JSON.stringify({ - references: [ - { - path: "./project1.tsconfig.json", - }, - ], - files: [], - })), + edit: sys => + sys.modifyFile( + "/a/b/tsconfig.json", + JSON.stringify({ + references: [ + { + path: "./project1.tsconfig.json", + }, + ], + files: [], + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ scenario: "programUpdates", subScenario: "tsbuildinfo has error", - sys: () => createWatchedSystem({ - "/src/project/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": "{}", - "/src/project/tsconfig.tsbuildinfo": "Some random string", - [libFile.path]: libFile.content, - }), + sys: () => + createWatchedSystem({ + "/src/project/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": "{}", + "/src/project/tsconfig.tsbuildinfo": "Some random string", + [libFile.path]: libFile.content, + }), commandLineArgs: ["--b", "src/project", "-i", "-w"], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/projectsBuilding.ts b/src/testRunner/unittests/tsbuildWatch/projectsBuilding.ts index 0968b40bdef0e..851af314be0e2 100644 --- a/src/testRunner/unittests/tsbuildWatch/projectsBuilding.ts +++ b/src/testRunner/unittests/tsbuildWatch/projectsBuilding.ts @@ -25,7 +25,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { return [ { path: `/user/username/projects/myproject/pkg${index}/index.ts`, - content: `export const pkg${index} = ${index};` + content: `export const pkg${index} = ${index};`, }, { path: `/user/username/projects/myproject/pkg${index}/tsconfig.json`, @@ -33,9 +33,9 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { compilerOptions: { composite: true }, references: index === 0 ? undefined : - [{ path: `../pkg0` }] - }) - } + [{ path: `../pkg0` }], + }), + }, ]; } function solution(maxPkgs: number): File { @@ -44,7 +44,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { content: JSON.stringify({ references: pkgs(createPkgReference, maxPkgs), files: [], - }) + }), }; } function checkBuildPkg(startIndex: number, count: number): TscWatchCompileChange { @@ -58,10 +58,11 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { scenario: "projectsBuilding", subScenario: `when there are 3 projects in a solution`, commandLineArgs: ["-b", "-w", "-v"], - sys: () => createWatchedSystem( - [libFile, ...ts.flatMap(pkgs(pkgFiles, 3), ts.identity), solution(3)], - { currentDirectory: "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + [libFile, ...ts.flatMap(pkgs(pkgFiles, 3), ts.identity), solution(3)], + { currentDirectory: "/user/username/projects/myproject" }, + ), edits: [ { caption: "dts doesn't change", @@ -72,20 +73,21 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { { caption: "dts change", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `export const someConst = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(1, 2), noopChange, - ] + ], }); verifyTscWatch({ scenario: "projectsBuilding", subScenario: `when there are 5 projects in a solution`, commandLineArgs: ["-b", "-w", "-v"], - sys: () => createWatchedSystem( - [libFile, ...ts.flatMap(pkgs(pkgFiles, 5), ts.identity), solution(5)], - { currentDirectory: "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + [libFile, ...ts.flatMap(pkgs(pkgFiles, 5), ts.identity), solution(5)], + { currentDirectory: "/user/username/projects/myproject" }, + ), edits: [ { caption: "dts doesn't change", @@ -96,20 +98,21 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { { caption: "dts change", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `export const someConst = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(1, 4), noopChange, - ] + ], }); verifyTscWatch({ scenario: "projectsBuilding", subScenario: `when there are 8 projects in a solution`, commandLineArgs: ["-b", "-w", "-v"], - sys: () => createWatchedSystem( - [libFile, ...ts.flatMap(pkgs(pkgFiles, 8), ts.identity), solution(8)], - { currentDirectory: "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + [libFile, ...ts.flatMap(pkgs(pkgFiles, 8), ts.identity), solution(8)], + { currentDirectory: "/user/username/projects/myproject" }, + ), edits: [ { caption: "dts doesn't change", @@ -120,7 +123,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { { caption: "dts change", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `export const someConst = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(1, 5), checkBuildPkg(6, 2), @@ -128,26 +131,27 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { { caption: "dts change2", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `export const someConst3 = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(1, 5), { caption: "change while building", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `const someConst4 = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(6, 2), noopChange, - ] + ], }); verifyTscWatch({ scenario: "projectsBuilding", subScenario: `when there are 23 projects in a solution`, commandLineArgs: ["-b", "-w", "-v"], - sys: () => createWatchedSystem( - [libFile, ...ts.flatMap(pkgs(pkgFiles, 23), ts.identity), solution(23)], - { currentDirectory: "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + [libFile, ...ts.flatMap(pkgs(pkgFiles, 23), ts.identity), solution(23)], + { currentDirectory: "/user/username/projects/myproject" }, + ), edits: [ { caption: "dts doesn't change", @@ -158,7 +162,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { { caption: "dts change", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `export const someConst = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(1, 5), checkBuildPkg(6, 5), @@ -169,20 +173,20 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { { caption: "dts change2", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `export const someConst3 = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(1, 5), checkBuildPkg(6, 5), { caption: "change while building", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `const someConst4 = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(11, 5), { caption: "change while building: dts changes", edit: sys => sys.appendFile(`/user/username/projects/myproject/pkg0/index.ts`, `export const someConst5 = 10;`), - timeouts: sys => sys.runQueuedTimeoutCallbacks() // Build pkg0 + timeouts: sys => sys.runQueuedTimeoutCallbacks(), // Build pkg0 }, checkBuildPkg(1, 5), checkBuildPkg(6, 5), @@ -190,6 +194,6 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { checkBuildPkg(16, 5), checkBuildPkg(21, 3), noopChange, - ] + ], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/publicApi.ts b/src/testRunner/unittests/tsbuildWatch/publicApi.ts index a8b5a21152553..2f5ba8f5f648e 100644 --- a/src/testRunner/unittests/tsbuildWatch/publicApi.ts +++ b/src/testRunner/unittests/tsbuildWatch/publicApi.ts @@ -16,16 +16,16 @@ it("unittests:: tsbuildWatch:: watchMode:: Public API with custom transformers", content: JSON.stringify({ references: [ { path: "./shared/tsconfig.json" }, - { path: "./webpack/tsconfig.json" } + { path: "./webpack/tsconfig.json" }, ], - files: [] - }) + files: [], + }), }; const sharedConfig: File = { path: `/user/username/projects/myproject/shared/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true }, - }) + }), }; const sharedIndex: File = { path: `/user/username/projects/myproject/shared/index.ts`, @@ -33,14 +33,14 @@ it("unittests:: tsbuildWatch:: watchMode:: Public API with custom transformers", export class c { } export enum e { } // leading -export function f2() { } // trailing` +export function f2() { } // trailing`, }; const webpackConfig: File = { path: `/user/username/projects/myproject/webpack/tsconfig.json`, content: JSON.stringify({ - compilerOptions: { composite: true, }, - references: [{ path: "../shared/tsconfig.json" }] - }) + compilerOptions: { composite: true }, + references: [{ path: "../shared/tsconfig.json" }], + }), }; const webpackIndex: File = { path: `/user/username/projects/myproject/webpack/index.ts`, @@ -48,7 +48,7 @@ export function f2() { } // trailing` export class c2 { } export enum e2 { } // leading -export function f22() { } // trailing` +export function f22() { } // trailing`, }; const commandLineArgs = ["--b", "--w"]; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem([libFile, solution, sharedConfig, sharedIndex, webpackConfig, webpackIndex], { currentDirectory: "/user/username/projects/myproject" })); @@ -71,10 +71,10 @@ export function f22() { } // trailing` timeouts: sys => { sys.runQueuedTimeoutCallbacks(); // Shared sys.runQueuedTimeoutCallbacks(); // webpack and solution - } - } + }, + }, ], - watchOrSolution: builder + watchOrSolution: builder, }); function getCustomTransformers(project: string): ts.CustomTransformers { @@ -111,4 +111,4 @@ export function f22() { } // trailing` }; return { before: [before], after: [after] }; } -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/reexport.ts b/src/testRunner/unittests/tsbuildWatch/reexport.ts index ff1f3b1f05bed..1184a781da54f 100644 --- a/src/testRunner/unittests/tsbuildWatch/reexport.ts +++ b/src/testRunner/unittests/tsbuildWatch/reexport.ts @@ -1,5 +1,9 @@ -import { libContent } from "../helpers/contents"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + libContent, +} from "../helpers/contents"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { createWatchedSystem, getTsBuildProjectFile, @@ -11,18 +15,22 @@ describe("unittests:: tsbuildWatch:: watchMode:: with reexport when referenced p scenario: "reexport", subScenario: "Reports errors correctly", commandLineArgs: ["-b", "-w", "-verbose", "src"], - sys: () => createWatchedSystem( - [ - ...[ - "src/tsconfig.json", - "src/main/tsconfig.json", "src/main/index.ts", - "src/pure/tsconfig.json", "src/pure/index.ts", "src/pure/session.ts" - ] - .map(f => getTsBuildProjectFile("reexport", f)), - { path: libFile.path, content: libContent } - ], - { currentDirectory: `/user/username/projects/reexport` } - ), + sys: () => + createWatchedSystem( + [ + ...[ + "src/tsconfig.json", + "src/main/tsconfig.json", + "src/main/index.ts", + "src/pure/tsconfig.json", + "src/pure/index.ts", + "src/pure/session.ts", + ] + .map(f => getTsBuildProjectFile("reexport", f)), + { path: libFile.path, content: libContent }, + ], + { currentDirectory: `/user/username/projects/reexport` }, + ), edits: [ { caption: "Introduce error", @@ -39,7 +47,7 @@ describe("unittests:: tsbuildWatch:: watchMode:: with reexport when referenced p sys.runQueuedTimeoutCallbacks(); // build src/pure sys.runQueuedTimeoutCallbacks(); // build src/main and src }, - } - ] + }, + ], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsbuildWatch/watchEnvironment.ts b/src/testRunner/unittests/tsbuildWatch/watchEnvironment.ts index ca887c6699db1..64904c3e6e913 100644 --- a/src/testRunner/unittests/tsbuildWatch/watchEnvironment.ts +++ b/src/testRunner/unittests/tsbuildWatch/watchEnvironment.ts @@ -18,7 +18,7 @@ describe("unittests:: tsbuildWatch:: watchEnvironment:: tsbuild:: watchMode:: wi const configPath = `${project}/tsconfig.json`; const typing: File = { path: `${project}/typings/xterm.d.ts`, - content: "export const typing = 10;" + content: "export const typing = 10;", }; const allPkgFiles = pkgs(pkgFiles); @@ -43,7 +43,7 @@ describe("unittests:: tsbuildWatch:: watchEnvironment:: tsbuild:: watchMode:: wi timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); - } + }, }, { // Make change @@ -60,7 +60,7 @@ describe("unittests:: tsbuildWatch:: watchEnvironment:: tsbuild:: watchMode:: wi timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); - } + }, }, { // Make change to remove all watches @@ -77,7 +77,7 @@ describe("unittests:: tsbuildWatch:: watchEnvironment:: tsbuild:: watchMode:: wi timeouts: sys => sys.logTimeoutQueueLength(), }, ], - watchOrSolution: solutionBuilder + watchOrSolution: solutionBuilder, }); function flatArray(arr: T[][]): readonly T[] { @@ -97,7 +97,7 @@ describe("unittests:: tsbuildWatch:: watchEnvironment:: tsbuild:: watchMode:: wi return [ { path: `${project}/pkg${index}/index.ts`, - content: `export const pkg${index} = ${index};` + content: `export const pkg${index} = ${index};`, }, { path: `${project}/pkg${index}/tsconfig.json`, @@ -105,18 +105,21 @@ describe("unittests:: tsbuildWatch:: watchEnvironment:: tsbuild:: watchMode:: wi complerOptions: { composite: true }, include: [ "**/*.ts", - "../typings/xterm.d.ts" - ] - }) - } + "../typings/xterm.d.ts", + ], + }), + }, ]; } function writePkgReferences(system: TestServerHost) { - system.writeFile(configPath, JSON.stringify({ - files: [], - include: [], - references: pkgs(createPkgReference) - })); + system.writeFile( + configPath, + JSON.stringify({ + files: [], + include: [], + references: pkgs(createPkgReference), + }), + ); } }); }); diff --git a/src/testRunner/unittests/tsc/cancellationToken.ts b/src/testRunner/unittests/tsc/cancellationToken.ts index dfda4549902b4..8deb7cee76083 100644 --- a/src/testRunner/unittests/tsc/cancellationToken.ts +++ b/src/testRunner/unittests/tsc/cancellationToken.ts @@ -27,7 +27,7 @@ describe("unittests:: tsc:: builder cancellationToken", () => { import {B} from './b'; declare var console: any; let b = new B(); - console.log(b.c.d);` + console.log(b.c.d);`, }; const bFile: File = { path: `/user/username/projects/myproject/b.ts`, @@ -35,36 +35,36 @@ describe("unittests:: tsc:: builder cancellationToken", () => { import {C} from './c'; export class B { c = new C(); - }` + }`, }; const cFile: File = { path: `/user/username/projects/myproject/c.ts`, content: Utils.dedent` export class C { d = 1; - }` + }`, }; const dFile: File = { path: `/user/username/projects/myproject/d.ts`, - content: "export class D { }" + content: "export class D { }", }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { incremental: true, declaration: true } }) + content: JSON.stringify({ compilerOptions: { incremental: true, declaration: true } }), }; const { sys, baseline, oldSnap: originalSnap } = createBaseline(createWatchedSystem( [aFile, bFile, cFile, dFile, config, libFile], - { currentDirectory: "/user/username/projects/myproject" } + { currentDirectory: "/user/username/projects/myproject" }, )); sys.exit = exitCode => sys.exitCode = exitCode; const reportDiagnostic = ts.createDiagnosticReporter(sys, /*pretty*/ true); const parsedConfig = ts.parseConfigFileWithSystem( "tsconfig.json", {}, - /*extendedConfigCache*/ undefined, - /*watchOptionsToExtend*/ undefined, + /*extendedConfigCache*/ undefined, + /*watchOptionsToExtend*/ undefined, sys, - reportDiagnostic + reportDiagnostic, )!; const host = ts.createIncrementalCompilerHost(parsedConfig.options, sys); let programs: CommandLineProgram[] = ts.emptyArray; @@ -91,7 +91,7 @@ describe("unittests:: tsc:: builder cancellationToken", () => { sys, baseline, sys => sys.appendFile(cFile.path, "export function foo() {}"), - "Add change that affects d.ts" + "Add change that affects d.ts", ); createIncrementalProgram(); @@ -145,8 +145,8 @@ describe("unittests:: tsc:: builder cancellationToken", () => { parsedConfig.options, host, builderProgram, - /*configFileParsingDiagnostics*/ undefined, - /*projectReferences*/ undefined, + /*configFileParsingDiagnostics*/ undefined, + /*projectReferences*/ undefined, ); updatePrograms(); } @@ -173,13 +173,13 @@ describe("unittests:: tsc:: builder cancellationToken", () => { parsedConfig.fileNames, parsedConfig.options, host, - /*oldProgram*/ undefined, - /*configFileParsingDiagnostics*/ undefined, - /*projectReferences*/ undefined, + /*oldProgram*/ undefined, + /*configFileParsingDiagnostics*/ undefined, + /*projectReferences*/ undefined, ); updatePrograms(); emitAndBaseline(); } }); } -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsc/composite.ts b/src/testRunner/unittests/tsc/composite.ts index 571ade2ab4235..a42d0cb4cc5bd 100644 --- a/src/testRunner/unittests/tsc/composite.ts +++ b/src/testRunner/unittests/tsc/composite.ts @@ -4,16 +4,17 @@ import { } from "../helpers/tsc"; import { loadProjectFromFiles, - replaceText + replaceText, } from "../helpers/vfs"; describe("unittests:: tsc:: composite::", () => { verifyTsc({ scenario: "composite", subScenario: "when setting composite false on command line", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": Utils.dedent` { "compilerOptions": { "target": "es5", @@ -24,16 +25,17 @@ describe("unittests:: tsc:: composite::", () => { "src/**/*.ts" ] }`, - }), + }), commandLineArgs: ["--composite", "false", "--p", "src/project"], }); verifyTsc({ scenario: "composite", subScenario: "when setting composite null on command line", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": Utils.dedent` { "compilerOptions": { "target": "es5", @@ -44,16 +46,17 @@ describe("unittests:: tsc:: composite::", () => { "src/**/*.ts" ] }`, - }), + }), commandLineArgs: ["--composite", "null", "--p", "src/project"], }); verifyTsc({ scenario: "composite", subScenario: "when setting composite false on command line but has tsbuild info in config", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": Utils.dedent` { "compilerOptions": { "target": "es5", @@ -65,16 +68,17 @@ describe("unittests:: tsc:: composite::", () => { "src/**/*.ts" ] }`, - }), + }), commandLineArgs: ["--composite", "false", "--p", "src/project"], }); verifyTsc({ scenario: "composite", subScenario: "when setting composite false and tsbuildinfo as null on command line but has tsbuild info in config", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": Utils.dedent` { "compilerOptions": { "target": "es5", @@ -86,28 +90,29 @@ describe("unittests:: tsc:: composite::", () => { "src/**/*.ts" ] }`, - }), + }), commandLineArgs: ["--composite", "false", "--p", "src/project", "--tsBuildInfoFile", "null"], }); verifyTsc({ scenario: "composite", subScenario: "converting to modules", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "const x = 10;", - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - module: "none", - composite: true, - }, + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "const x = 10;", + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "none", + composite: true, + }, + }), }), - }), commandLineArgs: ["-p", "/src/project"], edits: [ { caption: "convert to modules", edit: fs => replaceText(fs, "/src/project/tsconfig.json", "none", "es2015"), - } - ] + }, + ], }); }); diff --git a/src/testRunner/unittests/tsc/declarationEmit.ts b/src/testRunner/unittests/tsc/declarationEmit.ts index 55c5c3d3e8252..87383cad99c63 100644 --- a/src/testRunner/unittests/tsc/declarationEmit.ts +++ b/src/testRunner/unittests/tsc/declarationEmit.ts @@ -1,6 +1,8 @@ import * as ts from "../../_namespaces/ts"; import * as Utils from "../../_namespaces/Utils"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { createWatchedSystem, FileOrFolderOrSymLink, @@ -37,10 +39,11 @@ describe("unittests:: tsc:: declarationEmit::", () => { verifyTscWatch({ scenario: "declarationEmit", subScenario: caseChangeScenario, - sys: () => createWatchedSystem( - files.map(f => changeCaseFile(f, changeCaseFileTestPath, str => str.replace("myproject", "myProject"))), - { currentDirectory: "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + files.map(f => changeCaseFile(f, changeCaseFileTestPath, str => str.replace("myproject", "myProject"))), + { currentDirectory: "/user/username/projects/myproject" }, + ), commandLineArgs: ["-p", rootProject, "--explainFiles"], }); }); @@ -52,7 +55,7 @@ describe("unittests:: tsc:: declarationEmit::", () => { compilerOptions: { target: "es5", declaration: true, - traceResolution: true + traceResolution: true, }, }); } @@ -93,7 +96,7 @@ describe("unittests:: tsc:: declarationEmit::", () => { function fsaPackageJson() { return JSON.stringify({ name: "typescript-fsa", - version: "3.0.0-beta-2" + version: "3.0.0-beta-2", }); } function fsaIndex() { @@ -126,7 +129,7 @@ describe("unittests:: tsc:: declarationEmit::", () => { { path: `/user/username/projects/myproject/plugin-one/node_modules/typescript-fsa/package.json`, content: fsaPackageJson() }, { path: `/user/username/projects/myproject/plugin-one/node_modules/typescript-fsa/index.d.ts`, content: fsaIndex() }, { path: `/user/username/projects/myproject/plugin-one/node_modules/plugin-two`, symLink: `/user/username/projects/myproject/plugin-two` }, - libFile + libFile, ], changeCaseFileTestPath: str => ts.stringContains(str, "/plugin-two"), }); @@ -140,8 +143,8 @@ describe("unittests:: tsc:: declarationEmit::", () => { content: JSON.stringify({ name: "plugin-two", version: "0.1.3", - main: "dist/commonjs/index.js" - }) + main: "dist/commonjs/index.js", + }), }, { path: `/user/username/projects/myproject/plugin-two/dist/commonjs/index.d.ts`, content: pluginTwoDts() }, { path: `/user/username/projects/myproject/plugin-two/node_modules/typescript-fsa/package.json`, content: fsaPackageJson() }, @@ -150,13 +153,13 @@ describe("unittests:: tsc:: declarationEmit::", () => { { path: `/user/username/projects/myproject/plugin-one/index.ts`, content: `${pluginOneIndex()} -${pluginOneAction()}` +${pluginOneAction()}`, }, { path: `/user/username/projects/myproject/plugin-one/node_modules/typescript-fsa/package.json`, content: fsaPackageJson() }, { path: `/user/username/projects/myproject/plugin-one/node_modules/typescript-fsa/index.d.ts`, content: fsaIndex() }, { path: `/temp/yarn/data/link/plugin-two`, symLink: `/user/username/projects/myproject/plugin-two` }, { path: `/user/username/projects/myproject/plugin-one/node_modules/plugin-two`, symLink: `/temp/yarn/data/link/plugin-two` }, - libFile + libFile, ], changeCaseFileTestPath: str => ts.stringContains(str, "/plugin-two"), }); @@ -169,7 +172,7 @@ ${pluginOneAction()}` { path: `/user/username/projects/myproject/pkg1/dist/index.d.ts`, content: Utils.dedent` - export * from './types';` + export * from './types';`, }, { path: `/user/username/projects/myproject/pkg1/dist/types.d.ts`, @@ -186,7 +189,7 @@ ${pluginOneAction()}` private constructor(); toString(): string; static create(key: string): MetadataAccessor; - }` + }`, }, { path: `/user/username/projects/myproject/pkg1/package.json`, @@ -194,18 +197,18 @@ ${pluginOneAction()}` name: "@raymondfeng/pkg1", version: "1.0.0", main: "dist/index.js", - typings: "dist/index.d.ts" - }) + typings: "dist/index.d.ts", + }), }, { path: `/user/username/projects/myproject/pkg2/dist/index.d.ts`, content: Utils.dedent` - export * from './types';` + export * from './types';`, }, { path: `/user/username/projects/myproject/pkg2/dist/types.d.ts`, content: Utils.dedent` - export {MetadataAccessor} from '@raymondfeng/pkg1';` + export {MetadataAccessor} from '@raymondfeng/pkg1';`, }, { path: `/user/username/projects/myproject/pkg2/package.json`, @@ -213,19 +216,19 @@ ${pluginOneAction()}` name: "@raymondfeng/pkg2", version: "1.0.0", main: "dist/index.js", - typings: "dist/index.d.ts" - }) + typings: "dist/index.d.ts", + }), }, { path: `/user/username/projects/myproject/pkg3/src/index.ts`, content: Utils.dedent` - export * from './keys';` + export * from './keys';`, }, { path: `/user/username/projects/myproject/pkg3/src/keys.ts`, content: Utils.dedent` import {MetadataAccessor} from "@raymondfeng/pkg2"; - export const ADMIN = MetadataAccessor.create('1');` + export const ADMIN = MetadataAccessor.create('1');`, }, { path: `/user/username/projects/myproject/pkg3/tsconfig.json`, @@ -237,19 +240,19 @@ ${pluginOneAction()}` module: "commonjs", strict: true, esModuleInterop: true, - declaration: true - } - }) + declaration: true, + }, + }), }, { path: `/user/username/projects/myproject/pkg2/node_modules/@raymondfeng/pkg1`, - symLink: `/user/username/projects/myproject/pkg1` + symLink: `/user/username/projects/myproject/pkg1`, }, { path: `/user/username/projects/myproject/pkg3/node_modules/@raymondfeng/pkg2`, - symLink: `/user/username/projects/myproject/pkg2` + symLink: `/user/username/projects/myproject/pkg2`, }, - libFile + libFile, ], changeCaseFileTestPath: str => ts.stringContains(str, "/pkg1"), }); diff --git a/src/testRunner/unittests/tsc/extends.ts b/src/testRunner/unittests/tsc/extends.ts index 9fb78d0384073..ebc16575046d9 100644 --- a/src/testRunner/unittests/tsc/extends.ts +++ b/src/testRunner/unittests/tsc/extends.ts @@ -1,5 +1,9 @@ -import { getSymlinkedExtendsSys } from "../helpers/extends"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + getSymlinkedExtendsSys, +} from "../helpers/extends"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; describe("unittests:: tsc:: extends::", () => { verifyTscWatch({ @@ -8,4 +12,4 @@ describe("unittests:: tsc:: extends::", () => { sys: getSymlinkedExtendsSys, commandLineArgs: ["-p", "src", "--extendedDiagnostics"], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsc/forceConsistentCasingInFileNames.ts b/src/testRunner/unittests/tsc/forceConsistentCasingInFileNames.ts index 7a1f9414ef8f6..0a765e6e3f193 100644 --- a/src/testRunner/unittests/tsc/forceConsistentCasingInFileNames.ts +++ b/src/testRunner/unittests/tsc/forceConsistentCasingInFileNames.ts @@ -2,21 +2,24 @@ import * as Utils from "../../_namespaces/Utils"; import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsc:: forceConsistentCasingInFileNames::", () => { verifyTsc({ scenario: "forceConsistentCasingInFileNames", subScenario: "with relative and non relative file resolutions", commandLineArgs: ["/src/project/src/struct.d.ts", "--forceConsistentCasingInFileNames", "--explainFiles"], - fs: () => loadProjectFromFiles({ - "/src/project/src/struct.d.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/struct.d.ts": Utils.dedent` import * as xs1 from "fp-ts/lib/Struct"; import * as xs2 from "fp-ts/lib/struct"; import * as xs3 from "./Struct"; import * as xs4 from "./struct"; `, - "/src/project/node_modules/fp-ts/lib/struct.d.ts": `export function foo(): void`, - }), + "/src/project/node_modules/fp-ts/lib/struct.d.ts": `export function foo(): void`, + }), }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsc/incremental.ts b/src/testRunner/unittests/tsc/incremental.ts index e3d6adefb50a4..6232fc3b59bee 100644 --- a/src/testRunner/unittests/tsc/incremental.ts +++ b/src/testRunner/unittests/tsc/incremental.ts @@ -3,7 +3,7 @@ import * as Utils from "../../_namespaces/Utils"; import * as vfs from "../../_namespaces/vfs"; import { compilerOptionsToConfigJson, - libContent + libContent, } from "../helpers/contents"; import { noChangeOnlyRuns, @@ -14,17 +14,19 @@ import { import { appendText, loadProjectFromDisk, - loadProjectFromFiles, prependText, - replaceText + loadProjectFromFiles, + prependText, + replaceText, } from "../helpers/vfs"; describe("unittests:: tsc:: incremental::", () => { verifyTsc({ scenario: "incremental", subScenario: "when passing filename for buildinfo on commandline", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": Utils.dedent` { "compilerOptions": { "target": "es5", @@ -34,52 +36,55 @@ describe("unittests:: tsc:: incremental::", () => { "src/**/*.ts" ] }`, - }), + }), commandLineArgs: ["--incremental", "--p", "src/project", "--tsBuildInfoFile", "src/project/.tsbuildinfo", "--explainFiles"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); verifyTsc({ scenario: "incremental", subScenario: "when passing rootDir from commandline", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": Utils.dedent` { "compilerOptions": { "incremental": true, "outDir": "dist", }, }`, - }), + }), commandLineArgs: ["--p", "src/project", "--rootDir", "src/project/src"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); verifyTsc({ scenario: "incremental", subScenario: "with only dts files", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.d.ts": "export const x = 10;", - "/src/project/src/another.d.ts": "export const y = 10;", - "/src/project/tsconfig.json": "{}", - }), + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.d.ts": "export const x = 10;", + "/src/project/src/another.d.ts": "export const y = 10;", + "/src/project/tsconfig.json": "{}", + }), commandLineArgs: ["--incremental", "--p", "src/project"], edits: [ noChangeRun, { caption: "incremental-declaration-doesnt-change", - edit: fs => appendText(fs, "/src/project/src/main.d.ts", "export const xy = 100;") - } - ] + edit: fs => appendText(fs, "/src/project/src/main.d.ts", "export const xy = 100;"), + }, + ], }); verifyTsc({ scenario: "incremental", subScenario: "when passing rootDir is in the tsconfig", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": Utils.dedent` { "compilerOptions": { "incremental": true, @@ -87,24 +92,25 @@ describe("unittests:: tsc:: incremental::", () => { "rootDir": "./" }, }`, - }), + }), commandLineArgs: ["--p", "src/project"], - edits: noChangeOnlyRuns + edits: noChangeOnlyRuns, }); verifyTsc({ scenario: "incremental", subScenario: "tsbuildinfo has error", - fs: () => loadProjectFromFiles({ - "/src/project/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": "{}", - "/src/project/tsconfig.tsbuildinfo": "Some random string", - }), + fs: () => + loadProjectFromFiles({ + "/src/project/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": "{}", + "/src/project/tsconfig.tsbuildinfo": "Some random string", + }), commandLineArgs: ["--p", "src/project", "-i"], edits: [{ caption: "tsbuildinfo written has error", edit: fs => prependText(fs, "/src/project/tsconfig.tsbuildinfo", "Some random string"), - }] + }], }); describe("with noEmitOnError", () => { @@ -127,27 +133,42 @@ describe("unittests:: tsc:: incremental::", () => { noChangeRun, { caption: "incremental-declaration-doesnt-change", - edit: fixModifyFs + edit: fixModifyFs, }, noChangeRun, ], - baselinePrograms: true + baselinePrograms: true, }); } verifyNoEmitOnError( "with noEmitOnError syntax errors", - fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; + fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; const a = { lastName: 'sdsd' -};`, "utf-8") +};`, + "utf-8", + ), ); verifyNoEmitOnError( "with noEmitOnError semantic errors", - fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; -const a: string = "hello";`, "utf-8"), - fs => fs.writeFileSync("/src/src/main.ts", `import { A } from "../shared/types/db"; -const a: string = 10;`, "utf-8"), + fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; +const a: string = "hello";`, + "utf-8", + ), + fs => + fs.writeFileSync( + "/src/src/main.ts", + `import { A } from "../shared/types/db"; +const a: string = 10;`, + "utf-8", + ), ); }); @@ -283,23 +304,24 @@ const a: string = 10;`, "utf-8"), verifyTsc({ scenario: "incremental", subScenario: `when global file is added, the signatures are updated`, - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": Utils.dedent` /// /// function main() { } `, - "/src/project/src/anotherFileWithSameReferenes.ts": Utils.dedent` + "/src/project/src/anotherFileWithSameReferenes.ts": Utils.dedent` /// /// function anotherFileWithSameReferenes() { } `, - "/src/project/src/filePresent.ts": `function something() { return 10; }`, - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { composite: true, }, - include: ["src/**/*.ts"] + "/src/project/src/filePresent.ts": `function something() { return 10; }`, + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { composite: true }, + include: ["src/**/*.ts"], + }), }), - }), commandLineArgs: ["--p", "src/project"], edits: [ noChangeRun, @@ -315,8 +337,12 @@ const a: string = 10;`, "utf-8"), caption: "Add new file and update main file", edit: fs => { fs.writeFileSync(`/src/project/src/newFile.ts`, "function foo() { return 20; }"); - prependText(fs, `/src/project/src/main.ts`, `/// -`); + prependText( + fs, + `/src/project/src/main.ts`, + `/// +`, + ); appendText(fs, `/src/project/src/main.ts`, `foo();`); }, }, @@ -351,25 +377,27 @@ declare global { verifyTsc({ scenario: "react-jsx-emit-mode", subScenario: "with no backing types found doesn't crash", - fs: () => loadProjectFromFiles({ - "/src/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result - "/src/project/node_modules/@types/react/index.d.ts": getJsxLibraryContent(), // doesn't contain a jsx-runtime definition - "/src/project/src/index.tsx": `export const App = () =>
;`, - "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }) - }), - commandLineArgs: ["--p", "src/project"] + fs: () => + loadProjectFromFiles({ + "/src/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result + "/src/project/node_modules/@types/react/index.d.ts": getJsxLibraryContent(), // doesn't contain a jsx-runtime definition + "/src/project/src/index.tsx": `export const App = () =>
;`, + "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }), + }), + commandLineArgs: ["--p", "src/project"], }); verifyTsc({ scenario: "react-jsx-emit-mode", subScenario: "with no backing types found doesn't crash under --strict", - fs: () => loadProjectFromFiles({ - "/src/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result - "/src/project/node_modules/@types/react/index.d.ts": getJsxLibraryContent(), // doesn't contain a jsx-runtime definition - "/src/project/src/index.tsx": `export const App = () =>
;`, - "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }) - }), - commandLineArgs: ["--p", "src/project", "--strict"] + fs: () => + loadProjectFromFiles({ + "/src/project/node_modules/react/jsx-runtime.js": "export {}", // js needs to be present so there's a resolution result + "/src/project/node_modules/@types/react/index.d.ts": getJsxLibraryContent(), // doesn't contain a jsx-runtime definition + "/src/project/src/index.tsx": `export const App = () =>
;`, + "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { module: "commonjs", jsx: "react-jsx", incremental: true, jsxImportSource: "react" } }), + }), + commandLineArgs: ["--p", "src/project", "--strict"], }); }); @@ -377,27 +405,28 @@ declare global { scenario: "incremental", subScenario: "when new file is added to the referenced project", commandLineArgs: ["-i", "-p", `src/projects/project2`], - fs: () => loadProjectFromFiles({ - "/src/projects/project1/tsconfig.json": JSON.stringify({ - compilerOptions: { - module: "none", - composite: true - }, - exclude: ["temp"] - }), - "/src/projects/project1/class1.ts": `class class1 {}`, - "/src/projects/project1/class1.d.ts": `declare class class1 {}`, - "/src/projects/project2/tsconfig.json": JSON.stringify({ - compilerOptions: { - module: "none", - composite: true - }, - references: [ - { path: "../project1" } - ] + fs: () => + loadProjectFromFiles({ + "/src/projects/project1/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "none", + composite: true, + }, + exclude: ["temp"], + }), + "/src/projects/project1/class1.ts": `class class1 {}`, + "/src/projects/project1/class1.d.ts": `declare class class1 {}`, + "/src/projects/project2/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "none", + composite: true, + }, + references: [ + { path: "../project1" }, + ], + }), + "/src/projects/project2/class2.ts": `class class2 {}`, }), - "/src/projects/project2/class2.ts": `class class2 {}`, - }), edits: [ { caption: "Add class3 to project1 and build it", @@ -430,40 +459,42 @@ declare global { caption: "Create output for class3", edit: fs => fs.writeFileSync("/src/projects/project1/class3.d.ts", `declare class class3 {}`, "utf-8"), }, - ] + ], }); verifyTsc({ scenario: "incremental", subScenario: "when project has strict true", commandLineArgs: ["-noEmit", "-p", `src/project`], - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - incremental: true, - strict: true, - }, + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + incremental: true, + strict: true, + }, + }), + "/src/project/class1.ts": `export class class1 {}`, }), - "/src/project/class1.ts": `export class class1 {}`, - }), edits: noChangeOnlyRuns, - baselinePrograms: true + baselinePrograms: true, }); verifyTsc({ scenario: "incremental", subScenario: "serializing error chains", commandLineArgs: ["-p", `src/project`], - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - incremental: true, - strict: true, - jsx: "react", - module: "esnext", - }, - }), - "/src/project/index.tsx": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + incremental: true, + strict: true, + jsx: "react", + module: "esnext", + }, + }), + "/src/project/index.tsx": Utils.dedent` declare namespace JSX { interface ElementChildrenAttribute { children: {}; } interface IntrinsicElements { div: {} } @@ -476,16 +507,17 @@ declare global { (
- )` - }, `\ninterface ReadonlyArray { readonly length: number }`), + )`, + }, `\ninterface ReadonlyArray { readonly length: number }`), edits: noChangeOnlyRuns, }); verifyTsc({ scenario: "incremental", subScenario: "ts file with no-default-lib that augments the global scope", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": Utils.dedent` /// /// @@ -496,7 +528,7 @@ declare global { export {}; `, - "/src/project/tsconfig.json": Utils.dedent` + "/src/project/tsconfig.json": Utils.dedent` { "compilerOptions": { "target": "ESNext", @@ -505,24 +537,25 @@ declare global { "outDir": "dist", }, }`, - }), + }), commandLineArgs: ["--p", "src/project", "--rootDir", "src/project/src"], - modifyFs: (fs) => { + modifyFs: fs => { fs.writeFileSync("/lib/lib.esnext.d.ts", libContent); - } + }, }); verifyTsc({ scenario: "incremental", subScenario: "change to type that gets used as global through export in another file", commandLineArgs: ["-p", `src/project`], - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { composite: true }, }), - "/src/project/class1.ts": `const a: MagicNumber = 1; + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { composite: true } }), + "/src/project/class1.ts": `const a: MagicNumber = 1; console.log(a);`, - "/src/project/constants.ts": "export default 1;", - "/src/project/types.d.ts": `type MagicNumber = typeof import('./constants').default`, - }), + "/src/project/constants.ts": "export default 1;", + "/src/project/types.d.ts": `type MagicNumber = typeof import('./constants').default`, + }), edits: [{ caption: "Modify imports used in global file", edit: fs => fs.writeFileSync("/src/project/constants.ts", "export default 2;"), @@ -533,14 +566,15 @@ console.log(a);`, scenario: "incremental", subScenario: "change to type that gets used as global through export in another file through indirect import", commandLineArgs: ["-p", `src/project`], - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { composite: true }, }), - "/src/project/class1.ts": `const a: MagicNumber = 1; + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { composite: true } }), + "/src/project/class1.ts": `const a: MagicNumber = 1; console.log(a);`, - "/src/project/constants.ts": "export default 1;", - "/src/project/reexport.ts": `export { default as ConstantNumber } from "./constants"`, - "/src/project/types.d.ts": `type MagicNumber = typeof import('./reexport').ConstantNumber`, - }), + "/src/project/constants.ts": "export default 1;", + "/src/project/reexport.ts": `export { default as ConstantNumber } from "./constants"`, + "/src/project/types.d.ts": `type MagicNumber = typeof import('./reexport').ConstantNumber`, + }), edits: [{ caption: "Modify imports used in global file", edit: fs => fs.writeFileSync("/src/project/constants.ts", "export default 2;"), @@ -552,14 +586,15 @@ console.log(a);`, scenario: "incremental", subScenario: `change to modifier of class expression field${declaration ? " with declaration emit enabled" : ""}`, commandLineArgs: ["-p", "src/project", "--incremental"], - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { declaration } }), - "/src/project/main.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { declaration } }), + "/src/project/main.ts": Utils.dedent` import MessageablePerson from './MessageablePerson.js'; function logMessage( person: MessageablePerson ) { console.log( person.message ); }`, - "/src/project/MessageablePerson.ts": Utils.dedent` + "/src/project/MessageablePerson.ts": Utils.dedent` const Messageable = () => { return class MessageableClass { public message = 'hello'; @@ -568,11 +603,15 @@ console.log(a);`, const wrapper = () => Messageable(); type MessageablePerson = InstanceType>; export default MessageablePerson;`, - }), - modifyFs: fs => appendText(fs, "/lib/lib.d.ts", Utils.dedent` + }), + modifyFs: fs => + appendText( + fs, + "/lib/lib.d.ts", + Utils.dedent` type ReturnType any> = T extends (...args: any) => infer R ? R : any; - type InstanceType any> = T extends abstract new (...args: any) => infer R ? R : any;` - ), + type InstanceType any> = T extends abstract new (...args: any) => infer R ? R : any;`, + ), edits: [ { caption: "modify public to protected", @@ -591,17 +630,18 @@ console.log(a);`, verifyTsc({ scenario: "incremental", subScenario: `when declarationMap changes`, - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - noEmitOnError: true, - declaration: true, - composite: true, - } + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + noEmitOnError: true, + declaration: true, + composite: true, + }, + }), + "/src/project/a.ts": "const x = 10;", + "/src/project/b.ts": "const y = 10;", }), - "/src/project/a.ts": "const x = 10;", - "/src/project/b.ts": "const y = 10;" - }), commandLineArgs: ["--p", "/src/project"], edits: [ { @@ -612,31 +652,32 @@ console.log(a);`, `Clean build does not emit any file so will have emitSignatures with all files since they are not emitted`, `Incremental build has emitSignatures from before, so it will have a.ts with signature since file.version isnt same`, `Incremental build will also have emitSignatureDtsMapDiffers for both files since the emitSignatures were without declarationMap but currentOptions have declrationMap`, - ] + ], }, { caption: "fix error declarationMap", edit: fs => replaceText(fs, "/src/project/a.ts", "x: 20", "x"), commandLineArgs: ["--p", "/src/project", "--declarationMap"], }, - ] + ], }); verifyTsc({ scenario: "incremental", subScenario: `when declarationMap changes with outFile`, - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - noEmitOnError: true, - declaration: true, - composite: true, - outFile: "../outFile.js", - } + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + noEmitOnError: true, + declaration: true, + composite: true, + outFile: "../outFile.js", + }, + }), + "/src/project/a.ts": "const x = 10;", + "/src/project/b.ts": "const y = 10;", }), - "/src/project/a.ts": "const x = 10;", - "/src/project/b.ts": "const y = 10;" - }), commandLineArgs: ["--p", "/src/project"], edits: [ { @@ -649,7 +690,7 @@ console.log(a);`, edit: fs => replaceText(fs, "/src/project/a.ts", "x: 20", "x"), commandLineArgs: ["--p", "/src/project", "--declarationMap"], }, - ] + ], }); describe("different options::", () => { @@ -669,7 +710,7 @@ console.log(a);`, discrepancyExplanation: () => [ `Clean build tsbuildinfo will have compilerOptions with composite and ${option.replace(/-/g, "")}`, `Incremental build will detect that it doesnt need to rebuild so tsbuild info is from before which has option composite only`, - ] + ], }; } function withEmitDeclarationOnlyChangeAndDiscrepancyExplanation(caption: string): TestTscEdit { @@ -678,7 +719,7 @@ console.log(a);`, edit.discrepancyExplanation = () => [ ...discrepancyExplanation(), `Clean build info does not have js section because its fresh build`, - `Incremental build info has js section from old build` + `Incremental build info has js section from old build`, ]; return edit; } @@ -822,37 +863,39 @@ console.log(a);`, scenario: "incremental", subScenario: "when file is deleted", commandLineArgs: ["-p", `/src/project`], - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - composite: true, - outDir: "outDir", - }, + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + composite: true, + outDir: "outDir", + }, + }), + "/src/project/file1.ts": `export class C { }`, + "/src/project/file2.ts": `export class D { }`, }), - "/src/project/file1.ts": `export class C { }`, - "/src/project/file2.ts": `export class D { }`, - }), edits: [ { caption: "delete file with imports", edit: fs => fs.unlinkSync("/src/project/file2.ts"), }, - ] + ], }); verifyTsc({ scenario: "incremental", subScenario: "file deleted before fixing error with noEmitOnError", - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - outDir: "outDir", - noEmitOnError: true, - }, + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + outDir: "outDir", + noEmitOnError: true, + }, + }), + "/src/project/file1.ts": `export const x: 30 = "hello";`, + "/src/project/file2.ts": `export class D { }`, }), - "/src/project/file1.ts": `export const x: 30 = "hello";`, - "/src/project/file2.ts": `export class D { }`, - }), commandLineArgs: ["--p", "/src/project", "-i"], edits: [{ caption: "delete file without error", diff --git a/src/testRunner/unittests/tsc/libraryResolution.ts b/src/testRunner/unittests/tsc/libraryResolution.ts index c922ec87fa989..a2f7f49c05d60 100644 --- a/src/testRunner/unittests/tsc/libraryResolution.ts +++ b/src/testRunner/unittests/tsc/libraryResolution.ts @@ -1,5 +1,10 @@ -import { getCommandLineArgsForLibResolution, getFsForLibResolution } from "../helpers/libraryResolution"; -import { verifyTsc } from "../helpers/tsc"; +import { + getCommandLineArgsForLibResolution, + getFsForLibResolution, +} from "../helpers/libraryResolution"; +import { + verifyTsc, +} from "../helpers/tsc"; describe("unittests:: tsc:: libraryResolution:: library file resolution", () => { function verify(libRedirection?: true, withoutConfig?: true) { @@ -15,4 +20,4 @@ describe("unittests:: tsc:: libraryResolution:: library file resolution", () => verify(/*libRedirection*/ true); verify(/*libRedirection*/ undefined, /*withoutConfig*/ true); verify(/*libRedirection*/ true, /*withoutConfig*/ true); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsc/listFilesOnly.ts b/src/testRunner/unittests/tsc/listFilesOnly.ts index 1ff81276d2227..efff95327fa6e 100644 --- a/src/testRunner/unittests/tsc/listFilesOnly.ts +++ b/src/testRunner/unittests/tsc/listFilesOnly.ts @@ -3,36 +3,41 @@ import { noChangeRun, verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsc:: listFilesOnly::", () => { verifyTsc({ scenario: "listFilesOnly", subScenario: "combined with watch", - fs: () => loadProjectFromFiles({ - "/src/test.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/test.ts": Utils.dedent` export const x = 1;`, - }), - commandLineArgs: ["/src/test.ts", "--watch", "--listFilesOnly"] + }), + commandLineArgs: ["/src/test.ts", "--watch", "--listFilesOnly"], }); verifyTsc({ scenario: "listFilesOnly", subScenario: "loose file", - fs: () => loadProjectFromFiles({ - "/src/test.ts": Utils.dedent` + fs: () => + loadProjectFromFiles({ + "/src/test.ts": Utils.dedent` export const x = 1;`, - }), - commandLineArgs: ["/src/test.ts", "--listFilesOnly"] + }), + commandLineArgs: ["/src/test.ts", "--listFilesOnly"], }); verifyTsc({ scenario: "listFilesOnly", subScenario: "combined with incremental", - fs: () => loadProjectFromFiles({ - "/src/test.ts": `export const x = 1;`, - "/src/tsconfig.json": "{}" - }), + fs: () => + loadProjectFromFiles({ + "/src/test.ts": `export const x = 1;`, + "/src/tsconfig.json": "{}", + }), commandLineArgs: ["-p", "/src", "--incremental", "--listFilesOnly"], edits: [ { @@ -43,7 +48,7 @@ describe("unittests:: tsc:: listFilesOnly::", () => { { ...noChangeRun, commandLineArgs: ["-p", "/src", "--incremental"], - } - ] + }, + ], }); }); diff --git a/src/testRunner/unittests/tsc/moduleResolution.ts b/src/testRunner/unittests/tsc/moduleResolution.ts index 7be319098fcdc..0ff875796ccc6 100644 --- a/src/testRunner/unittests/tsc/moduleResolution.ts +++ b/src/testRunner/unittests/tsc/moduleResolution.ts @@ -1,6 +1,15 @@ -import { getFsConentsForNode10ResultAtTypesPackageJson, getFsContentsForNode10Result, getFsContentsForNode10ResultDts, getFsContentsForNode10ResultPackageJson } from "../helpers/node10Result"; -import { verifyTsc } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + getFsConentsForNode10ResultAtTypesPackageJson, + getFsContentsForNode10Result, + getFsContentsForNode10ResultDts, + getFsContentsForNode10ResultPackageJson, +} from "../helpers/node10Result"; +import { + verifyTsc, +} from "../helpers/tsc"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsc:: moduleResolution::", () => { verifyTsc({ @@ -58,6 +67,6 @@ describe("unittests:: tsc:: moduleResolution::", () => { caption: "add the ndoe10Result in package/types", edit: fs => fs.writeFileSync("/home/src/projects/project/node_modules/foo2/index.d.ts", getFsContentsForNode10ResultDts("foo2")), }, - ] + ], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsc/projectReferences.ts b/src/testRunner/unittests/tsc/projectReferences.ts index e6bd7ce6caf20..bd3df222617d7 100644 --- a/src/testRunner/unittests/tsc/projectReferences.ts +++ b/src/testRunner/unittests/tsc/projectReferences.ts @@ -1,45 +1,49 @@ import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsc:: projectReferences::", () => { verifyTsc({ scenario: "projectReferences", subScenario: "when project contains invalid project reference", - fs: () => loadProjectFromFiles({ - "/src/project/src/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - module: "amd", - outFile: "theApp.js" - }, - references: [ - { path: "../Util/Dates" } - ] + fs: () => + loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "amd", + outFile: "theApp.js", + }, + references: [ + { path: "../Util/Dates" }, + ], + }), }), - }), commandLineArgs: ["--p", "src/project"], }); verifyTsc({ scenario: "projectReferences", subScenario: "when project references composite project with noEmit", - fs: () => loadProjectFromFiles({ - "/src/utils/index.ts": "export const x = 10;", - "/src/utils/tsconfig.json": JSON.stringify({ - compilerOptions: { - composite: true, - noEmit: true, - } - }), - "/src/project/index.ts": `import { x } from "../utils";`, - "/src/project/tsconfig.json": JSON.stringify({ - references: [ - { path: "../utils" } - ] + fs: () => + loadProjectFromFiles({ + "/src/utils/index.ts": "export const x = 10;", + "/src/utils/tsconfig.json": JSON.stringify({ + compilerOptions: { + composite: true, + noEmit: true, + }, + }), + "/src/project/index.ts": `import { x } from "../utils";`, + "/src/project/tsconfig.json": JSON.stringify({ + references: [ + { path: "../utils" }, + ], + }), }), - }), - commandLineArgs: ["--p", "src/project"] + commandLineArgs: ["--p", "src/project"], }); }); diff --git a/src/testRunner/unittests/tsc/projectReferencesConfig.ts b/src/testRunner/unittests/tsc/projectReferencesConfig.ts index ae2f4c736cc39..4a631c946702f 100644 --- a/src/testRunner/unittests/tsc/projectReferencesConfig.ts +++ b/src/testRunner/unittests/tsc/projectReferencesConfig.ts @@ -1,6 +1,10 @@ import * as ts from "../../_namespaces/ts"; -import { verifyTsc } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + verifyTsc, +} from "../helpers/tsc"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; function emptyModule() { return "export { };"; @@ -17,37 +21,42 @@ function moduleImporting(...names: string[]) { function getConfig({ references, options, config }: { references?: (string | ts.ProjectReference)[]; options?: ts.CompilerOptions; - config?: object + config?: object; } = {}) { - return JSON.stringify({ - compilerOptions: { - composite: true, - outDir: "bin", - ...options + return JSON.stringify( + { + compilerOptions: { + composite: true, + outDir: "bin", + ...options, + }, + references: references?.map(r => { + if (typeof r === "string") { + return { path: r }; + } + return r; + }) || [], + ...config, }, - references: references?.map(r => { - if (typeof r === "string") { - return { path: r }; - } - return r; - }) || [], - ...config, - }, undefined, " "); + undefined, + " ", + ); } describe("unittests:: config:: project-references meta check", () => { verifyTsc({ scenario: "projectReferencesConfig", subScenario: "default setup was created correctly", - fs: () => loadProjectFromFiles({ - "/primary/tsconfig.json": getConfig(), - "/primary/a.ts": emptyModule(), - "/secondary/tsconfig.json": getConfig({ - references: ["../primary"] + fs: () => + loadProjectFromFiles({ + "/primary/tsconfig.json": getConfig(), + "/primary/a.ts": emptyModule(), + "/secondary/tsconfig.json": getConfig({ + references: ["../primary"], + }), + "/secondary/b.ts": moduleImporting("../primary/a"), }), - "/secondary/b.ts": moduleImporting("../primary/a"), - }), - commandLineArgs: ["--p", "/primary/tsconfig.json"] + commandLineArgs: ["--p", "/primary/tsconfig.json"], }); }); @@ -58,114 +67,121 @@ describe("unittests:: config:: project-references constraint checking for settin verifyTsc({ scenario: "projectReferencesConfig", subScenario: "errors when declaration = false", - fs: () => loadProjectFromFiles({ - "/primary/tsconfig.json": getConfig({ - options: { - declaration: false - } + fs: () => + loadProjectFromFiles({ + "/primary/tsconfig.json": getConfig({ + options: { + declaration: false, + }, + }), + "/primary/a.ts": emptyModule(), }), - "/primary/a.ts": emptyModule(), - }), - commandLineArgs: ["--p", "/primary/tsconfig.json"] + commandLineArgs: ["--p", "/primary/tsconfig.json"], }); verifyTsc({ scenario: "projectReferencesConfig", subScenario: "errors when the referenced project doesnt have composite", - fs: () => loadProjectFromFiles({ - "/primary/tsconfig.json": getConfig({ - options: { - composite: false - } + fs: () => + loadProjectFromFiles({ + "/primary/tsconfig.json": getConfig({ + options: { + composite: false, + }, + }), + "/primary/a.ts": emptyModule(), + "/reference/tsconfig.json": getConfig({ + references: ["../primary"], + config: { + files: ["b.ts"], + }, + }), + "/reference/b.ts": moduleImporting("../primary/a"), }), - "/primary/a.ts": emptyModule(), - "/reference/tsconfig.json": getConfig({ - references: ["../primary"], - config: { - files: ["b.ts"] - } - }), - "/reference/b.ts": moduleImporting("../primary/a"), - }), - commandLineArgs: ["--p", "/reference/tsconfig.json"] + commandLineArgs: ["--p", "/reference/tsconfig.json"], }); verifyTsc({ scenario: "projectReferencesConfig", subScenario: "does not error when the referenced project doesnt have composite if its a container project", - fs: () => loadProjectFromFiles({ - "/primary/tsconfig.json": getConfig({ - options: { - composite: false - } + fs: () => + loadProjectFromFiles({ + "/primary/tsconfig.json": getConfig({ + options: { + composite: false, + }, + }), + "/primary/a.ts": emptyModule(), + "/reference/tsconfig.json": getConfig({ + references: ["../primary"], + config: { + files: [], + }, + }), + "/reference/b.ts": moduleImporting("../primary/a"), }), - "/primary/a.ts": emptyModule(), - "/reference/tsconfig.json": getConfig({ - references: ["../primary"], - config: { - files: [] - } - }), - "/reference/b.ts": moduleImporting("../primary/a"), - }), - commandLineArgs: ["--p", "/reference/tsconfig.json"] + commandLineArgs: ["--p", "/reference/tsconfig.json"], }); verifyTsc({ scenario: "projectReferencesConfig", subScenario: "errors when the file list is not exhaustive", - fs: () => loadProjectFromFiles({ - "/primary/tsconfig.json": getConfig({ - config: { - files: ["a.ts"] - } + fs: () => + loadProjectFromFiles({ + "/primary/tsconfig.json": getConfig({ + config: { + files: ["a.ts"], + }, + }), + "/primary/a.ts": "import * as b from './b'", + "/primary/b.ts": "export {}", }), - "/primary/a.ts": "import * as b from './b'", - "/primary/b.ts": "export {}", - }), - commandLineArgs: ["--p", "/primary/tsconfig.json"] + commandLineArgs: ["--p", "/primary/tsconfig.json"], }); verifyTsc({ scenario: "projectReferencesConfig", subScenario: "errors when the referenced project doesnt exist", - fs: () => loadProjectFromFiles({ - "/primary/tsconfig.json": getConfig({ - references: ["../foo"] + fs: () => + loadProjectFromFiles({ + "/primary/tsconfig.json": getConfig({ + references: ["../foo"], + }), + "/primary/a.ts": emptyModule(), }), - "/primary/a.ts": emptyModule(), - }), - commandLineArgs: ["--p", "/primary/tsconfig.json"] + commandLineArgs: ["--p", "/primary/tsconfig.json"], }); verifyTsc({ scenario: "projectReferencesConfig", subScenario: "errors when a prepended project reference doesnt set outFile", - fs: () => loadProjectFromFiles({ - "/primary/tsconfig.json": getConfig({ - references: [{ path: "../someProj", prepend: true }], + fs: () => + loadProjectFromFiles({ + "/primary/tsconfig.json": getConfig({ + references: [{ path: "../someProj", prepend: true }], + }), + "/primary/a.ts": emptyModule(), + "/someProj/tsconfig.json": getConfig(), + "/someProj/b.ts": "const x = 100;", }), - "/primary/a.ts": emptyModule(), - "/someProj/tsconfig.json": getConfig(), - "/someProj/b.ts": "const x = 100;", - }), - commandLineArgs: ["--p", "/primary/tsconfig.json", "--ignoreDeprecations", "5.0"] + commandLineArgs: ["--p", "/primary/tsconfig.json", "--ignoreDeprecations", "5.0"], }); verifyTsc({ scenario: "projectReferencesConfig", subScenario: "errors when a prepended project reference output doesnt exist", - fs: () => loadProjectFromFiles({ - "/primary/tsconfig.json": getConfig({ - references: [{ path: "../someProj", prepend: true }], - }), - "/primary/a.ts": "const y = x;", - "/someProj/tsconfig.json": getConfig({ - options: { outFile: "foo.js" } + fs: () => + loadProjectFromFiles({ + "/primary/tsconfig.json": getConfig({ + references: [{ path: "../someProj", prepend: true }], + }), + "/primary/a.ts": "const y = x;", + "/someProj/tsconfig.json": getConfig({ + options: { outFile: "foo.js" }, + }), + "/someProj/b.ts": "const x = 100;", }), - "/someProj/b.ts": "const x = 100;", - }), - commandLineArgs: ["--p", "/primary/tsconfig.json", "--ignoreDeprecations", "5.0"] + commandLineArgs: ["--p", "/primary/tsconfig.json", "--ignoreDeprecations", "5.0"], }); }); @@ -176,16 +192,17 @@ describe("unittests:: config:: project-references path mapping", () => { verifyTsc({ scenario: "projectReferencesConfig", subScenario: "redirects to the output dts file", - fs: () => loadProjectFromFiles({ - "/alpha/tsconfig.json": getConfig(), - "/alpha/a.ts": "export const m: number = 3;", - "/alpha/bin/a.d.ts": emptyModule(), - "/beta/tsconfig.json": getConfig({ - references: ["../alpha"] + fs: () => + loadProjectFromFiles({ + "/alpha/tsconfig.json": getConfig(), + "/alpha/a.ts": "export const m: number = 3;", + "/alpha/bin/a.d.ts": emptyModule(), + "/beta/tsconfig.json": getConfig({ + references: ["../alpha"], + }), + "/beta/b.ts": "import { m } from '../alpha/a'", }), - "/beta/b.ts": "import { m } from '../alpha/a'", - }), - commandLineArgs: ["--p", "/beta/tsconfig.json", "--explainFiles"] + commandLineArgs: ["--p", "/beta/tsconfig.json", "--explainFiles"], }); }); @@ -193,35 +210,37 @@ describe("unittests:: config:: project-references nice-behavior", () => { verifyTsc({ scenario: "projectReferencesConfig", subScenario: "issues a nice error when the input file is missing", - fs: () => loadProjectFromFiles({ - "/alpha/tsconfig.json": getConfig(), - "/alpha/a.ts": "export const m: number = 3;", - "/beta/tsconfig.json": getConfig({ - references: ["../alpha"] + fs: () => + loadProjectFromFiles({ + "/alpha/tsconfig.json": getConfig(), + "/alpha/a.ts": "export const m: number = 3;", + "/beta/tsconfig.json": getConfig({ + references: ["../alpha"], + }), + "/beta/b.ts": "import { m } from '../alpha/a'", }), - "/beta/b.ts": "import { m } from '../alpha/a'", - }), - commandLineArgs: ["--p", "/beta/tsconfig.json"] + commandLineArgs: ["--p", "/beta/tsconfig.json"], }); verifyTsc({ scenario: "projectReferencesConfig", subScenario: "issues a nice error when the input file is missing when module reference is not relative", - fs: () => loadProjectFromFiles({ - "/alpha/tsconfig.json": getConfig(), - "/alpha/a.ts": "export const m: number = 3;", - "/beta/tsconfig.json": getConfig({ - references: ["../alpha"], - options: { - baseUrl: "./", - paths: { - "@alpha/*": ["/alpha/*"] - } - } + fs: () => + loadProjectFromFiles({ + "/alpha/tsconfig.json": getConfig(), + "/alpha/a.ts": "export const m: number = 3;", + "/beta/tsconfig.json": getConfig({ + references: ["../alpha"], + options: { + baseUrl: "./", + paths: { + "@alpha/*": ["/alpha/*"], + }, + }, + }), + "/beta/b.ts": "import { m } from '@alpha/a'", }), - "/beta/b.ts": "import { m } from '@alpha/a'", - }), - commandLineArgs: ["--p", "/beta/tsconfig.json"] + commandLineArgs: ["--p", "/beta/tsconfig.json"], }); }); @@ -232,11 +251,12 @@ describe("unittests:: config:: project-references behavior changes under composi verifyTsc({ scenario: "projectReferencesConfig", subScenario: "doesnt infer the rootDir from source paths", - fs: () => loadProjectFromFiles({ - "/alpha/tsconfig.json": getConfig(), - "/alpha/src/a.ts": "export const m: number = 3;", - }), - commandLineArgs: ["--p", "/alpha/tsconfig.json"] + fs: () => + loadProjectFromFiles({ + "/alpha/tsconfig.json": getConfig(), + "/alpha/src/a.ts": "export const m: number = 3;", + }), + commandLineArgs: ["--p", "/alpha/tsconfig.json"], }); }); @@ -244,11 +264,12 @@ describe("unittests:: config:: project-references errors when a file in a compos verifyTsc({ scenario: "projectReferencesConfig", subScenario: "errors when a file is outside the rootdir", - fs: () => loadProjectFromFiles({ - "/alpha/tsconfig.json": getConfig(), - "/alpha/src/a.ts": "import * as b from '../../beta/b'", - "/beta/b.ts": "export { }", - }), - commandLineArgs: ["--p", "/alpha/tsconfig.json"] + fs: () => + loadProjectFromFiles({ + "/alpha/tsconfig.json": getConfig(), + "/alpha/src/a.ts": "import * as b from '../../beta/b'", + "/beta/b.ts": "export { }", + }), + commandLineArgs: ["--p", "/alpha/tsconfig.json"], }); }); diff --git a/src/testRunner/unittests/tsc/redirect.ts b/src/testRunner/unittests/tsc/redirect.ts index bd56f7aafdc53..83328e47c052f 100644 --- a/src/testRunner/unittests/tsc/redirect.ts +++ b/src/testRunner/unittests/tsc/redirect.ts @@ -1,37 +1,40 @@ import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsc:: redirect::", () => { verifyTsc({ scenario: "redirect", subScenario: "when redirecting ts file", - fs: () => loadProjectFromFiles({ - "/src/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - outDir: "out" - }, - include: [ - "copy1/node_modules/target/*", - "copy2/node_modules/target/*", - ] - }), - "/src/project/copy1/node_modules/target/index.ts": "export const a = 1;", - "/src/project/copy1/node_modules/target/import.ts": `import {} from "./";`, - "/src/project/copy1/node_modules/target/package.json": JSON.stringify({ - name: "target", - version: "1.0.0", - main: "index.js", - }), - "/src/project/copy2/node_modules/target/index.ts": "export const a = 1;", - "/src/project/copy2/node_modules/target/import.ts": `import {} from "./";`, - "/src/project/copy2/node_modules/target/package.json": JSON.stringify({ - name: "target", - version: "1.0.0", - main: "index.js", + fs: () => + loadProjectFromFiles({ + "/src/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + outDir: "out", + }, + include: [ + "copy1/node_modules/target/*", + "copy2/node_modules/target/*", + ], + }), + "/src/project/copy1/node_modules/target/index.ts": "export const a = 1;", + "/src/project/copy1/node_modules/target/import.ts": `import {} from "./";`, + "/src/project/copy1/node_modules/target/package.json": JSON.stringify({ + name: "target", + version: "1.0.0", + main: "index.js", + }), + "/src/project/copy2/node_modules/target/index.ts": "export const a = 1;", + "/src/project/copy2/node_modules/target/import.ts": `import {} from "./";`, + "/src/project/copy2/node_modules/target/package.json": JSON.stringify({ + name: "target", + version: "1.0.0", + main: "index.js", + }), }), - }), commandLineArgs: ["-p", "src/project"], }); }); diff --git a/src/testRunner/unittests/tsc/runWithoutArgs.ts b/src/testRunner/unittests/tsc/runWithoutArgs.ts index ee4c7a8ae0a41..d92f526aaf39d 100644 --- a/src/testRunner/unittests/tsc/runWithoutArgs.ts +++ b/src/testRunner/unittests/tsc/runWithoutArgs.ts @@ -1,7 +1,9 @@ import { verifyTsc, } from "../helpers/tsc"; -import { loadProjectFromFiles } from "../helpers/vfs"; +import { + loadProjectFromFiles, +} from "../helpers/vfs"; describe("unittests:: tsc:: runWithoutArgs::", () => { verifyTsc({ @@ -9,7 +11,7 @@ describe("unittests:: tsc:: runWithoutArgs::", () => { subScenario: "show help with ExitStatus.DiagnosticsPresent_OutputsSkipped", fs: () => loadProjectFromFiles({}), commandLineArgs: [], - environmentVariables: { TS_TEST_TERMINAL_WIDTH: "120" } + environmentVariables: { TS_TEST_TERMINAL_WIDTH: "120" }, }); verifyTsc({ @@ -24,7 +26,6 @@ describe("unittests:: tsc:: runWithoutArgs::", () => { subScenario: "does not add color when NO_COLOR is set", fs: () => loadProjectFromFiles({}), commandLineArgs: [], - environmentVariables: { NO_COLOR: "true" } + environmentVariables: { NO_COLOR: "true" }, }); - }); diff --git a/src/testRunner/unittests/tscWatch/consoleClearing.ts b/src/testRunner/unittests/tscWatch/consoleClearing.ts index f48ea56bd5060..60d1cb0e9690e 100644 --- a/src/testRunner/unittests/tscWatch/consoleClearing.ts +++ b/src/testRunner/unittests/tscWatch/consoleClearing.ts @@ -16,7 +16,7 @@ describe("unittests:: tsc-watch:: console clearing", () => { const scenario = "consoleClearing"; const file: File = { path: "/f.ts", - content: "" + content: "", }; const makeChangeToFile: TscWatchCompileChange[] = [{ @@ -42,11 +42,11 @@ describe("unittests:: tsc-watch:: console clearing", () => { describe("when preserveWatchOutput is true in config file", () => { const compilerOptions: ts.CompilerOptions = { - preserveWatchOutput: true + preserveWatchOutput: true, }; const configFile: File = { path: "/tsconfig.json", - content: JSON.stringify({ compilerOptions }) + content: JSON.stringify({ compilerOptions }), }; const files = [file, configFile, libFile]; it("using createWatchOfConfigFile ", () => { @@ -64,7 +64,7 @@ describe("unittests:: tsc-watch:: console clearing", () => { ...baseline, getPrograms: () => [[watch.getCurrentProgram().getProgram(), watch.getCurrentProgram()]], edits: makeChangeToFile, - watchOrSolution: watch + watchOrSolution: watch, }); }); verifyTscWatch({ diff --git a/src/testRunner/unittests/tscWatch/emit.ts b/src/testRunner/unittests/tscWatch/emit.ts index 4cd7a3b591920..f2866743888f9 100644 --- a/src/testRunner/unittests/tscWatch/emit.ts +++ b/src/testRunner/unittests/tscWatch/emit.ts @@ -17,24 +17,25 @@ describe("unittests:: tsc-watch:: emit with outFile or out setting", () => { scenario, subScenario: `emit with outFile or out setting/${subScenario}`, commandLineArgs: ["--w", "-p", "/a/tsconfig.json"], - sys: () => createWatchedSystem({ - "/a/a.ts": "let x = 1", - "/a/b.ts": "let y = 1", - "/a/tsconfig.json": JSON.stringify({ compilerOptions: { out, outFile } }), - [libFile.path]: libFile.content, - }), + sys: () => + createWatchedSystem({ + "/a/a.ts": "let x = 1", + "/a/b.ts": "let y = 1", + "/a/tsconfig.json": JSON.stringify({ compilerOptions: { out, outFile } }), + [libFile.path]: libFile.content, + }), edits: [ { caption: "Make change in the file", edit: sys => sys.writeFile("/a/a.ts", "let x = 11"), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Make change in the file again", edit: sys => sys.writeFile("/a/a.ts", "let xy = 11"), - timeouts: sys => sys.runQueuedTimeoutCallbacks() - } - ] + timeouts: sys => sys.runQueuedTimeoutCallbacks(), + }, + ], }); } verifyOutAndOutFileSetting("config does not have out or outFile"); @@ -49,19 +50,19 @@ describe("unittests:: tsc-watch:: emit with outFile or out setting", () => { sys: () => { const file1: File = { path: "/a/b/output/AnotherDependency/file1.d.ts", - content: "declare namespace Common.SomeComponent.DynamicMenu { enum Z { Full = 0, Min = 1, Average = 2, } }" + content: "declare namespace Common.SomeComponent.DynamicMenu { enum Z { Full = 0, Min = 1, Average = 2, } }", }; const file2: File = { path: "/a/b/dependencies/file2.d.ts", - content: "declare namespace Dependencies.SomeComponent { export class SomeClass { version: string; } }" + content: "declare namespace Dependencies.SomeComponent { export class SomeClass { version: string; } }", }; const file3: File = { path: "/a/b/project/src/main.ts", - content: "namespace Main { export function fooBar() {} }" + content: "namespace Main { export function fooBar() {} }", }; const file4: File = { path: "/a/b/project/src/main2.ts", - content: "namespace main.file4 { import DynamicMenu = Common.SomeComponent.DynamicMenu; export function foo(a: DynamicMenu.z) { } }" + content: "namespace main.file4 { import DynamicMenu = Common.SomeComponent.DynamicMenu; export function foo(a: DynamicMenu.z) { } }", }; const configFile: File = { path: "/a/b/project/tsconfig.json", @@ -69,8 +70,8 @@ describe("unittests:: tsc-watch:: emit with outFile or out setting", () => { compilerOptions: useOutFile ? { outFile: "../output/common.js", target: "es5" } : { outDir: "../output", target: "es5" }, - files: [file1.path, file2.path, file3.path, file4.path] - }) + files: [file1.path, file2.path, file3.path, file4.path], + }), }; return createWatchedSystem([file1, file2, file3, file4, libFile, configFile]); }, @@ -95,14 +96,14 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { getAdditionalFileOrFolder?: () => File[]; /** initial list of files to emit if not the default list */ firstReloadFileList?: string[]; - changes: TscWatchCompileChange[] + changes: TscWatchCompileChange[]; } function verifyTscWatchEmit({ subScenario, configObj, getAdditionalFileOrFolder, firstReloadFileList, - changes + changes, }: VerifyTscWatchEmit) { verifyTscWatch({ scenario, @@ -131,20 +132,21 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { const globalFile3: File = { path: globalFilePath, - content: `interface GlobalFoo { age: number }` + content: `interface GlobalFoo { age: number }`, }; const configFile: File = { path: configFilePath, - content: JSON.stringify(configObj || {}) + content: JSON.stringify(configObj || {}), }; const additionalFiles = getAdditionalFileOrFolder?.() || ts.emptyArray; const files = [moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile, ...additionalFiles]; - return createWatchedSystem(firstReloadFileList ? - ts.map(firstReloadFileList, fileName => ts.find(files, file => file.path === fileName)!) : - files + return createWatchedSystem( + firstReloadFileList ? + ts.map(firstReloadFileList, fileName => ts.find(files, file => file.path === fileName)!) : + files, ); }, - edits: changes + edits: changes, }); } @@ -165,8 +167,8 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { caption: "Change the content of moduleFile1 to `export var T: number;export function Foo() { console.log('hi'); };`", edit: sys => sys.writeFile(moduleFile1Path, `export var T: number;export function Foo() { console.log('hi'); };`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ @@ -197,8 +199,8 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { modifyModuleFile1Shape(sys); }, timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ @@ -211,8 +213,8 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { sys.deleteFile(file1Consumer2Path); }, timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ @@ -225,8 +227,8 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { modifyModuleFile1Shape(sys); }, timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ @@ -238,8 +240,8 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { caption: "change file1 internal, and verify only file1 is affected", edit: sys => sys.appendFile(moduleFile1Path, "var T1: number;"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ @@ -249,31 +251,31 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { caption: "change shape of global file", edit: sys => sys.appendFile(globalFilePath, "var T2: string;"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ subScenario: "should always return the file itself if '--isolatedModules' is specified", configObj: { compilerOptions: { isolatedModules: true } }, changes: [ - changeModuleFile1Shape - ] + changeModuleFile1Shape, + ], }); verifyTscWatchEmit({ subScenario: "should always return the file itself if '--out' or '--outFile' is specified", configObj: { compilerOptions: { module: "system", outFile: "/a/b/out.js" } }, changes: [ - changeModuleFile1Shape - ] + changeModuleFile1Shape, + ], }); verifyTscWatchEmit({ subScenario: "should return cascaded affected file list", getAdditionalFileOrFolder: () => [{ path: "/a/b/file1Consumer1Consumer1.ts", - content: `import {y} from "./file1Consumer1";` + content: `import {y} from "./file1Consumer1";`, }], changes: [ { @@ -289,8 +291,8 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { sys.writeFile(moduleFile1Path, `export var T2: number;export function Foo() { };`); }, timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ @@ -299,13 +301,13 @@ describe("unittests:: tsc-watch:: emit for configured projects", () => { { path: "/a/b/file1.ts", content: `/// -export var t1 = 10;` +export var t1 = 10;`, }, { path: "/a/b/file2.ts", content: `/// -export var t2 = 10;` - } +export var t2 = 10;`, + }, ], firstReloadFileList: [libFile.path, "/a/b/file1.ts", "/a/b/file2.ts", configFilePath], changes: [ @@ -313,8 +315,8 @@ export var t2 = 10;` caption: "change file1", edit: sys => sys.appendFile("/a/b/file1.ts", "export var t3 = 10;"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ @@ -322,7 +324,7 @@ export var t2 = 10;` getAdditionalFileOrFolder: () => [{ path: "/a/b/referenceFile1.ts", content: `/// -export var x = Foo();` +export var x = Foo();`, }], firstReloadFileList: [libFile.path, "/a/b/referenceFile1.ts", moduleFile1Path, configFilePath], changes: [ @@ -330,8 +332,8 @@ export var x = Foo();` caption: "delete moduleFile1", edit: sys => sys.deleteFile(moduleFile1Path), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatchEmit({ @@ -339,7 +341,7 @@ export var x = Foo();` getAdditionalFileOrFolder: () => [{ path: "/a/b/referenceFile1.ts", content: `/// -export var x = Foo();` +export var x = Foo();`, }], firstReloadFileList: [libFile.path, "/a/b/referenceFile1.ts", configFilePath], changes: [ @@ -352,8 +354,8 @@ export var x = Foo();` caption: "create moduleFile2", edit: sys => sys.writeFile(moduleFile2Path, "export var Foo4 = 10;"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); }); @@ -363,22 +365,23 @@ describe("unittests:: tsc-watch:: emit file content", () => { scenario, subScenario: `emit file content/${subScenario}`, commandLineArgs: ["--w", "/a/app.ts"], - sys: () => createWatchedSystem( - [ - { - path: "/a/app.ts", - content: ["var x = 1;", "var y = 2;"].join(newLine) - }, - libFile - ], - { newLine } - ), + sys: () => + createWatchedSystem( + [ + { + path: "/a/app.ts", + content: ["var x = 1;", "var y = 2;"].join(newLine), + }, + libFile, + ], + { newLine }, + ), edits: [ { caption: "Append a line", edit: sys => sys.appendFile("/a/app.ts", newLine + "var z = 3;"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); } @@ -392,22 +395,22 @@ describe("unittests:: tsc-watch:: emit file content", () => { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: `export function Foo() { return 10; }` + content: `export function Foo() { return 10; }`, }; const file2 = { path: "/a/b/f2.ts", - content: `import {Foo} from "./f1"; export let y = Foo();` + content: `import {Foo} from "./f1"; export let y = Foo();`, }; const file3 = { path: "/a/b/f3.ts", - content: `import {y} from "./f2"; let x = y;` + content: `import {y} from "./f2"; let x = y;`, }; const configFile = { path: "/a/b/tsconfig.json", - content: "{}" + content: "{}", }; return createWatchedSystem([file1, file2, file3, configFile, libFile]); }, @@ -421,7 +424,7 @@ describe("unittests:: tsc-watch:: emit file content", () => { caption: "Again Append content to f1", edit: sys => sys.appendFile("/a/b/f1.ts", "export function fooN() { return 2; }"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); @@ -433,15 +436,15 @@ describe("unittests:: tsc-watch:: emit file content", () => { const currentDirectory = "/user/someone/projects/myproject"; const file1: File = { path: `${currentDirectory}/file1.ts`, - content: "export const enum E1 { V = 1 }" + content: "export const enum E1 { V = 1 }", }; const file2: File = { path: `${currentDirectory}/file2.ts`, - content: `import { E1 } from "./file1"; export const enum E2 { V = E1.V }` + content: `import { E1 } from "./file1"; export const enum E2 { V = E1.V }`, }; const file3: File = { path: `${currentDirectory}/file3.ts`, - content: `import { E2 } from "./file2"; const v: E2 = E2.V;` + content: `import { E2 } from "./file2"; const v: E2 = E2.V;`, }; return createWatchedSystem([file1, file2, file3, libFile]); }, @@ -450,7 +453,7 @@ describe("unittests:: tsc-watch:: emit file content", () => { caption: "Append content to file3", edit: sys => sys.appendFile("/user/someone/projects/myproject/file3.ts", "function foo2() { return 2; }"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); @@ -462,15 +465,15 @@ describe("unittests:: tsc-watch:: emit file content", () => { const projectLocation = "/home/username/project"; const file: File = { path: `${projectLocation}/app/file.ts`, - content: "var a = 10;" + content: "var a = 10;", }; const configFile: File = { path: `${projectLocation}/tsconfig.json`, content: JSON.stringify({ include: [ - "app/**/*.ts" - ] - }) + "app/**/*.ts", + ], + }), }; const files = [file, configFile, libFile]; return createWatchedSystem(files, { currentDirectory: projectLocation, useCaseSensitiveFileNames: true }); @@ -480,8 +483,8 @@ describe("unittests:: tsc-watch:: emit file content", () => { caption: "file is deleted and then created to modify content", edit: sys => sys.appendFile("/home/username/project/app/file.ts", "\nvar b = 10;", { invokeFileDeleteCreateAsPartInsteadOfChange: true }), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); }); @@ -497,33 +500,34 @@ describe("unittests:: tsc-watch:: emit with when module emit is specified as nod compilerOptions: { module: "none", allowJs: true, - outDir: "Static/scripts/" + outDir: "Static/scripts/", }, include: [ - "Scripts/**/*" + "Scripts/**/*", ], - }) + }), }; const file1: File = { path: "/a/rootFolder/project/Scripts/TypeScript.ts", - content: "var z = 10;" + content: "var z = 10;", }; const file2: File = { path: "/a/rootFolder/project/Scripts/Javascript.js", - content: "var zz = 10;" + content: "var zz = 10;", }; return createWatchedSystem([configFile, file1, file2, libFile]); }, edits: [ { caption: "Modify typescript file", - edit: sys => sys.modifyFile( - "/a/rootFolder/project/Scripts/TypeScript.ts", - "var zz30 = 100;", - { invokeDirectoryWatcherInsteadOfFileChanged: true }, - ), + edit: sys => + sys.modifyFile( + "/a/rootFolder/project/Scripts/TypeScript.ts", + "var zz30 = 100;", + { invokeDirectoryWatcherInsteadOfFileChanged: true }, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); }); diff --git a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts index 926cf99ec5c4f..f46e0db56b05e 100644 --- a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts +++ b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts @@ -1,4 +1,6 @@ -import { libContent } from "../helpers/contents"; +import { + libContent, +} from "../helpers/contents"; import { TscWatchCompileChange, verifyTscWatch, @@ -13,10 +15,10 @@ import { describe("unittests:: tsc-watch:: Emit times and Error updates in builder after program changes", () => { const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: `{}` + content: `{}`, }; interface VerifyEmitAndErrorUpdates { - subScenario: string + subScenario: string; files: () => File[]; currentDirectory?: string; changes: TscWatchCompileChange[]; @@ -31,72 +33,78 @@ describe("unittests:: tsc-watch:: Emit times and Error updates in builder after scenario: "emitAndErrorUpdates", subScenario: `default/${subScenario}`, commandLineArgs: ["--w"], - sys: () => createWatchedSystem( - files(), - { currentDirectory: currentDirectory || "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + files(), + { currentDirectory: currentDirectory || "/user/username/projects/myproject" }, + ), edits: changes, - baselineIncremental: true + baselineIncremental: true, }); verifyTscWatch({ scenario: "emitAndErrorUpdates", subScenario: `defaultAndD/${subScenario}`, commandLineArgs: ["--w", "--d"], - sys: () => createWatchedSystem( - files(), - { currentDirectory: currentDirectory || "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + files(), + { currentDirectory: currentDirectory || "/user/username/projects/myproject" }, + ), edits: changes, - baselineIncremental: true + baselineIncremental: true, }); verifyTscWatch({ scenario: "emitAndErrorUpdates", subScenario: `isolatedModules/${subScenario}`, commandLineArgs: ["--w", "--isolatedModules"], - sys: () => createWatchedSystem( - files(), - { currentDirectory: currentDirectory || "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + files(), + { currentDirectory: currentDirectory || "/user/username/projects/myproject" }, + ), edits: changes, - baselineIncremental: true + baselineIncremental: true, }); verifyTscWatch({ scenario: "emitAndErrorUpdates", subScenario: `isolatedModulesAndD/${subScenario}`, commandLineArgs: ["--w", "--isolatedModules", "--d"], - sys: () => createWatchedSystem( - files(), - { currentDirectory: currentDirectory || "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + files(), + { currentDirectory: currentDirectory || "/user/username/projects/myproject" }, + ), edits: changes, - baselineIncremental: true + baselineIncremental: true, }); verifyTscWatch({ scenario: "emitAndErrorUpdates", subScenario: `assumeChangesOnlyAffectDirectDependencies/${subScenario}`, commandLineArgs: ["--w", "--assumeChangesOnlyAffectDirectDependencies"], - sys: () => createWatchedSystem( - files(), - { currentDirectory: currentDirectory || "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + files(), + { currentDirectory: currentDirectory || "/user/username/projects/myproject" }, + ), edits: changes, - baselineIncremental: true + baselineIncremental: true, }); verifyTscWatch({ scenario: "emitAndErrorUpdates", subScenario: `assumeChangesOnlyAffectDirectDependenciesAndD/${subScenario}`, commandLineArgs: ["--w", "--assumeChangesOnlyAffectDirectDependencies", "--d"], - sys: () => createWatchedSystem( - files(), - { currentDirectory: currentDirectory || "/user/username/projects/myproject" } - ), + sys: () => + createWatchedSystem( + files(), + { currentDirectory: currentDirectory || "/user/username/projects/myproject" }, + ), edits: changes, - baselineIncremental: true + baselineIncremental: true, }); } @@ -106,7 +114,7 @@ describe("unittests:: tsc-watch:: Emit times and Error updates in builder after content: `import {B} from './b'; declare var console: any; let b = new B(); -console.log(b.c.d);` +console.log(b.c.d);`, }; function verifyDeepImportChange(subScenario: string, bFile: File, cFile: File) { @@ -128,7 +136,7 @@ console.log(b.c.d);` caption: "Rename property d to d2 of class C", edit: sys => sys.writeFile(cFile.path, cFile.content.replace("d", "d2")), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); } @@ -139,19 +147,19 @@ console.log(b.c.d);` export class B { c = new C(); -}` +}`, }; const cFile: File = { path: `/user/username/projects/myproject/c.ts`, content: `export class C { d = 1; -}` +}`, }; verifyDeepImportChange( "errors for .ts change", bFile, - cFile + cFile, ); }); describe("updates errors when deep import through declaration file changes", () => { @@ -161,19 +169,19 @@ export class B export class B { c: C; -}` +}`, }; const cFile: File = { path: `/user/username/projects/myproject/c.d.ts`, content: `export class C { d: number; -}` +}`, }; verifyDeepImportChange( "errors for .d.ts change", bFile, - cFile + cFile, ); }); }); @@ -188,13 +196,13 @@ export class B export interface Coords { x2: number; y: number; -}` +}`, }; const bFile: File = { path: `/user/username/projects/myproject/b.ts`, content: `import { Point } from "./a"; export interface PointWrapper extends Point { -}` +}`, }; const cFile: File = { path: `/user/username/projects/myproject/c.ts`, @@ -207,16 +215,16 @@ export function getPoint(): PointWrapper { y: 2 } } -};` +};`, }; const dFile: File = { path: `/user/username/projects/myproject/d.ts`, content: `import { getPoint } from "./c"; -getPoint().c.x;` +getPoint().c.x;`, }; const eFile: File = { path: `/user/username/projects/myproject/e.ts`, - content: `import "./d";` + content: `import "./d";`, }; verifyEmitAndErrorUpdates({ subScenario: "file not exporting a deep multilevel import that changes", @@ -237,7 +245,7 @@ getPoint().c.x;` edit: sys => sys.writeFile(aFile.path, aFile.content.replace("x2", "x")), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); }); describe("updates errors when file transitively exported file changes", () => { @@ -245,8 +253,8 @@ getPoint().c.x;` path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ files: ["app.ts"], - compilerOptions: { baseUrl: "." } - }) + compilerOptions: { baseUrl: "." }, + }), }; const app: File = { path: `/user/username/projects/myproject/app.ts`, @@ -255,11 +263,11 @@ export class App { public constructor() { new Data().test(); } -}` +}`, }; const lib2Public: File = { path: `/user/username/projects/myproject/lib2/public.ts`, - content: `export * from "./data";` + content: `export * from "./data";`, }; const lib2Data: File = { path: `/user/username/projects/myproject/lib2/data.ts`, @@ -271,21 +279,21 @@ export class Data { } return result; } -}` +}`, }; const lib1Public: File = { path: `/user/username/projects/myproject/lib1/public.ts`, - content: `export * from "./tools/public";` + content: `export * from "./tools/public";`, }; const lib1ToolsPublic: File = { path: `/user/username/projects/myproject/lib1/tools/public.ts`, - content: `export * from "./toolsinterface";` + content: `export * from "./toolsinterface";`, }; const lib1ToolsInterface: File = { path: `/user/username/projects/myproject/lib1/tools/toolsinterface.ts`, content: `export interface ITest { title: string; -}` +}`, }; function verifyTransitiveExports(subScenario: string, files: readonly File[]) { @@ -307,14 +315,14 @@ export class Data { caption: "Rename property title to title2 of interface ITest", edit: sys => sys.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2")), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); } describe("when there are no circular import and exports", () => { verifyTransitiveExports( "no circular import/export", - [lib2Data] + [lib2Data], ); }); describe("when there are circular import and exports", () => { @@ -328,18 +336,18 @@ export class Data { } return result; } -}` +}`, }; const lib2Data2: File = { path: `/user/username/projects/myproject/lib2/data2.ts`, content: `import { Data } from "./data"; export class Data2 { public dat?: Data; -}` +}`, }; verifyTransitiveExports( "yes circular import/exports", - [lib2Data, lib2Data2] + [lib2Data, lib2Data2], ); }); }); @@ -350,7 +358,7 @@ export class Data2 { caption, edit: sys => sys.writeFile(`/user/username/projects/noEmitOnError/src/main.ts`, content), // build project - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }; } const noChange: TscWatchCompileChange = { @@ -362,19 +370,29 @@ export class Data2 { verifyEmitAndErrorUpdates({ subScenario: "with noEmitOnError", currentDirectory: `/user/username/projects/noEmitOnError`, - files: () => ["shared/types/db.ts", "src/main.ts", "src/other.ts", "tsconfig.json"] - .map(f => getTsBuildProjectFile("noEmitOnError", f)).concat({ path: libFile.path, content: libContent }), + files: () => + ["shared/types/db.ts", "src/main.ts", "src/other.ts", "tsconfig.json"] + .map(f => getTsBuildProjectFile("noEmitOnError", f)).concat({ path: libFile.path, content: libContent }), changes: [ noChange, - change("Fix Syntax error", `import { A } from "../shared/types/db"; + change( + "Fix Syntax error", + `import { A } from "../shared/types/db"; const a = { lastName: 'sdsd' -};`), - change("Semantic Error", `import { A } from "../shared/types/db"; -const a: string = 10;`), +};`, + ), + change( + "Semantic Error", + `import { A } from "../shared/types/db"; +const a: string = 10;`, + ), noChange, - change("Fix Semantic Error", `import { A } from "../shared/types/db"; -const a: string = "hello";`), + change( + "Fix Semantic Error", + `import { A } from "../shared/types/db"; +const a: string = "hello";`, + ), noChange, ], }); diff --git a/src/testRunner/unittests/tscWatch/extends.ts b/src/testRunner/unittests/tscWatch/extends.ts index d70f05d9830a9..db8ff56cd72d4 100644 --- a/src/testRunner/unittests/tscWatch/extends.ts +++ b/src/testRunner/unittests/tscWatch/extends.ts @@ -1,5 +1,9 @@ -import { getSymlinkedExtendsSys } from "../helpers/extends"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + getSymlinkedExtendsSys, +} from "../helpers/extends"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; describe("unittests:: tsc-watch:: extends::", () => { verifyTscWatch({ @@ -8,4 +12,4 @@ describe("unittests:: tsc-watch:: extends::", () => { sys: getSymlinkedExtendsSys, commandLineArgs: ["-w", "-p", "src", "--extendedDiagnostics"], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tscWatch/forceConsistentCasingInFileNames.ts b/src/testRunner/unittests/tscWatch/forceConsistentCasingInFileNames.ts index da9db45871b84..a1b5de3e42c38 100644 --- a/src/testRunner/unittests/tscWatch/forceConsistentCasingInFileNames.ts +++ b/src/testRunner/unittests/tscWatch/forceConsistentCasingInFileNames.ts @@ -13,17 +13,17 @@ import { describe("unittests:: tsc-watch:: forceConsistentCasingInFileNames", () => { const loggerFile: File = { path: `/user/username/projects/myproject/logger.ts`, - content: `export class logger { }` + content: `export class logger { }`, }; const anotherFile: File = { path: `/user/username/projects/myproject/another.ts`, - content: `import { logger } from "./logger"; new logger();` + content: `import { logger } from "./logger"; new logger();`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ - compilerOptions: { forceConsistentCasingInFileNames: true } - }) + compilerOptions: { forceConsistentCasingInFileNames: true }, + }), }; function verifyConsistentFileNames({ subScenario, changes }: { subScenario: string; changes: TscWatchCompileChange[]; }) { @@ -32,7 +32,7 @@ describe("unittests:: tsc-watch:: forceConsistentCasingInFileNames", () => { subScenario, commandLineArgs: ["--w", "--p", tsconfig.path], sys: () => createWatchedSystem([loggerFile, anotherFile, tsconfig, libFile]), - edits: changes + edits: changes, }); } @@ -43,8 +43,8 @@ describe("unittests:: tsc-watch:: forceConsistentCasingInFileNames", () => { caption: "Change module name from logger to Logger", edit: sys => sys.writeFile(anotherFile.path, anotherFile.content.replace("./logger", "./Logger")), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyConsistentFileNames({ @@ -54,8 +54,8 @@ describe("unittests:: tsc-watch:: forceConsistentCasingInFileNames", () => { caption: "Change name of file from logger to Logger", edit: sys => sys.renameFile(loggerFile.path, `/user/username/projects/myproject/Logger.ts`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -65,29 +65,33 @@ describe("unittests:: tsc-watch:: forceConsistentCasingInFileNames", () => { sys: () => { const moduleA: File = { path: `/user/username/projects/myproject/moduleA.ts`, - content: `import a = require("./ModuleC")` + content: `import a = require("./ModuleC")`, }; const moduleB: File = { path: `/user/username/projects/myproject/moduleB.ts`, - content: `import a = require("./moduleC")` + content: `import a = require("./moduleC")`, }; const moduleC: File = { path: `/user/username/projects/myproject/moduleC.ts`, - content: `export const x = 10;` + content: `export const x = 10;`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true } }) + content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true } }), }; return createWatchedSystem([moduleA, moduleB, moduleC, libFile, tsconfig], { currentDirectory: "/user/username/projects/myproject" }); }, edits: [ { caption: "Prepend a line to moduleA", - edit: sys => sys.prependFile(`/user/username/projects/myproject/moduleA.ts`, `// some comment - `), + edit: sys => + sys.prependFile( + `/user/username/projects/myproject/moduleA.ts`, + `// some comment + `, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); @@ -95,11 +99,12 @@ describe("unittests:: tsc-watch:: forceConsistentCasingInFileNames", () => { scenario: "forceConsistentCasingInFileNames", subScenario: "jsxImportSource option changed", commandLineArgs: ["--w", "--p", ".", "--explainFiles"], - sys: () => createWatchedSystem([ - libFile, - { - path: `/user/username/projects/myproject/node_modules/react/Jsx-runtime/index.d.ts`, - content: `export namespace JSX { + sys: () => + createWatchedSystem([ + libFile, + { + path: `/user/username/projects/myproject/node_modules/react/Jsx-runtime/index.d.ts`, + content: `export namespace JSX { interface Element {} interface IntrinsicElements { div: { @@ -111,23 +116,23 @@ export function jsx(...args: any[]): void; export function jsxs(...args: any[]): void; export const Fragment: unique symbol; `, - }, - { - path: `/user/username/projects/myproject/node_modules/react/package.json`, - content: JSON.stringify({ name: "react", version: "0.0.1" }) - }, - { - path: `/user/username/projects/myproject/index.tsx`, - content: `export const App = () =>
;` - }, - { - path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { jsx: "react-jsx", jsxImportSource: "react", forceConsistentCasingInFileNames: true }, - files: ["node_modules/react/Jsx-Runtime/index.d.ts", "index.tsx"] - }) - } - ], { currentDirectory: "/user/username/projects/myproject" }), + }, + { + path: `/user/username/projects/myproject/node_modules/react/package.json`, + content: JSON.stringify({ name: "react", version: "0.0.1" }), + }, + { + path: `/user/username/projects/myproject/index.tsx`, + content: `export const App = () =>
;`, + }, + { + path: `/user/username/projects/myproject/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { jsx: "react-jsx", jsxImportSource: "react", forceConsistentCasingInFileNames: true }, + files: ["node_modules/react/Jsx-Runtime/index.d.ts", "index.tsx"], + }), + }, + ], { currentDirectory: "/user/username/projects/myproject" }), }); function verifyWindowsStyleRoot(subScenario: string, windowsStyleRoot: string, projectRootRelative: string) { @@ -141,7 +146,7 @@ export const Fragment: unique symbol; content: ` export const a = 1; export const b = 2; -` +`, }; const moduleB: File = { path: `${windowsStyleRoot}/${projectRootRelative}/b.ts`, @@ -150,21 +155,25 @@ import { a } from "${windowsStyleRoot.toLocaleUpperCase()}/${projectRootRelative import { b } from "${windowsStyleRoot.toLocaleLowerCase()}/${projectRootRelative}/a" a;b; -` +`, }; const tsconfig: File = { path: `${windowsStyleRoot}/${projectRootRelative}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true } }) + content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true } }), }; return createWatchedSystem([moduleA, moduleB, libFile, tsconfig], { windowsStyleRoot, useCaseSensitiveFileNames: false }); }, edits: [ { caption: "Prepend a line to moduleA", - edit: sys => sys.prependFile(`${windowsStyleRoot}/${projectRootRelative}/a.ts`, `// some comment - `), + edit: sys => + sys.prependFile( + `${windowsStyleRoot}/${projectRootRelative}/a.ts`, + `// some comment + `, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); } @@ -179,12 +188,11 @@ a;b; commandLineArgs: ["--w", "--p", ".", "--explainFiles"], sys: () => { const moduleA: File = { - path: diskPath, content: ` export const a = 1; export const b = 2; -` +`, }; const symlinkA: SymLink = { path: `/user/username/projects/myproject/link.ts`, @@ -197,21 +205,25 @@ import { a } from "${importedPath}"; import { b } from "./link"; a;b; -` +`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true } }) + content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true } }), }; return createWatchedSystem([moduleA, symlinkA, moduleB, libFile, tsconfig], { currentDirectory: "/user/username/projects/myproject" }); }, edits: [ { caption: "Prepend a line to moduleA", - edit: sys => sys.prependFile(diskPath, `// some comment - `), + edit: sys => + sys.prependFile( + diskPath, + `// some comment + `, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); } @@ -229,12 +241,11 @@ a;b; commandLineArgs: ["--w", "--p", ".", "--explainFiles"], sys: () => { const moduleA: File = { - path: `${diskPath}/a.ts`, content: ` export const a = 1; export const b = 2; -` +`, }; const symlinkA: SymLink = { path: `/user/username/projects/myproject/link`, @@ -247,22 +258,26 @@ import { a } from "${importedPath}/a"; import { b } from "./link/a"; a;b; -` +`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, // Use outFile because otherwise the real and linked files will have the same output path - content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true, outFile: "out.js", module: "system" } }) + content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true, outFile: "out.js", module: "system" } }), }; return createWatchedSystem([moduleA, symlinkA, moduleB, libFile, tsconfig], { currentDirectory: "/user/username/projects/myproject" }); }, edits: [ { caption: "Prepend a line to moduleA", - edit: sys => sys.prependFile(`${diskPath}/a.ts`, `// some comment - `), + edit: sys => + sys.prependFile( + `${diskPath}/a.ts`, + `// some comment + `, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); } @@ -277,91 +292,93 @@ a;b; scenario: "forceConsistentCasingInFileNames", subScenario: "with nodeNext resolution", commandLineArgs: ["--w", "--explainFiles"], - sys: () => createWatchedSystem({ - "/Users/name/projects/web/src/bin.ts": `import { foo } from "yargs";`, - "/Users/name/projects/web/node_modules/@types/yargs/index.d.ts": "export function foo(): void;", - "/Users/name/projects/web/node_modules/@types/yargs/index.d.mts": "export function foo(): void;", - "/Users/name/projects/web/node_modules/@types/yargs/package.json": JSON.stringify({ - name: "yargs", - version: "17.0.12", - exports: { - ".": { - types: { - import: "./index.d.mts", - default: "./index.d.ts" - } + sys: () => + createWatchedSystem({ + "/Users/name/projects/web/src/bin.ts": `import { foo } from "yargs";`, + "/Users/name/projects/web/node_modules/@types/yargs/index.d.ts": "export function foo(): void;", + "/Users/name/projects/web/node_modules/@types/yargs/index.d.mts": "export function foo(): void;", + "/Users/name/projects/web/node_modules/@types/yargs/package.json": JSON.stringify({ + name: "yargs", + version: "17.0.12", + exports: { + ".": { + types: { + import: "./index.d.mts", + default: "./index.d.ts", + }, + }, }, - } - }), - "/Users/name/projects/web/tsconfig.json": JSON.stringify({ - compilerOptions: { - moduleResolution: "nodenext", - forceConsistentCasingInFileNames: true, - traceResolution: true, - } - }), - [libFile.path]: libFile.content, - }, { currentDirectory: "/Users/name/projects/web" }), + }), + "/Users/name/projects/web/tsconfig.json": JSON.stringify({ + compilerOptions: { + moduleResolution: "nodenext", + forceConsistentCasingInFileNames: true, + traceResolution: true, + }, + }), + [libFile.path]: libFile.content, + }, { currentDirectory: "/Users/name/projects/web" }), }); verifyTscWatch({ scenario: "forceConsistentCasingInFileNames", subScenario: "self name package reference", commandLineArgs: ["-w", "--explainFiles"], - sys: () => createWatchedSystem({ - "/Users/name/projects/web/package.json": JSON.stringify({ - name: "@this/package", - type: "module", - exports: { - ".": "./dist/index.js" - } - }), - "/Users/name/projects/web/index.ts": Utils.dedent` + sys: () => + createWatchedSystem({ + "/Users/name/projects/web/package.json": JSON.stringify({ + name: "@this/package", + type: "module", + exports: { + ".": "./dist/index.js", + }, + }), + "/Users/name/projects/web/index.ts": Utils.dedent` import * as me from "@this/package"; me.thing(); export function thing(): void {} `, - "/Users/name/projects/web/tsconfig.json": JSON.stringify({ - compilerOptions: { - module: "nodenext", - outDir: "./dist", - declarationDir: "./types", - composite: true, - forceConsistentCasingInFileNames: true, - traceResolution: true, - } - }), - "/a/lib/lib.esnext.full.d.ts": libFile.content, - }, { currentDirectory: "/Users/name/projects/web" }), + "/Users/name/projects/web/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "nodenext", + outDir: "./dist", + declarationDir: "./types", + composite: true, + forceConsistentCasingInFileNames: true, + traceResolution: true, + }, + }), + "/a/lib/lib.esnext.full.d.ts": libFile.content, + }, { currentDirectory: "/Users/name/projects/web" }), }); - verifyTscWatch({ scenario: "forceConsistentCasingInFileNames", subScenario: "package json is looked up for file", commandLineArgs: ["-w", "--explainFiles"], - sys: () => createWatchedSystem({ - "/Users/name/projects/lib-boilerplate/package.json": JSON.stringify({ - name: "lib-boilerplate", - version: "0.0.2", - type: "module", - exports: "./src/index.ts", - }), - "/Users/name/projects/lib-boilerplate/src/index.ts": Utils.dedent` + sys: () => + createWatchedSystem({ + "/Users/name/projects/lib-boilerplate/package.json": JSON.stringify({ + name: "lib-boilerplate", + version: "0.0.2", + type: "module", + exports: "./src/index.ts", + }), + "/Users/name/projects/lib-boilerplate/src/index.ts": Utils.dedent` export function thing(): void {} `, - "/Users/name/projects/lib-boilerplate/test/basic.spec.ts": Utils.dedent` + "/Users/name/projects/lib-boilerplate/test/basic.spec.ts": Utils.dedent` import { thing } from 'lib-boilerplate' `, - "/Users/name/projects/lib-boilerplate/tsconfig.json": JSON.stringify({ - compilerOptions: { - module: "node16", - target: "es2021", - forceConsistentCasingInFileNames: true, - traceResolution: true, - } - }), - "/a/lib/lib.es2021.full.d.ts": libFile.content, - }, { currentDirectory: "/Users/name/projects/lib-boilerplate" }), + "/Users/name/projects/lib-boilerplate/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "node16", + target: "es2021", + forceConsistentCasingInFileNames: true, + traceResolution: true, + }, + }), + "/a/lib/lib.es2021.full.d.ts": libFile.content, + }, { currentDirectory: "/Users/name/projects/lib-boilerplate" }), }); }); diff --git a/src/testRunner/unittests/tscWatch/incremental.ts b/src/testRunner/unittests/tscWatch/incremental.ts index 4bef1da5b5d87..c2218d1ae6037 100644 --- a/src/testRunner/unittests/tscWatch/incremental.ts +++ b/src/testRunner/unittests/tscWatch/incremental.ts @@ -1,7 +1,11 @@ import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; -import { CommandLineProgram } from "../helpers/baseline"; -import { libContent } from "../helpers/contents"; +import { + CommandLineProgram, +} from "../helpers/baseline"; +import { + libContent, +} from "../helpers/contents"; import { applyEdit, createBaseline, @@ -21,7 +25,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { const configFile: File = { path: `${project}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { incremental: true } }) + content: JSON.stringify({ compilerOptions: { incremental: true } }), }; interface VerifyIncrementalWatchEmitInput { @@ -43,7 +47,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { function verifyIncrementalWatchEmitWorker( { subScenario, files, optionsToExtend, modifyFs }: VerifyIncrementalWatchEmitInput, - incremental: boolean + incremental: boolean, ) { const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem(files(), { currentDirectory: project })); if (incremental) sys.exit = exitCode => sys.exitCode = exitCode; @@ -70,7 +74,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { getPrograms, oldPrograms, sys, - oldSnap + oldSnap, }); if (closer) closer.close(); } @@ -79,11 +83,11 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { describe("non module compilation", () => { const file1: File = { path: `${project}/file1.ts`, - content: "const x = 10;" + content: "const x = 10;", }; const file2: File = { path: `${project}/file2.ts`, - content: "const y = 20;" + content: "const y = 20;", }; describe("own file emit without errors", () => { function verify(subScenario: string, optionsToExtend?: readonly string[]) { @@ -102,7 +106,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { verifyIncrementalWatchEmit({ files: () => [libFile, file1, configFile, { path: file2.path, - content: `const y: string = 20;` + content: `const y: string = 20;`, }], subScenario: "own file emit with errors", modifyFs: host => host.writeFile(file1.path, file1.content.replace("x", "z")), @@ -111,7 +115,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { verifyIncrementalWatchEmit({ files: () => [libFile, file1, file2, { path: configFile.path, - content: JSON.stringify({ compilerOptions: { incremental: true, outFile: "out.js" } }) + content: JSON.stringify({ compilerOptions: { incremental: true, outFile: "out.js" } }), }], subScenario: "with --out", }); @@ -120,15 +124,15 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { describe("module compilation", () => { const file1: File = { path: `${project}/file1.ts`, - content: "export const x = 10;" + content: "export const x = 10;", }; const file2: File = { path: `${project}/file2.ts`, - content: "export const y = 20;" + content: "export const y = 20;", }; const config: File = { path: configFile.path, - content: JSON.stringify({ compilerOptions: { incremental: true, module: "amd" } }) + content: JSON.stringify({ compilerOptions: { incremental: true, module: "amd" } }), }; verifyIncrementalWatchEmit({ @@ -140,7 +144,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { describe("own file emit with errors", () => { const fileModified: File = { path: file2.path, - content: `export const y: string = 20;` + content: `export const y: string = 20;`, }; verifyIncrementalWatchEmit({ @@ -159,7 +163,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { projectReferences: parsedConfig.projectReferences, configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(parsedConfig), reportDiagnostic, - system + system, }); const command = ts.parseConfigFileWithSystem("tsconfig.json", {}, /*extendedConfigCache*/ undefined, /*watchOptionsToExtend*/ undefined, system, ts.noop)!; @@ -168,7 +172,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { options: command.options, projectReferences: command.projectReferences, configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(command), - host: ts.createIncrementalCompilerHost(command.options, system) + host: ts.createIncrementalCompilerHost(command.options, system), }); const state = builderProgram.getState(); @@ -197,7 +201,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { assert.deepEqual(state.compilerOptions, { incremental: true, module: ts.ModuleKind.AMD, - configFilePath: config.path + configFilePath: config.path, }); assert.equal(ts.arrayFrom(state.referencedMap!.keys()).length, 0); @@ -225,7 +229,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { verifyIncrementalWatchEmit({ files: () => [libFile, file1, file2, { path: configFile.path, - content: JSON.stringify({ compilerOptions: { incremental: true, module: "amd", outFile: "out.js" } }) + content: JSON.stringify({ compilerOptions: { incremental: true, module: "amd", outFile: "out.js" } }), }], subScenario: "module compilation/with --out", }); @@ -241,9 +245,9 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { target: "es5", module: "commonjs", declaration: true, - emitDeclarationOnly: true - } - }) + emitDeclarationOnly: true, + }, + }), }; const aTs: File = { path: `${project}/a.ts`, @@ -251,7 +255,7 @@ describe("unittests:: tsc-watch:: emit file --incremental", () => { export interface A { b: B; } -` +`, }; const bTs: File = { path: `${project}/b.ts`, @@ -259,7 +263,7 @@ export interface A { export interface B { b: C; } -` +`, }; const cTs: File = { path: `${project}/c.ts`, @@ -267,24 +271,28 @@ export interface B { export interface C { a: A; } -` +`, }; const indexTs: File = { path: `${project}/index.ts`, content: `export { A } from "./a"; export { B } from "./b"; export { C } from "./c"; -` +`, }; return [libFile, aTs, bTs, cTs, indexTs, config]; }, subScenario: "incremental with circular references", - modifyFs: host => host.writeFile(`${project}/a.ts`, `import { B } from "./b"; + modifyFs: host => + host.writeFile( + `${project}/a.ts`, + `import { B } from "./b"; export interface A { b: B; foo: any; } -`) +`, + ), }); verifyIncrementalWatchEmit({ @@ -293,9 +301,9 @@ export interface A { { path: libFile.path, content: libContent }, { path: `${project}/globals.d.ts`, content: `declare namespace Config { const value: string;} ` }, { path: `${project}/index.ts`, content: `console.log(Config.value);` }, - { path: configFile.path, content: JSON.stringify({ compilerOptions: { incremental: true, } }) } + { path: configFile.path, content: JSON.stringify({ compilerOptions: { incremental: true } }) }, ], - modifyFs: host => host.deleteFile(`${project}/globals.d.ts`) + modifyFs: host => host.deleteFile(`${project}/globals.d.ts`), }); describe("with option jsxImportSource", () => { @@ -322,10 +330,10 @@ export const Fragment: unique symbol; { path: `${project}/node_modules/preact/jsx-runtime/index.d.ts`, content: jsxLibraryContent.replace("propA", "propB") }, { path: `${project}/node_modules/preact/package.json`, content: JSON.stringify({ name: "preact", version: "0.0.1" }) }, { path: `${project}/index.tsx`, content: `export const App = () =>
;` }, - { path: configFile.path, content: JSON.stringify({ compilerOptions: jsxImportSourceOptions }) } + { path: configFile.path, content: JSON.stringify({ compilerOptions: jsxImportSourceOptions }) }, ], modifyFs: host => host.writeFile(configFile.path, JSON.stringify({ compilerOptions: { ...jsxImportSourceOptions, jsxImportSource: "preact" } })), - optionsToExtend: ["--explainFiles"] + optionsToExtend: ["--explainFiles"], }); verifyIncrementalWatchEmit({ @@ -333,7 +341,7 @@ export const Fragment: unique symbol; files: () => [ { path: libFile.path, content: libContent }, { path: `${project}/index.tsx`, content: `export const App = () =>
;` }, - { path: configFile.path, content: JSON.stringify({ compilerOptions: jsxImportSourceOptions }) } + { path: configFile.path, content: JSON.stringify({ compilerOptions: jsxImportSourceOptions }) }, ], modifyFs: host => { host.createDirectory(`${project}/node_modules`); @@ -341,7 +349,7 @@ export const Fragment: unique symbol; host.createDirectory(`${project}/node_modules/react/jsx-runtime`); host.writeFile(`${project}/node_modules/react/jsx-runtime/index.d.ts`, jsxLibraryContent); host.writeFile(`${project}/node_modules/react/package.json`, JSON.stringify({ name: "react", version: "0.0.1" })); - } + }, }); verifyIncrementalWatchEmit({ @@ -351,12 +359,12 @@ export const Fragment: unique symbol; { path: `${project}/node_modules/react/jsx-runtime/index.d.ts`, content: jsxLibraryContent }, { path: `${project}/node_modules/react/package.json`, content: JSON.stringify({ name: "react", version: "0.0.1" }) }, { path: `${project}/index.tsx`, content: `export const App = () =>
;` }, - { path: configFile.path, content: JSON.stringify({ compilerOptions: jsxImportSourceOptions }) } + { path: configFile.path, content: JSON.stringify({ compilerOptions: jsxImportSourceOptions }) }, ], modifyFs: host => { host.deleteFile(`${project}/node_modules/react/jsx-runtime/index.d.ts`); host.deleteFile(`${project}/node_modules/react/package.json`); - } + }, }); verifyIncrementalWatchEmit({ @@ -366,12 +374,12 @@ export const Fragment: unique symbol; { path: `${project}/node_modules/tslib/index.d.ts`, content: "export function __assign(...args: any[]): any;" }, { path: `${project}/node_modules/tslib/package.json`, content: JSON.stringify({ name: "tslib", version: "0.0.1" }) }, { path: `${project}/index.tsx`, content: `export const x = {...{}};` }, - { path: configFile.path, content: JSON.stringify({ compilerOptions: { importHelpers: true } }) } + { path: configFile.path, content: JSON.stringify({ compilerOptions: { importHelpers: true } }) }, ], modifyFs: host => { host.deleteFile(`${project}/node_modules/tslib/index.d.ts`); host.deleteFile(`${project}/node_modules/tslib/package.json`); - } + }, }); }); @@ -395,12 +403,13 @@ export const Fragment: unique symbol; verifyTscWatch({ scenario: "incremental", subScenario: "tsbuildinfo has error", - sys: () => createWatchedSystem({ - "/src/project/main.ts": "export const x = 10;", - "/src/project/tsconfig.json": "{}", - "/src/project/tsconfig.tsbuildinfo": "Some random string", - [libFile.path]: libFile.content, - }), + sys: () => + createWatchedSystem({ + "/src/project/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": "{}", + "/src/project/tsconfig.tsbuildinfo": "Some random string", + [libFile.path]: libFile.content, + }), commandLineArgs: ["--p", "src/project", "-i", "-w"], }); }); diff --git a/src/testRunner/unittests/tscWatch/libraryResolution.ts b/src/testRunner/unittests/tscWatch/libraryResolution.ts index 9605491eca0f6..fe6e1447b8fa7 100644 --- a/src/testRunner/unittests/tscWatch/libraryResolution.ts +++ b/src/testRunner/unittests/tscWatch/libraryResolution.ts @@ -1,8 +1,11 @@ -import { getCommandLineArgsForLibResolution, getSysForLibResolution } from "../helpers/libraryResolution"; +import { + getCommandLineArgsForLibResolution, + getSysForLibResolution, +} from "../helpers/libraryResolution"; import { TscWatchCompileChange, TscWatchSystem, - verifyTscWatch + verifyTscWatch, } from "../helpers/tscWatch"; describe("unittests:: tsc-watch:: libraryResolution", () => { @@ -14,31 +17,38 @@ describe("unittests:: tsc-watch:: libraryResolution", () => { return withoutConfig ? [] : [ { caption: "change program options to update module resolution", - edit: sys => sys.writeFile("/home/src/projects/project1/tsconfig.json", JSON.stringify({ - compilerOptions: { - composite: true, - typeRoots: ["./typeroot1", "./typeroot2"], - lib: ["es5", "dom"], - traceResolution: true, - }, - })), + edit: sys => + sys.writeFile( + "/home/src/projects/project1/tsconfig.json", + JSON.stringify({ + compilerOptions: { + composite: true, + typeRoots: ["./typeroot1", "./typeroot2"], + lib: ["es5", "dom"], + traceResolution: true, + }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "change program options to update module resolution and also update lib file", edit: sys => { - sys.writeFile("/home/src/projects/project1/tsconfig.json", JSON.stringify({ - compilerOptions: { - composite: true, - typeRoots: ["./typeroot1"], - lib: ["es5", "dom"], - traceResolution: true, - }, - })); + sys.writeFile( + "/home/src/projects/project1/tsconfig.json", + JSON.stringify({ + compilerOptions: { + composite: true, + typeRoots: ["./typeroot1"], + lib: ["es5", "dom"], + traceResolution: true, + }, + }), + ); changeLib(sys); }, timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ]; } function verify(withoutConfig?: true) { @@ -54,7 +64,7 @@ describe("unittests:: tsc-watch:: libraryResolution", () => { timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); - } + }, }, { caption: "edit index", @@ -78,14 +88,14 @@ describe("unittests:: tsc-watch:: libraryResolution", () => { timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); - } + }, }, { caption: "delete redirect file webworker", edit: sys => sys.deleteFile("/home/src/projects/node_modules/@typescript/lib-webworker/index.d.ts"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -115,7 +125,7 @@ describe("unittests:: tsc-watch:: libraryResolution", () => { timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); - } + }, }, ...editOptions(withoutConfig, sys => sys.deleteFile("/home/src/projects/node_modules/@typescript/lib-dom/index.d.ts")), { @@ -129,9 +139,9 @@ describe("unittests:: tsc-watch:: libraryResolution", () => { timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); - } + }, }, - ] + ], }); } verify(); diff --git a/src/testRunner/unittests/tscWatch/moduleResolution.ts b/src/testRunner/unittests/tscWatch/moduleResolution.ts index 2512116a46ab1..10a7a86a1614b 100644 --- a/src/testRunner/unittests/tscWatch/moduleResolution.ts +++ b/src/testRunner/unittests/tscWatch/moduleResolution.ts @@ -1,6 +1,13 @@ import * as Utils from "../../_namespaces/Utils"; -import { getFsConentsForNode10ResultAtTypesPackageJson, getFsContentsForNode10Result, getFsContentsForNode10ResultDts, getFsContentsForNode10ResultPackageJson } from "../helpers/node10Result"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + getFsConentsForNode10ResultAtTypesPackageJson, + getFsContentsForNode10Result, + getFsContentsForNode10ResultDts, + getFsContentsForNode10ResultPackageJson, +} from "../helpers/node10Result"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { createWatchedSystem, File, @@ -11,55 +18,56 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { verifyTscWatch({ scenario: "moduleResolution", subScenario: `watches for changes to package-json main fields`, - sys: () => createWatchedSystem([ - { - path: `/user/username/projects/myproject/packages/pkg1/package.json`, - content: JSON.stringify({ - name: "pkg1", - version: "1.0.0", - main: "build/index.js", - }) - }, - { - path: `/user/username/projects/myproject/packages/pkg1/index.ts`, - content: Utils.dedent` + sys: () => + createWatchedSystem([ + { + path: `/user/username/projects/myproject/packages/pkg1/package.json`, + content: JSON.stringify({ + name: "pkg1", + version: "1.0.0", + main: "build/index.js", + }), + }, + { + path: `/user/username/projects/myproject/packages/pkg1/index.ts`, + content: Utils.dedent` import type { TheNum } from 'pkg2' - export const theNum: TheNum = 42;` - }, - { - path: `/user/username/projects/myproject/packages/pkg1/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { - outDir: "build", - }, - }) - }, - { - path: `/user/username/projects/myproject/packages/pkg2/build/const.d.ts`, - content: `export type TheNum = 42;` - }, - { - path: `/user/username/projects/myproject/packages/pkg2/build/index.d.ts`, - content: `export type { TheNum } from './const.js';` - }, - { - path: `/user/username/projects/myproject/packages/pkg2/build/other.d.ts`, - content: `export type TheStr = string;` - }, - { - path: `/user/username/projects/myproject/packages/pkg2/package.json`, - content: JSON.stringify({ - name: "pkg2", - version: "1.0.0", - main: "build/index.js", - }) - }, - { - path: `/user/username/projects/myproject/node_modules/pkg2`, - symLink: `/user/username/projects/myproject/packages/pkg2`, - }, - libFile - ], { currentDirectory: "/user/username/projects/myproject" }), + export const theNum: TheNum = 42;`, + }, + { + path: `/user/username/projects/myproject/packages/pkg1/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + outDir: "build", + }, + }), + }, + { + path: `/user/username/projects/myproject/packages/pkg2/build/const.d.ts`, + content: `export type TheNum = 42;`, + }, + { + path: `/user/username/projects/myproject/packages/pkg2/build/index.d.ts`, + content: `export type { TheNum } from './const.js';`, + }, + { + path: `/user/username/projects/myproject/packages/pkg2/build/other.d.ts`, + content: `export type TheStr = string;`, + }, + { + path: `/user/username/projects/myproject/packages/pkg2/package.json`, + content: JSON.stringify({ + name: "pkg2", + version: "1.0.0", + main: "build/index.js", + }), + }, + { + path: `/user/username/projects/myproject/node_modules/pkg2`, + symLink: `/user/username/projects/myproject/packages/pkg2`, + }, + libFile, + ], { currentDirectory: "/user/username/projects/myproject" }), commandLineArgs: ["--project", "./packages/pkg1/tsconfig.json", "-w", "--traceResolution"], edits: [ { @@ -78,59 +86,60 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { sys.runQueuedTimeoutCallbacks(); // actual update }, }, - ] + ], }); verifyTscWatch({ scenario: "moduleResolution", subScenario: "diagnostics from cache", - sys: () => createWatchedSystem([ - { - path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { - moduleResolution: "nodenext", - outDir: "./dist", - declaration: true, - declarationDir: "./types" - }, - }) - }, - { - path: `/user/username/projects/myproject/package.json`, - content: JSON.stringify({ - name: "@this/package", - type: "module", - exports: { - ".": { - default: "./dist/index.js", - types: "./types/index.d.ts" - } - } - }) - }, - { - path: `/user/username/projects/myproject/index.ts`, - content: Utils.dedent` + sys: () => + createWatchedSystem([ + { + path: `/user/username/projects/myproject/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + moduleResolution: "nodenext", + outDir: "./dist", + declaration: true, + declarationDir: "./types", + }, + }), + }, + { + path: `/user/username/projects/myproject/package.json`, + content: JSON.stringify({ + name: "@this/package", + type: "module", + exports: { + ".": { + default: "./dist/index.js", + types: "./types/index.d.ts", + }, + }, + }), + }, + { + path: `/user/username/projects/myproject/index.ts`, + content: Utils.dedent` import * as me from "@this/package"; me.thing() export function thing(): void {} - ` - }, - { - path: `/user/username/projects/myproject/index2.ts`, - content: Utils.dedent` + `, + }, + { + path: `/user/username/projects/myproject/index2.ts`, + content: Utils.dedent` export function thing(): void {} - ` - }, - libFile - ], { currentDirectory: "/user/username/projects/myproject" }), + `, + }, + libFile, + ], { currentDirectory: "/user/username/projects/myproject" }), commandLineArgs: ["-w", "--traceResolution"], edits: [{ caption: "Add import to index2", edit: sys => sys.prependFile(`/user/username/projects/myproject/index2.ts`, `import * as me from "./index.js";`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - }] + }], }); describe("package json file is edited", () => { @@ -141,31 +150,31 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { compilerOptions: { target: "es2016", module: "Node16", - outDir: "../out" - } - }) + outDir: "../out", + }, + }), }; const packageFile: File = { path: `/user/username/projects/myproject/package.json`, - content: packageFileContents + content: packageFileContents, }; const fileA: File = { path: `/user/username/projects/myproject/src/fileA.ts`, content: Utils.dedent` import { foo } from "./fileB.mjs"; foo(); - ` + `, }; const fileB: File = { path: `/user/username/projects/myproject/project/src/fileB.mts`, content: Utils.dedent` export function foo() { } - ` + `, }; return createWatchedSystem( [configFile, fileA, fileB, packageFile, { ...libFile, path: "/a/lib/lib.es2016.full.d.ts" }], - { currentDirectory: "/user/username/projects/myproject" } + { currentDirectory: "/user/username/projects/myproject" }, ); } verifyTscWatch({ @@ -176,9 +185,15 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { edits: [ { caption: "Modify package json file to add type module", - edit: sys => sys.writeFile(`/user/username/projects/myproject/package.json`, JSON.stringify({ - name: "app", version: "1.0.0", type: "module", - })), + edit: sys => + sys.writeFile( + `/user/username/projects/myproject/package.json`, + JSON.stringify({ + name: "app", + version: "1.0.0", + type: "module", + }), + ), timeouts: host => { host.runQueuedTimeoutCallbacks(); // Failed lookup updates host.runQueuedTimeoutCallbacks(); // Actual update @@ -202,9 +217,15 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { }, { caption: "Modify package json file to add type module", - edit: sys => sys.writeFile(`/user/username/projects/myproject/package.json`, JSON.stringify({ - name: "app", version: "1.0.0", type: "module", - })), + edit: sys => + sys.writeFile( + `/user/username/projects/myproject/package.json`, + JSON.stringify({ + name: "app", + version: "1.0.0", + type: "module", + }), + ), timeouts: host => { host.runQueuedTimeoutCallbacks(); // Failed lookup updates host.runQueuedTimeoutCallbacks(); // Actual update @@ -225,9 +246,12 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { scenario: "moduleResolution", subScenario: "package json file is edited when package json with type module exists", commandLineArgs: ["--w", "--p", "src", "--extendedDiagnostics", "-traceResolution", "--explainFiles"], - sys: () => getSys(JSON.stringify({ - name: "app", version: "1.0.0", type: "module", - })), + sys: () => + getSys(JSON.stringify({ + name: "app", + version: "1.0.0", + type: "module", + })), edits: [ { caption: "Modify package.json file to remove type module", @@ -239,9 +263,15 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { }, { caption: "Modify package json file to add type module", - edit: sys => sys.writeFile(`/user/username/projects/myproject/package.json`, JSON.stringify({ - name: "app", version: "1.0.0", type: "module", - })), + edit: sys => + sys.writeFile( + `/user/username/projects/myproject/package.json`, + JSON.stringify({ + name: "app", + version: "1.0.0", + type: "module", + }), + ), timeouts: host => { host.runQueuedTimeoutCallbacks(); // Failed lookup updates host.runQueuedTimeoutCallbacks(); // Actual update @@ -278,160 +308,162 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { verifyTscWatch({ scenario: "moduleResolution", subScenario: "module resolutions from file are partially used", - sys: () => createWatchedSystem([ - { - path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { moduleResolution: "node16" }, - }) - }, - { - path: `/user/username/projects/myproject/index.ts`, - content: Utils.dedent` + sys: () => + createWatchedSystem([ + { + path: `/user/username/projects/myproject/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { moduleResolution: "node16" }, + }), + }, + { + path: `/user/username/projects/myproject/index.ts`, + content: Utils.dedent` import type { ImportInterface } from "pkg" assert { "resolution-mode": "import" }; import type { RequireInterface } from "pkg1" assert { "resolution-mode": "require" }; import {x} from "./a"; - ` - }, - { - path: `/user/username/projects/myproject/a.ts`, - content: Utils.dedent` + `, + }, + { + path: `/user/username/projects/myproject/a.ts`, + content: Utils.dedent` export const x = 10; - ` - }, - { - path: `/user/username/projects/myproject/node_modules/pkg/package.json`, - content: JSON.stringify({ - name: "pkg", - version: "0.0.1", - exports: { - import: "./import.js", - require: "./require.js" - } - }) - }, - { - path: `/user/username/projects/myproject/node_modules/pkg/import.d.ts`, - content: `export interface ImportInterface {}` - }, - { - path: `/user/username/projects/myproject/node_modules/pkg/require.d.ts`, - content: `export interface RequireInterface {}` - }, - { - path: `/user/username/projects/myproject/node_modules/pkg1/package.json`, - content: JSON.stringify({ - name: "pkg1", - version: "0.0.1", - exports: { - import: "./import.js", - require: "./require.js" - } - }) - }, - { - path: `/user/username/projects/myproject/node_modules/pkg1/import.d.ts`, - content: `export interface ImportInterface {}` - }, - libFile - ], { currentDirectory: "/user/username/projects/myproject" }), + `, + }, + { + path: `/user/username/projects/myproject/node_modules/pkg/package.json`, + content: JSON.stringify({ + name: "pkg", + version: "0.0.1", + exports: { + import: "./import.js", + require: "./require.js", + }, + }), + }, + { + path: `/user/username/projects/myproject/node_modules/pkg/import.d.ts`, + content: `export interface ImportInterface {}`, + }, + { + path: `/user/username/projects/myproject/node_modules/pkg/require.d.ts`, + content: `export interface RequireInterface {}`, + }, + { + path: `/user/username/projects/myproject/node_modules/pkg1/package.json`, + content: JSON.stringify({ + name: "pkg1", + version: "0.0.1", + exports: { + import: "./import.js", + require: "./require.js", + }, + }), + }, + { + path: `/user/username/projects/myproject/node_modules/pkg1/import.d.ts`, + content: `export interface ImportInterface {}`, + }, + libFile, + ], { currentDirectory: "/user/username/projects/myproject" }), commandLineArgs: ["-w", "--traceResolution"], edits: [ { caption: "modify aFile by adding import", edit: sys => sys.appendFile(`/user/username/projects/myproject/a.ts`, `import type { ImportInterface } from "pkg" assert { "resolution-mode": "import" }`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ scenario: "moduleResolution", subScenario: "type reference resolutions reuse", - sys: () => createWatchedSystem([ - { - path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ - compilerOptions: { moduleResolution: "node16" }, - }) - }, - { - path: `/user/username/projects/myproject/index.ts`, - content: Utils.dedent` + sys: () => + createWatchedSystem([ + { + path: `/user/username/projects/myproject/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { moduleResolution: "node16" }, + }), + }, + { + path: `/user/username/projects/myproject/index.ts`, + content: Utils.dedent` /// /// export interface LocalInterface extends RequireInterface {} - ` - }, - { - path: `/user/username/projects/myproject/a.ts`, - content: Utils.dedent` + `, + }, + { + path: `/user/username/projects/myproject/a.ts`, + content: Utils.dedent` export const x = 10; - ` - }, - { - path: `/user/username/projects/myproject/node_modules/pkg/package.json`, - content: JSON.stringify({ - name: "pkg", - version: "0.0.1", - exports: { - import: "./import.js", - require: "./require.js" - } - }) - }, - { - path: `/user/username/projects/myproject/node_modules/pkg/import.d.ts`, - content: Utils.dedent` + `, + }, + { + path: `/user/username/projects/myproject/node_modules/pkg/package.json`, + content: JSON.stringify({ + name: "pkg", + version: "0.0.1", + exports: { + import: "./import.js", + require: "./require.js", + }, + }), + }, + { + path: `/user/username/projects/myproject/node_modules/pkg/import.d.ts`, + content: Utils.dedent` export {}; declare global { interface ImportInterface {} } - ` - }, - { - path: `/user/username/projects/myproject/node_modules/pkg/require.d.ts`, - content: Utils.dedent` + `, + }, + { + path: `/user/username/projects/myproject/node_modules/pkg/require.d.ts`, + content: Utils.dedent` export {}; declare global { interface RequireInterface {} } - ` - }, - { - path: `/user/username/projects/myproject/node_modules/pkg1/package.json`, - content: JSON.stringify({ - name: "pkg1", - version: "0.0.1", - exports: { - import: "./import.js", - require: "./require.js" - } - }) - }, - { - path: `/user/username/projects/myproject/node_modules/pkg1/import.d.ts`, - content: Utils.dedent` + `, + }, + { + path: `/user/username/projects/myproject/node_modules/pkg1/package.json`, + content: JSON.stringify({ + name: "pkg1", + version: "0.0.1", + exports: { + import: "./import.js", + require: "./require.js", + }, + }), + }, + { + path: `/user/username/projects/myproject/node_modules/pkg1/import.d.ts`, + content: Utils.dedent` export {}; declare global { interface ImportInterface {} } - ` - }, - { - path: `/user/username/projects/myproject/node_modules/@types/pkg2/index.d.ts`, - content: `export const x = 10;` - }, - libFile - ], { currentDirectory: "/user/username/projects/myproject" }), + `, + }, + { + path: `/user/username/projects/myproject/node_modules/@types/pkg2/index.d.ts`, + content: `export const x = 10;`, + }, + libFile, + ], { currentDirectory: "/user/username/projects/myproject" }), commandLineArgs: ["-w", "--traceResolution"], edits: [ { caption: "modify aFile by adding import", edit: sys => sys.prependFile(`/user/username/projects/myproject/a.ts`, `/// \n`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -536,6 +568,6 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { sys.runQueuedTimeoutCallbacks(); }, }, - ] + ], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tscWatch/nodeNextWatch.ts b/src/testRunner/unittests/tscWatch/nodeNextWatch.ts index 38f5b340a8643..9f66c823ab3e2 100644 --- a/src/testRunner/unittests/tscWatch/nodeNextWatch.ts +++ b/src/testRunner/unittests/tscWatch/nodeNextWatch.ts @@ -1,5 +1,7 @@ import * as Utils from "../../_namespaces/Utils"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { createWatchedSystem, File, @@ -20,9 +22,9 @@ describe("unittests:: tsc-watch:: nodeNextWatch:: emit when module emit is speci target: "es2020", module: "nodenext", moduleResolution: "nodenext", - outDir: "../dist" - } - }) + outDir: "../dist", + }, + }), }; const packageFile: File = { path: "/project/package.json", @@ -32,33 +34,34 @@ describe("unittests:: tsc-watch:: nodeNextWatch:: emit when module emit is speci description: "", type: "module", main: "index.js", - }) + }), }; const file1: File = { path: "/project/src/index.ts", content: Utils.dedent` import * as Thing from "thing"; - Thing.fn();` + Thing.fn();`, }; const declFile: File = { path: "/project/src/deps.d.ts", - content: `declare module "thing";` + content: `declare module "thing";`, }; return createWatchedSystem([configFile, file1, declFile, packageFile, { ...libFile, path: "/a/lib/lib.es2020.full.d.ts" }]); }, edits: [ { caption: "Modify typescript file", - edit: sys => sys.modifyFile( - "/project/src/index.ts", - Utils.dedent` + edit: sys => + sys.modifyFile( + "/project/src/index.ts", + Utils.dedent` import * as Thing from "thing"; Thing.fn();`, - {}, - ), + {}, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } + }, ], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tscWatch/programUpdates.ts b/src/testRunner/unittests/tscWatch/programUpdates.ts index 196056480048f..5338f3b30dd4f 100644 --- a/src/testRunner/unittests/tscWatch/programUpdates.ts +++ b/src/testRunner/unittests/tscWatch/programUpdates.ts @@ -1,7 +1,11 @@ import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; -import { commandLineCallbacks } from "../helpers/baseline"; -import { compilerOptionsToConfigJson } from "../helpers/contents"; +import { + commandLineCallbacks, +} from "../helpers/baseline"; +import { + compilerOptionsToConfigJson, +} from "../helpers/contents"; import { commonFile1, commonFile2, @@ -26,7 +30,7 @@ describe("unittests:: tsc-watch:: program updates", () => { const configFilePath = "/a/b/tsconfig.json"; const configFile: File = { path: configFilePath, - content: `{}` + content: `{}`, }; verifyTscWatch({ scenario, @@ -38,12 +42,12 @@ describe("unittests:: tsc-watch:: program updates", () => { content: ` import {f} from "./module" console.log(f) - ` + `, }; const moduleFile: File = { path: "/a/b/c/module.d.ts", - content: `export let x: number` + content: `export let x: number`, }; return createWatchedSystem([appFile, moduleFile, libFile]); }, @@ -56,13 +60,13 @@ describe("unittests:: tsc-watch:: program updates", () => { sys: () => { const f1 = { path: "/a/b/app.ts", - content: "let x = 1" + content: "let x = 1", }; const config = { path: configFilePath, content: JSON.stringify({ - include: ["app.ts"] - }) + include: ["app.ts"], + }), }; return createWatchedSystem([f1, libFile, config], { useCaseSensitiveFileNames: false }); }, @@ -81,19 +85,19 @@ describe("unittests:: tsc-watch:: program updates", () => { "exclude": [ "e" ] - }` + }`, }; const file1: File = { path: "/a/b/c/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2: File = { path: "/a/b/d/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const file3: File = { path: "/a/b/e/f3.ts", - content: "let z = 1" + content: "let z = 1", }; return createWatchedSystem([configFile, libFile, file1, file2, file3]); }, @@ -109,8 +113,8 @@ describe("unittests:: tsc-watch:: program updates", () => { caption: "Create commonFile2", edit: sys => sys.writeFile(commonFile2.path, commonFile2.content), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -126,7 +130,7 @@ describe("unittests:: tsc-watch:: program updates", () => { "commonFile1.ts", "commonFile3.ts" ] - }` + }`, }; return createWatchedSystem([commonFile1, commonFile2, libFile, configFile]); }, @@ -154,8 +158,8 @@ describe("unittests:: tsc-watch:: program updates", () => { caption: "recreate file2", edit: sys => sys.writeFile(commonFile2.path, commonFile2.content), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -166,7 +170,7 @@ describe("unittests:: tsc-watch:: program updates", () => { const file1: File = { path: commonFile1.path, content: `/// - let x = y` + let x = y`, }; return createWatchedSystem([file1, libFile]); }, @@ -175,8 +179,8 @@ describe("unittests:: tsc-watch:: program updates", () => { caption: "create file2", edit: sys => sys.writeFile(commonFile2.path, commonFile2.content), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -189,7 +193,7 @@ describe("unittests:: tsc-watch:: program updates", () => { content: `{ "compilerOptions": {}, "files": ["${commonFile1.path}", "${commonFile2.path}"] - }` + }`, }; return createWatchedSystem([libFile, commonFile1, commonFile2, configFile]); }, @@ -201,13 +205,17 @@ describe("unittests:: tsc-watch:: program updates", () => { }, { caption: "Change config", - edit: sys => sys.writeFile(configFilePath, `{ + edit: sys => + sys.writeFile( + configFilePath, + `{ "compilerOptions": {}, "files": ["${commonFile1.path}"] - }`), + }`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -220,20 +228,24 @@ describe("unittests:: tsc-watch:: program updates", () => { content: `{ "compilerOptions": {}, "files": ["${commonFile1.path}", "${commonFile2.path}"] - }` + }`, }; return createWatchedSystem([libFile, commonFile1, commonFile2, configFile]); }, edits: [ { caption: "Modify config without changing content", - edit: sys => sys.modifyFile(configFilePath, `{ + edit: sys => + sys.modifyFile( + configFilePath, + `{ "compilerOptions": {}, "files": ["${commonFile1.path}", "${commonFile2.path}"] - }`), + }`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -243,32 +255,40 @@ describe("unittests:: tsc-watch:: program updates", () => { sys: () => { const aTs: File = { path: "/a.ts", - content: "label: while (1) {}" + content: "label: while (1) {}", }; const tsconfig: File = { path: "/tsconfig.json", content: JSON.stringify({ - compilerOptions: { allowUnusedLabels: true } - }) + compilerOptions: { allowUnusedLabels: true }, + }), }; return createWatchedSystem([libFile, aTs, tsconfig]); }, edits: [ { caption: "Disable allowUnsusedLabels", - edit: sys => sys.modifyFile("/tsconfig.json", JSON.stringify({ - compilerOptions: { allowUnusedLabels: false } - })), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + edit: sys => + sys.modifyFile( + "/tsconfig.json", + JSON.stringify({ + compilerOptions: { allowUnusedLabels: false }, + }), + ), + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Enable allowUnsusedLabels", - edit: sys => sys.modifyFile("/tsconfig.json", JSON.stringify({ - compilerOptions: { allowUnusedLabels: true } - })), + edit: sys => + sys.modifyFile( + "/tsconfig.json", + JSON.stringify({ + compilerOptions: { allowUnusedLabels: true }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -278,39 +298,47 @@ describe("unittests:: tsc-watch:: program updates", () => { sys: () => { const aTs: File = { path: "/a.ts", - content: "import {} from './b.css'" + content: "import {} from './b.css'", }; const bCssTs: File = { path: "/b.d.css.ts", - content: "declare const style: string;" + content: "declare const style: string;", }; const tsconfig: File = { path: "/tsconfig.json", content: JSON.stringify({ compilerOptions: { allowArbitraryExtensions: true }, files: ["/a.ts"], - }) + }), }; return createWatchedSystem([libFile, aTs, bCssTs, tsconfig]); }, edits: [ { caption: "Disable allowArbitraryExtensions", - edit: sys => sys.modifyFile("/tsconfig.json", JSON.stringify({ - compilerOptions: { allowArbitraryExtensions: false }, - files: ["/a.ts"], - })), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + edit: sys => + sys.modifyFile( + "/tsconfig.json", + JSON.stringify({ + compilerOptions: { allowArbitraryExtensions: false }, + files: ["/a.ts"], + }), + ), + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Enable allowArbitraryExtensions", - edit: sys => sys.modifyFile("/tsconfig.json", JSON.stringify({ - compilerOptions: { allowArbitraryExtensions: true }, - files: ["/a.ts"], - })), + edit: sys => + sys.modifyFile( + "/tsconfig.json", + JSON.stringify({ + compilerOptions: { allowArbitraryExtensions: true }, + files: ["/a.ts"], + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -333,28 +361,35 @@ export class A { const tsconfig: File = { path: "/tsconfig.json", content: JSON.stringify({ - compilerOptions: { target: "es6", importsNotUsedAsValues: "error" } - }) + compilerOptions: { target: "es6", importsNotUsedAsValues: "error" }, + }), }; return createWatchedSystem([libFile, aTs, bTs, tsconfig]); }, edits: [ { caption: "Enable experimentalDecorators", - edit: sys => sys.modifyFile("/tsconfig.json", JSON.stringify({ - compilerOptions: { target: "es6", importsNotUsedAsValues: "error", experimentalDecorators: true } - })), + edit: sys => + sys.modifyFile( + "/tsconfig.json", + JSON.stringify({ + compilerOptions: { target: "es6", importsNotUsedAsValues: "error", experimentalDecorators: true }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - }, { caption: "Enable emitDecoratorMetadata", - edit: sys => sys.modifyFile("/tsconfig.json", JSON.stringify({ - compilerOptions: { target: "es6", importsNotUsedAsValues: "error", experimentalDecorators: true, emitDecoratorMetadata: true } - })), + edit: sys => + sys.modifyFile( + "/tsconfig.json", + JSON.stringify({ + compilerOptions: { target: "es6", importsNotUsedAsValues: "error", experimentalDecorators: true, emitDecoratorMetadata: true }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -367,11 +402,11 @@ export class A { content: `{ "compilerOptions": {}, "exclude": ["/a/c"] - }` + }`, }; const excludedFile1: File = { path: "/a/c/excluedFile1.ts", - content: `let t = 1;` + content: `let t = 1;`, }; return createWatchedSystem([libFile, commonFile1, commonFile2, excludedFile1, configFile]); }, @@ -384,15 +419,15 @@ export class A { sys: () => { const file1: File = { path: "/a/b/file1.ts", - content: `import { T } from "module1";` + content: `import { T } from "module1";`, }; const nodeModuleFile: File = { path: "/a/b/node_modules/module1.ts", - content: `export interface T {}` + content: `export interface T {}`, }; const classicModuleFile: File = { path: "/a/module1.ts", - content: `export interface T {}` + content: `export interface T {}`, }; const configFile: File = { path: configFilePath, @@ -401,22 +436,26 @@ export class A { "moduleResolution": "node" }, "files": ["${file1.path}"] - }` + }`, }; return createWatchedSystem([libFile, file1, nodeModuleFile, classicModuleFile, configFile]); }, edits: [ { caption: "Change module resolution to classic", - edit: sys => sys.writeFile(configFile.path, `{ + edit: sys => + sys.writeFile( + configFile.path, + `{ "compilerOptions": { "moduleResolution": "classic" }, "files": ["/a/b/file1.ts"] - }`), + }`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -432,7 +471,7 @@ export class A { "allowAnything": true }, "someOtherProperty": {} - }` + }`, }; return createWatchedSystem([commonFile1, commonFile2, libFile, configFile]); }, @@ -445,15 +484,15 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: `export * from "./f2"` + content: `export * from "./f2"`, }; const file2 = { path: "/a/b/f2.ts", - content: `export let x = 1` + content: `export let x = 1`, }; const file3 = { path: "/a/c/f3.ts", - content: `export let y = 1;` + content: `export let y = 1;`, }; return createWatchedSystem([file1, file2, file3, libFile]); }, @@ -463,8 +502,8 @@ export class A { // now inferred project should inclule file3 edit: sys => sys.modifyFile("/a/b/f2.ts", `export * from "../c/f3"`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -474,15 +513,15 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: `export * from "./f2"` + content: `export * from "./f2"`, }; const file2 = { path: "/a/b/f2.ts", - content: `export * from "../c/f3"` + content: `export * from "../c/f3"`, }; const file3 = { path: "/a/c/f3.ts", - content: `export let y = 1;` + content: `export let y = 1;`, }; return createWatchedSystem([file1, file2, file3, libFile]); }, @@ -491,8 +530,8 @@ export class A { caption: "Delete f2", edit: sys => sys.deleteFile("/a/b/f2.ts"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -502,15 +541,15 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: `export * from "./f2"` + content: `export * from "./f2"`, }; const file2 = { path: "/a/b/f2.ts", - content: `export * from "../c/f3"` + content: `export * from "../c/f3"`, }; const file3 = { path: "/a/c/f3.ts", - content: `export let y = 1;` + content: `export let y = 1;`, }; return createWatchedSystem([file1, file2, file3, libFile]); }, @@ -519,8 +558,8 @@ export class A { caption: "Delete f2", edit: sys => sys.deleteFile("/a/b/f2.ts"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -530,19 +569,19 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: "export let x = 5" + content: "export let x = 5", }; const file2 = { path: "/a/c/f2.ts", - content: `import {x} from "../b/f1"` + content: `import {x} from "../b/f1"`, }; const file3 = { path: "/a/c/f3.ts", - content: "export let y = 1" + content: "export let y = 1", }; const configFile = { path: "/a/c/tsconfig.json", - content: JSON.stringify({ compilerOptions: {}, files: ["f2.ts", "f3.ts"] }) + content: JSON.stringify({ compilerOptions: {}, files: ["f2.ts", "f3.ts"] }), }; return createWatchedSystem([file1, file2, file3, libFile, configFile]); }, @@ -555,7 +594,7 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: "export {}\ndeclare global {}" + content: "export {}\ndeclare global {}", }; return createWatchedSystem([file1, libFile, configFile]); }, @@ -564,8 +603,8 @@ export class A { timeouts: sys => sys.runQueuedTimeoutCallbacks(), edit: sys => { sys.writeFile(configFilePath, JSON.stringify({ compilerOptions: { module: "none" } })); - } - }] + }, + }], }); it("two watch programs are not affected by each other", () => { @@ -573,15 +612,15 @@ export class A { path: "/a/b/f1.ts", content: ` export * from "../c/f2"; - export * from "../d/f3";` + export * from "../d/f3";`, }; const file2 = { path: "/a/c/f2.ts", - content: "export let x = 1;" + content: "export let x = 1;", }; const file3 = { path: "/a/d/f3.ts", - content: "export let y = 1;" + content: "export let y = 1;", }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem([libFile, file1, file2, file3])); const host = createWatchCompilerHostOfFilesAndCompilerOptionsForBaseline({ @@ -589,7 +628,7 @@ export class A { system: sys, options: { allowNonTsExtensions: true }, cb, - watchOptions: undefined + watchOptions: undefined, }); ts.createWatchProgram(host); baseline.push(`${sys.getExecutingFilePath()} --w ${file2.path} ${file3.path}`); @@ -601,15 +640,15 @@ export class A { oldSnap, }); - const {cb: cb2, getPrograms: getPrograms2 } = commandLineCallbacks(sys); + const { cb: cb2, getPrograms: getPrograms2 } = commandLineCallbacks(sys); const oldSnap2 = sys.snap(); baseline.push("createing separate watcher"); ts.createWatchProgram(createWatchCompilerHostOfFilesAndCompilerOptionsForBaseline({ - rootFiles:[file1.path], + rootFiles: [file1.path], system: sys, options: { allowNonTsExtensions: true }, cb: cb2, - watchOptions: undefined + watchOptions: undefined, })); watchBaseline({ baseline, @@ -632,7 +671,7 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; return createWatchedSystem([file1, libFile, configFile]); }, @@ -641,8 +680,8 @@ export class A { caption: "Write f2", edit: sys => sys.writeFile("/a/b/f2.ts", "let y = 1"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -652,15 +691,15 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const configFile = { path: configFilePath, - content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts"] }) + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts"] }), }; return createWatchedSystem([file1, file2, libFile, configFile]); }, @@ -669,8 +708,8 @@ export class A { caption: "Modify config to make f2 as root too", edit: sys => sys.writeFile(configFilePath, JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] })), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -680,15 +719,15 @@ export class A { sys: () => { const file1 = { path: `/user/username/projects/myproject/f1.ts`, - content: "export const x = 1" + content: "export const x = 1", }; const file2 = { path: `/user/username/projects/myproject/f2.ts`, - content: "export const y = 1" + content: "export const y = 1", }; const configFile = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { composite: true }, include: ["./", "./**/*.json"] }) + content: JSON.stringify({ compilerOptions: { composite: true }, include: ["./", "./**/*.json"] }), }; return createWatchedSystem([file1, file2, libFile, configFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -702,8 +741,8 @@ export class A { caption: "Import new file", edit: sys => sys.prependFile(`/user/username/projects/myproject/f1.ts`, `import { z } from "./new-file";`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -713,11 +752,11 @@ export class A { sys: () => { const file1 = { path: `/user/username/projects/myproject/Project/file1.ts`, - content: "export const x = 10;" + content: "export const x = 10;", }; const configFile = { path: `/user/username/projects/myproject/Project/tsconfig.json`, - content: JSON.stringify({ include: [".", "./**/*.json"] }) + content: JSON.stringify({ include: [".", "./**/*.json"] }), }; return createWatchedSystem([file1, libFile, configFile], { currentDirectory: `/user/username/projects/myproject/Project` }); }, @@ -725,9 +764,9 @@ export class A { { caption: "Write file2", edit: sys => sys.writeFile(`/user/username/projects/myproject/Project/file2.ts`, "export const y = 10;"), - timeouts: sys => sys.runQueuedTimeoutCallbacks() - } - ] + timeouts: sys => sys.runQueuedTimeoutCallbacks(), + }, + ], }); verifyTscWatch({ @@ -737,15 +776,15 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const configFile = { path: configFilePath, - content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }), }; return createWatchedSystem([file1, file2, libFile, configFile]); }, @@ -754,8 +793,8 @@ export class A { caption: "Modify config to set outFile option", edit: sys => sys.writeFile(configFilePath, JSON.stringify({ compilerOptions: { outFile: "out.js" }, files: ["f1.ts", "f2.ts"] })), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -765,15 +804,15 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const configFile = { path: configFilePath, - content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }), }; return createWatchedSystem([file1, file2, libFile, configFile]); }, @@ -782,8 +821,8 @@ export class A { caption: "Delete f2", edit: sys => sys.deleteFile("/a/b/f2.ts"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -793,11 +832,11 @@ export class A { sys: () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1;" + content: "let x = 1;", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 2;" + content: "let y = 2;", }; return createWatchedSystem([file1, file2, libFile, configFile]); }, @@ -806,8 +845,8 @@ export class A { caption: "Delete config file", edit: sys => sys.deleteFile(configFilePath), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -817,11 +856,11 @@ export class A { sys: () => { const file1 = { path: "/a/b/app.ts", - content: "" + content: "", }; const corruptedConfig = { path: configFilePath, - content: "{" + content: "{", }; return createWatchedSystem([file1, libFile, corruptedConfig]); }, @@ -835,15 +874,15 @@ export class A { const libES5 = { path: "/compiler/lib.es5.d.ts", content: `${libFile.content} -declare const eval: any` +declare const eval: any`, }; const libES2015Promise = { path: "/compiler/lib.es2015.promise.d.ts", - content: `declare class Promise {}` + content: `declare class Promise {}`, }; const app = { path: "/src/app.ts", - content: "var x: Promise;" + content: "var x: Promise;", }; const config1 = { path: "/src/tsconfig.json", @@ -855,33 +894,38 @@ declare const eval: any` noImplicitAny: true, sourceMap: false, lib: [ - "es5" - ] - } - }) + "es5", + ], + }, + }, + ), }; return createWatchedSystem([libES5, libES2015Promise, app, config1], { executingFilePath: "/compiler/tsc.js" }); }, edits: [ { caption: "Change the lib in config", - edit: sys => sys.writeFile("/src/tsconfig.json", JSON.stringify( - { - compilerOptions: { - module: "commonjs", - target: "es5", - noImplicitAny: true, - sourceMap: false, - lib: [ - "es5", - "es2015.promise" - ] - } - }) - ), + edit: sys => + sys.writeFile( + "/src/tsconfig.json", + JSON.stringify( + { + compilerOptions: { + module: "commonjs", + target: "es5", + noImplicitAny: true, + sourceMap: false, + lib: [ + "es5", + "es2015.promise", + ], + }, + }, + ), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -891,7 +935,7 @@ declare const eval: any` sys: () => { const f = { path: "/a/src/app.ts", - content: "let x = 1;" + content: "let x = 1;", }; const config = { path: "/a/tsconfig.json", @@ -899,9 +943,9 @@ declare const eval: any` compilerOptions: {}, include: [ "src/**/*", - "notexistingfolder/*" - ] - }) + "notexistingfolder/*", + ], + }), }; return createWatchedSystem([f, config, libFile]); }, @@ -918,7 +962,7 @@ declare const eval: any` sys.renameFile("/users/username/projects/project/moduleFile.ts", "/users/username/projects/project/moduleFile1.ts"); sys.deleteFile("/users/username/projects/project/moduleFile.js"); }, - timeouts: runQueuedTimeoutCallbacksTwice + timeouts: runQueuedTimeoutCallbacksTwice, }; const changeModuleFile1ToModuleFile: TscWatchCompileChange = { caption: "Rename moduleFile1 back to moduleFile", @@ -933,18 +977,18 @@ declare const eval: any` sys: () => { const moduleFile = { path: "/users/username/projects/project/moduleFile.ts", - content: "export function bar() { };" + content: "export function bar() { };", }; const file1 = { path: "/users/username/projects/project/file1.ts", - content: 'import * as T from "./moduleFile"; T.bar();' + content: 'import * as T from "./moduleFile"; T.bar();', }; return createWatchedSystem([moduleFile, file1, libFile]); }, edits: [ changeModuleFileToModuleFile1, - changeModuleFile1ToModuleFile - ] + changeModuleFile1ToModuleFile, + ], }); verifyTscWatch({ @@ -954,22 +998,22 @@ declare const eval: any` sys: () => { const moduleFile = { path: "/users/username/projects/project/moduleFile.ts", - content: "export function bar() { };" + content: "export function bar() { };", }; const file1 = { path: "/users/username/projects/project/file1.ts", - content: 'import * as T from "./moduleFile"; T.bar();' + content: 'import * as T from "./moduleFile"; T.bar();', }; const configFile = { path: "/users/username/projects/project/tsconfig.json", - content: `{}` + content: `{}`, }; return createWatchedSystem([moduleFile, file1, configFile, libFile]); }, edits: [ changeModuleFileToModuleFile1, - changeModuleFile1ToModuleFile - ] + changeModuleFile1ToModuleFile, + ], }); describe("types from config file", () => { @@ -983,18 +1027,18 @@ declare const eval: any` sys: () => { const f1 = { path: "/a/b/app.ts", - content: "let x = 1" + content: "let x = 1", }; const config = { path: configFilePath, - content: JSON.stringify({ compilerOptions: { types: ["node"], typeRoots: includeTypeRoots ? [] : undefined } }) + content: JSON.stringify({ compilerOptions: { types: ["node"], typeRoots: includeTypeRoots ? [] : undefined } }), }; const node = { path: "/a/b/node_modules/@types/node/index.d.ts", - content: "declare var process: any" + content: "declare var process: any", }; const cwd = { - path: "/a/c" + path: "/a/c", }; return createWatchedSystem([f1, config, node, cwd, libFile], { currentDirectory: cwd.path }); }, @@ -1011,7 +1055,7 @@ declare const eval: any` sys: () => { const file1 = { path: "/users/username/projects/project/file1.ts", - content: 'import * as T from "./moduleFile"; T.bar();' + content: 'import * as T from "./moduleFile"; T.bar();', }; return createWatchedSystem([file1, libFile]); }, @@ -1020,8 +1064,8 @@ declare const eval: any` caption: "Create module file", edit: sys => sys.writeFile("/users/username/projects/project/moduleFile.ts", "export function bar() { }"), timeouts: runQueuedTimeoutCallbacksTwice, - } - ] + }, + ], }); verifyTscWatch({ @@ -1031,7 +1075,7 @@ declare const eval: any` sys: () => { const file = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const configFile = { path: configFilePath, @@ -1040,7 +1084,7 @@ declare const eval: any` "foo": "bar", "allowJS": true } - }` + }`, }; return createWatchedSystem([file, configFile, libFile]); }, @@ -1053,13 +1097,13 @@ declare const eval: any` sys: () => { const file = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const configFile = { path: configFilePath, content: `{ "compilerOptions": {} - }` + }`, }; return createWatchedSystem([file, configFile, libFile]); }, @@ -1072,29 +1116,37 @@ declare const eval: any` sys: () => { const file = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; return createWatchedSystem([file, configFile, libFile]); }, edits: [ { caption: "change config file to add error", - edit: sys => sys.writeFile(configFilePath, `{ + edit: sys => + sys.writeFile( + configFilePath, + `{ "compilerOptions": { "haha": 123 } - }`), + }`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "change config file to remove error", - edit: sys => sys.writeFile(configFilePath, `{ + edit: sys => + sys.writeFile( + configFilePath, + `{ "compilerOptions": { } - }`), + }`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -1107,11 +1159,11 @@ declare const eval: any` content: `{ "compilerOptions": {}, "include": ["app/*", "test/**/*", "something"] - }` + }`, }; const file1 = { path: "/a/b/file1.ts", - content: "let t = 10;" + content: "let t = 10;", }; return createWatchedSystem([file1, configFile, libFile]); }, @@ -1124,22 +1176,22 @@ declare const eval: any` sys: () => { const f = { path: "/a/app.ts", - content: "let x = 1" + content: "let x = 1", }; const config = { path: "/a/tsconfig.json", content: JSON.stringify({ compiler: {}, - files: [] - }) + files: [], + }), }; const t1 = { path: "/a/node_modules/@types/typings/index.d.ts", - content: `export * from "./lib"` + content: `export * from "./lib"`, }; const t2 = { path: "/a/node_modules/@types/typings/lib.d.ts", - content: `export const x: number` + content: `export const x: number`, }; return createWatchedSystem([f, config, t1, t2, libFile], { currentDirectory: ts.getDirectoryPath(f.path) }); }, @@ -1148,7 +1200,7 @@ declare const eval: any` it("should support files without extensions", () => { const f = { path: "/a/compile", - content: "let x = 1" + content: "let x = 1", }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem([f, libFile])); const watch = ts.createWatchProgram(createWatchCompilerHostOfFilesAndCompilerOptionsForBaseline({ @@ -1156,7 +1208,7 @@ declare const eval: any` system: sys, options: { allowNonTsExtensions: true }, cb, - watchOptions: undefined + watchOptions: undefined, })); runWatchBaseline({ scenario, @@ -1166,7 +1218,7 @@ declare const eval: any` baseline, oldSnap, getPrograms, - watchOrSolution: watch + watchOrSolution: watch, }); }); @@ -1177,7 +1229,7 @@ declare const eval: any` sys: () => { const file = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const configFile = { path: configFilePath, @@ -1189,23 +1241,27 @@ declare const eval: any` "inlineSourceMap": true, "mapRoot": "./" } -}` +}`, }; return createWatchedSystem([file, libFile, configFile]); }, edits: [ { caption: "Remove the comment from config file", - edit: sys => sys.writeFile(configFilePath, ` + edit: sys => + sys.writeFile( + configFilePath, + ` { "compilerOptions": { "inlineSourceMap": true, "mapRoot": "./" } -}`), +}`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); describe("should not trigger recompilation because of program emit", () => { @@ -1217,17 +1273,17 @@ declare const eval: any` sys: () => { const file1: File = { path: `/user/username/projects/myproject/file1.ts`, - content: "export const c = 30;" + content: "export const c = 30;", }; const file2: File = { path: `/user/username/projects/myproject/src/file2.ts`, - content: `import {c} from "file1"; export const d = 30;` + content: `import {c} from "file1"; export const d = 30;`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ - compilerOptions: compilerOptionsToConfigJson(options) - }) + compilerOptions: compilerOptionsToConfigJson(options), + }), }; return createWatchedSystem([file1, file2, libFile, tsconfig], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1239,38 +1295,38 @@ declare const eval: any` timeouts: sys => sys.runQueuedTimeoutCallbacks(), // To update program and failed lookups }, noopChange, - ] + ], }); } verifyWithOptions( "without outDir or outFile is specified", - { module: ts.ModuleKind.AMD } + { module: ts.ModuleKind.AMD }, ); verifyWithOptions( "with outFile", - { module: ts.ModuleKind.AMD, outFile: "build/outFile.js" } + { module: ts.ModuleKind.AMD, outFile: "build/outFile.js" }, ); verifyWithOptions( "when outDir is specified", - { module: ts.ModuleKind.AMD, outDir: "build" } + { module: ts.ModuleKind.AMD, outDir: "build" }, ); verifyWithOptions( "without outDir or outFile is specified with declaration enabled", - { module: ts.ModuleKind.AMD, declaration: true } + { module: ts.ModuleKind.AMD, declaration: true }, ); verifyWithOptions( "when outDir and declarationDir is specified", - { module: ts.ModuleKind.AMD, outDir: "build", declaration: true, declarationDir: "decls" } + { module: ts.ModuleKind.AMD, outDir: "build", declaration: true, declarationDir: "decls" }, ); verifyWithOptions( "declarationDir is specified", - { module: ts.ModuleKind.AMD, declaration: true, declarationDir: "decls" } + { module: ts.ModuleKind.AMD, declaration: true, declarationDir: "decls" }, ); }); @@ -1286,23 +1342,26 @@ function two() { return function three() { one(); } -}` +}`, }; return createWatchedSystem([file, libFile]); }, edits: [ { caption: "Change file to module", - edit: sys => sys.writeFile("/a/b/file.ts", `function one() {} + edit: sys => + sys.writeFile( + "/a/b/file.ts", + `function one() {} export function two() { return function three() { one(); } -}`), +}`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - - } - ] + }, + ], }); verifyTscWatch({ @@ -1313,11 +1372,11 @@ export function two() { const projectLocation = "/home/username/project"; const file: File = { path: `${projectLocation}/src/file1.ts`, - content: "var a = 10;" + content: "var a = 10;", }; const configFile: File = { path: `${projectLocation}/tsconfig.json`, - content: "{}" + content: "{}", }; return createWatchedSystem([file, libFile, configFile]); }, @@ -1326,8 +1385,8 @@ export function two() { caption: "Rename file1 to file2", edit: sys => sys.renameFile("/home/username/project/src/file1.ts", "/home/username/project/src/file2.ts"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); function changeParameterTypeOfBFile(parameterName: string, toType: string): TscWatchCompileChange { @@ -1346,14 +1405,14 @@ export function two() { const aFile: File = { path: `/user/username/projects/myproject/a.ts`, content: `import test from './b'; -test(4, 5);` +test(4, 5);`, }; const bFile: File = { path: `/user/username/projects/myproject/b.ts`, content: `function test(x: number, y: number) { return x + y / 5; } -export default test;` +export default test;`, }; const tsconfigFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, @@ -1362,8 +1421,8 @@ export default test;` module: "commonjs", noEmit: true, strict: true, - } - }) + }, + }), }; return createWatchedSystem([aFile, bFile, libFile, tsconfigFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1372,7 +1431,7 @@ export default test;` changeParameterTypeOfBFile("x", "number"), changeParameterTypeOfBFile("y", "string"), changeParameterTypeOfBFile("y", "number"), - ] + ], }); verifyTscWatch({ @@ -1383,11 +1442,11 @@ export default test;` const aFile: File = { path: `/user/username/projects/myproject/a.ts`, content: `declare function foo(): null | { hello: any }; -foo().hello` +foo().hello`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: {} }) + content: JSON.stringify({ compilerOptions: {} }), }; return createWatchedSystem([aFile, config, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1407,7 +1466,7 @@ foo().hello` edit: sys => sys.writeFile(`/user/username/projects/myproject/tsconfig.json`, JSON.stringify({ compilerOptions: {} })), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1426,11 +1485,11 @@ foo().hello` reallyLongPropertyName6: string | number | boolean | object | symbol | bigint; reallyLongPropertyName7: string | number | boolean | object | symbol | bigint; }; -v === 'foo';` +v === 'foo';`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: {} }) + content: JSON.stringify({ compilerOptions: {} }), }; return createWatchedSystem([aFile, config, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1440,7 +1499,7 @@ v === 'foo';` edit: sys => sys.writeFile(`/user/username/projects/myproject/tsconfig.json`, JSON.stringify({ compilerOptions: { noErrorTruncation: true } })), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1451,11 +1510,11 @@ v === 'foo';` const aFile: File = { path: `/a.ts`, content: `class C { get prop() { return 1; } } -class D extends C { prop = 1; }` +class D extends C { prop = 1; }`, }; const config: File = { path: `/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { target: "es6" } }) + content: JSON.stringify({ compilerOptions: { target: "es6" } }), }; return createWatchedSystem([aFile, config, libFile]); }, @@ -1465,7 +1524,7 @@ class D extends C { prop = 1; }` edit: sys => sys.writeFile(`/tsconfig.json`, JSON.stringify({ compilerOptions: { target: "es6", useDefineForClassFields: true } })), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1475,16 +1534,16 @@ class D extends C { prop = 1; }` sys: () => { const aFile: File = { path: `/user/username/projects/myproject/a.ts`, - content: `export class C {}` + content: `export class C {}`, }; const bFile: File = { path: `/user/username/projects/myproject/b.ts`, content: `import {C} from './a'; -export function f(p: C) { return p; }` +export function f(p: C) { return p; }`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: {} }) + content: JSON.stringify({ compilerOptions: {} }), }; return createWatchedSystem([aFile, bFile, config, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1504,10 +1563,9 @@ export function f(p: C) { return p; }` edit: sys => sys.writeFile(`/user/username/projects/myproject/tsconfig.json`, JSON.stringify({ compilerOptions: { importsNotUsedAsValues: "preserve" } })), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); - verifyTscWatch({ scenario, subScenario: "updates errors when forceConsistentCasingInFileNames changes", @@ -1515,15 +1573,15 @@ export function f(p: C) { return p; }` sys: () => { const aFile: File = { path: `/a.ts`, - content: `export class C {}` + content: `export class C {}`, }; const bFile: File = { path: `/b.ts`, - content: `import {C} from './a'; import * as A from './A';` + content: `import {C} from './a'; import * as A from './A';`, }; const config: File = { path: `/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: false } }) + content: JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: false } }), }; return createWatchedSystem([aFile, bFile, config, libFile], { useCaseSensitiveFileNames: false }); }, @@ -1533,7 +1591,7 @@ export function f(p: C) { return p; }` edit: sys => sys.writeFile(`/tsconfig.json`, JSON.stringify({ compilerOptions: { forceConsistentCasingInFileNames: true } })), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1543,15 +1601,15 @@ export function f(p: C) { return p; }` sys: () => { const aFile: File = { path: `/user/username/projects/myproject/a.ts`, - content: `import * as data from './data.json'` + content: `import * as data from './data.json'`, }; const jsonFile: File = { path: `/user/username/projects/myproject/data.json`, - content: `{ "foo": 1 }` + content: `{ "foo": 1 }`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { moduleResolution: "node" } }) + content: JSON.stringify({ compilerOptions: { moduleResolution: "node" } }), }; return createWatchedSystem([aFile, jsonFile, config, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1561,7 +1619,7 @@ export function f(p: C) { return p; }` edit: sys => sys.writeFile(`/user/username/projects/myproject/tsconfig.json`, JSON.stringify({ compilerOptions: { moduleResolution: "node", resolveJsonModule: true } })), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1573,11 +1631,11 @@ export function f(p: C) { return p; }` path: `/user/username/projects/myproject/a.ts`, content: `declare module 'a' { type foo = number; -}` +}`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; return createWatchedSystem([aFile, config, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1585,9 +1643,13 @@ export function f(p: C) { return p; }` { caption: "Create b.ts with same content", // Create bts with same file contents - edit: sys => sys.writeFile(`/user/username/projects/myproject/b.ts`, `declare module 'a' { + edit: sys => + sys.writeFile( + `/user/username/projects/myproject/b.ts`, + `declare module 'a' { type foo = number; -}`), +}`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { @@ -1595,7 +1657,7 @@ export function f(p: C) { return p; }` edit: sys => sys.deleteFile(`/user/username/projects/myproject/b.ts`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); describe("updates errors in lib file", () => { @@ -1609,7 +1671,7 @@ export function f(p: C) { return p; }` content: `${libFile.content} interface Document { readonly ${field}: boolean; -}` +}`, }; function verifyLibFileErrorsWith(subScenario: string, aFile: File) { @@ -1630,7 +1692,7 @@ interface Document { edit: sys => sys.writeFile(aFile.path, aFile.content), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); } @@ -1643,7 +1705,7 @@ interface Document { const aFile: File = { path: `/user/username/projects/myproject/a.ts`, content: `${fieldWithoutReadonly} -var y: number;` +var y: number;`, }; verifyLibFileErrorsWith("when non module file changes", aFile); }); @@ -1655,7 +1717,7 @@ var y: number;` declare global { ${fieldWithoutReadonly} var y: number; -}` +}`, }; verifyLibFileErrorsWith("when module file with global definitions changes", aFile); }); @@ -1680,24 +1742,24 @@ var y: number; path: `/user/username/projects/myproject/a.ts`, content: `interface Document { ${field}: boolean; -}` +}`, }; const bFile: File = { path: `/user/username/projects/myproject/b.d.ts`, content: `interface Document { ${field}: boolean; -}` +}`, }; const libFileWithDocument: File = { path: libFile.path, content: `${libFile.content} interface Document { readonly ${field}: boolean; -}` +}`, }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; return createWatchedSystem([aFile, bFile, configFile, libFileWithDocument], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1708,7 +1770,7 @@ interface Document { changeWhenLibCheckChanges({ skipDefaultLibCheck: true }), changeWhenLibCheckChanges({ skipLibCheck: true }), changeWhenLibCheckChanges({}), - ] + ], }); verifyTscWatch({ @@ -1718,20 +1780,20 @@ interface Document { sys: () => { const aFile: File = { path: `/user/username/projects/myproject/a.ts`, - content: `export const a: string = "";` + content: `export const a: string = "";`, }; const bFile: File = { path: `/user/username/projects/myproject/b.ts`, content: `import { a } from "./a"; -const b: string = a;` +const b: string = a;`, }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - isolatedModules: true - } - }) + isolatedModules: true, + }, + }), }; return createWatchedSystem([aFile, bFile, configFile, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1741,7 +1803,7 @@ const b: string = a;` edit: sys => sys.writeFile(`/user/username/projects/myproject/a.ts`, `export const a: number = 1`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1751,32 +1813,36 @@ const b: string = a;` sys: () => { const aFile: File = { path: `/user/username/projects/myproject/a.ts`, - content: `import { x } from "../b";` + content: `import { x } from "../b";`, }; const bFile: File = { path: `/user/username/projects/b.ts`, - content: `export const x = 10;` + content: `export const x = 10;`, }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { rootDir: ".", - outDir: "lib" - } - }) + outDir: "lib", + }, + }), }; return createWatchedSystem([aFile, bFile, configFile, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, edits: [ { caption: "Make changes to file a", - edit: sys => sys.writeFile(`/user/username/projects/myproject/a.ts`, ` + edit: sys => + sys.writeFile( + `/user/username/projects/myproject/a.ts`, + ` -import { x } from "../b";`), +import { x } from "../b";`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1786,15 +1852,15 @@ import { x } from "../b";`), sys: () => { const index: File = { path: `/user/username/projects/myproject/index.tsx`, - content: `declare var React: any;\nconst d =
;` + content: `declare var React: any;\nconst d =
;`, }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - jsx: "preserve" - } - }) + jsx: "preserve", + }, + }), }; return createWatchedSystem([index, configFile, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1804,7 +1870,7 @@ import { x } from "../b";`), edit: sys => sys.writeFile(`/user/username/projects/myproject/tsconfig.json`, '{ "compilerOptions": { "jsx": "react" } }'), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1816,65 +1882,86 @@ import { x } from "../b";`), path: "/a/b/first.tsconfig.json", content: JSON.stringify({ compilerOptions: { - strict: true - } - }) + strict: true, + }, + }), }; const secondExtendedConfigFile: File = { path: "/a/b/second.tsconfig.json", content: JSON.stringify({ - extends: "./first.tsconfig.json" - }) + extends: "./first.tsconfig.json", + }), }; const configFile: File = { path: configFilePath, content: JSON.stringify({ compilerOptions: {}, - files: [commonFile1.path, commonFile2.path] - }) + files: [commonFile1.path, commonFile2.path], + }), }; return createWatchedSystem([ - libFile, commonFile1, commonFile2, configFile, firstExtendedConfigFile, secondExtendedConfigFile + libFile, + commonFile1, + commonFile2, + configFile, + firstExtendedConfigFile, + secondExtendedConfigFile, ]); }, edits: [ { caption: "Change config to extend another config", - edit: sys => sys.modifyFile(configFilePath, JSON.stringify({ - extends: "./second.tsconfig.json", - compilerOptions: {}, - files: [commonFile1.path, commonFile2.path] - })), + edit: sys => + sys.modifyFile( + configFilePath, + JSON.stringify({ + extends: "./second.tsconfig.json", + compilerOptions: {}, + files: [commonFile1.path, commonFile2.path], + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Change first extended config", - edit: sys => sys.modifyFile("/a/b/first.tsconfig.json", JSON.stringify({ - compilerOptions: { - strict: false, - } - })), + edit: sys => + sys.modifyFile( + "/a/b/first.tsconfig.json", + JSON.stringify({ + compilerOptions: { + strict: false, + }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Change second extended config", - edit: sys => sys.modifyFile("/a/b/second.tsconfig.json", JSON.stringify({ - extends: "./first.tsconfig.json", - compilerOptions: { - strictNullChecks: true, - } - })), + edit: sys => + sys.modifyFile( + "/a/b/second.tsconfig.json", + JSON.stringify({ + extends: "./first.tsconfig.json", + compilerOptions: { + strictNullChecks: true, + }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Change config to stop extending another config", - edit: sys => sys.modifyFile(configFilePath, JSON.stringify({ - compilerOptions: {}, - files: [commonFile1.path, commonFile2.path] - })), + edit: sys => + sys.modifyFile( + configFilePath, + JSON.stringify({ + compilerOptions: {}, + files: [commonFile1.path, commonFile2.path], + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1884,11 +1971,11 @@ import { x } from "../b";`), sys: () => { const module1: File = { path: `/user/username/projects/myproject/client/folder1/module1.ts`, - content: `export class Module1Class { }` + content: `export class Module1Class { }`, }; const module2: File = { path: `/user/username/projects/myproject/folder2/module2.ts`, - content: `import * as M from "folder1/module1";` + content: `import * as M from "folder1/module1";`, }; const symlink: SymLink = { path: `/user/username/projects/myproject/client/linktofolder2`, @@ -1901,8 +1988,8 @@ import { x } from "../b";`), baseUrl: "client", paths: { "*": ["*"] }, }, - include: ["client/**/*", "folder2"] - }) + include: ["client/**/*", "folder2"], + }), }; return createWatchedSystem([module1, module2, symlink, config, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -1912,7 +1999,7 @@ import { x } from "../b";`), edit: sys => sys.writeFile(`/user/username/projects/myproject/client/linktofolder2/module3.ts`, `import * as M from "folder1/module1";`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1925,35 +2012,35 @@ import { x } from "../b";`), content: JSON.stringify({ compilerOptions: { module: "none", - composite: true + composite: true, }, - exclude: ["temp"] - }) + exclude: ["temp"], + }), }; const class1: File = { path: `/user/username/projects/myproject/projects/project1/class1.ts`, - content: `class class1 {}` + content: `class class1 {}`, }; // Built file const class1Dt: File = { path: `/user/username/projects/myproject/projects/project1/class1.d.ts`, - content: `declare class class1 {}` + content: `declare class class1 {}`, }; const config2: File = { path: `/user/username/projects/myproject/projects/project2/tsconfig.json`, content: JSON.stringify({ compilerOptions: { module: "none", - composite: true + composite: true, }, references: [ - { path: "../project1" } - ] - }) + { path: "../project1" }, + ], + }), }; const class2: File = { path: `/user/username/projects/myproject/projects/project2/class2.ts`, - content: `class class2 {}` + content: `class class2 {}`, }; return createWatchedSystem([config1, class1, config2, class2, libFile, class1Dt]); }, @@ -1983,7 +2070,7 @@ import { x } from "../b";`), edit: sys => sys.writeFile(`/user/username/projects/myproject/projects/project1/class3.d.ts`, `declare class class3 {}`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -1993,11 +2080,11 @@ import { x } from "../b";`), sys: () => { const module1: File = { path: `/user/username/projects/myproject/index.ts`, - content: `` + content: ``, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: `{}` + content: `{}`, }; return createWatchedSystem([module1, config, libFile], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -2007,7 +2094,7 @@ import { x } from "../b";`), edit: sys => sys.writeFile(`/user/username/projects/myproject/foo`, ``), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ @@ -2017,19 +2104,19 @@ import { x } from "../b";`), sys: () => { const module1: File = { path: `/user/username/projects/myproject/a.ts`, - content: `` + content: ``, }; const module2: File = { path: `/user/username/projects/myproject/b.ts`, - content: `import "./a.ts";` + content: `import "./a.ts";`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { noEmit: true, - allowImportingTsExtensions: false - } + allowImportingTsExtensions: false, + }, }), }; return createWatchedSystem([module1, module2, config, libFile], { currentDirectory: "/user/username/projects/myproject" }); @@ -2037,14 +2124,18 @@ import { x } from "../b";`), edits: [ { caption: "Change allowImportingTsExtensions to true", - edit: sys => sys.writeFile(`/user/username/projects/myproject/tsconfig.json`, JSON.stringify({ - compilerOptions: { - noEmit: true, - allowImportingTsExtensions: true - } - })), + edit: sys => + sys.writeFile( + `/user/username/projects/myproject/tsconfig.json`, + JSON.stringify({ + compilerOptions: { + noEmit: true, + allowImportingTsExtensions: true, + }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); }); diff --git a/src/testRunner/unittests/tscWatch/projectsWithReferences.ts b/src/testRunner/unittests/tscWatch/projectsWithReferences.ts index 8c091768df202..1fe3bc5200e05 100644 --- a/src/testRunner/unittests/tscWatch/projectsWithReferences.ts +++ b/src/testRunner/unittests/tscWatch/projectsWithReferences.ts @@ -2,7 +2,9 @@ import { createSolutionBuilder, createSystemWithSolutionBuild, } from "../helpers/solutionBuilder"; -import { verifyTscWatch } from "../helpers/tscWatch"; +import { + verifyTscWatch, +} from "../helpers/tscWatch"; import { getTsBuildProjectFile, getTsBuildProjectFilePath, @@ -14,21 +16,22 @@ describe("unittests:: tsc-watch:: projects with references: invoking when refere verifyTscWatch({ scenario: "projectsWithReferences", subScenario: "on sample project", - sys: () => createSystemWithSolutionBuild( - ["tests"], - [ - libFile, - getTsBuildProjectFile("sample1", "core/tsconfig.json"), - getTsBuildProjectFile("sample1", "core/index.ts"), - getTsBuildProjectFile("sample1", "core/anotherModule.ts"), - getTsBuildProjectFile("sample1", "core/some_decl.d.ts"), - getTsBuildProjectFile("sample1", "logic/tsconfig.json"), - getTsBuildProjectFile("sample1", "logic/index.ts"), - getTsBuildProjectFile("sample1", "tests/tsconfig.json"), - getTsBuildProjectFile("sample1", "tests/index.ts"), - ], - { currentDirectory: `/user/username/projects/sample1` } - ), + sys: () => + createSystemWithSolutionBuild( + ["tests"], + [ + libFile, + getTsBuildProjectFile("sample1", "core/tsconfig.json"), + getTsBuildProjectFile("sample1", "core/index.ts"), + getTsBuildProjectFile("sample1", "core/anotherModule.ts"), + getTsBuildProjectFile("sample1", "core/some_decl.d.ts"), + getTsBuildProjectFile("sample1", "logic/tsconfig.json"), + getTsBuildProjectFile("sample1", "logic/index.ts"), + getTsBuildProjectFile("sample1", "tests/tsconfig.json"), + getTsBuildProjectFile("sample1", "tests/index.ts"), + ], + { currentDirectory: `/user/username/projects/sample1` }, + ), commandLineArgs: ["-w", "-p", "tests", "--traceResolution", "--explainFiles"], edits: [ { @@ -49,22 +52,25 @@ describe("unittests:: tsc-watch:: projects with references: invoking when refere const solutionBuilder = createSolutionBuilder(sys, ["logic"]); solutionBuilder.build(); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "change in project reference config file builds correctly", edit: sys => { - sys.writeFile(getTsBuildProjectFilePath("sample1", "logic/tsconfig.json"), JSON.stringify({ - compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, - references: [{ path: "../core" }] - })); + sys.writeFile( + getTsBuildProjectFilePath("sample1", "logic/tsconfig.json"), + JSON.stringify({ + compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, + references: [{ path: "../core" }], + }), + ); const solutionBuilder = createSolutionBuilder(sys, ["logic"]); solutionBuilder.build(); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], - baselineDependencies: true + baselineDependencies: true, }); function changeCompilerOpitonsPaths(sys: TestServerHost, config: string, newPaths: object) { @@ -76,20 +82,21 @@ describe("unittests:: tsc-watch:: projects with references: invoking when refere verifyTscWatch({ scenario: "projectsWithReferences", subScenario: "on transitive references", - sys: () => createSystemWithSolutionBuild( - ["tsconfig.c.json"], - [ - libFile, - getTsBuildProjectFile("transitiveReferences", "tsconfig.a.json"), - getTsBuildProjectFile("transitiveReferences", "tsconfig.b.json"), - getTsBuildProjectFile("transitiveReferences", "tsconfig.c.json"), - getTsBuildProjectFile("transitiveReferences", "a.ts"), - getTsBuildProjectFile("transitiveReferences", "b.ts"), - getTsBuildProjectFile("transitiveReferences", "c.ts"), - getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), - ], - { currentDirectory: `/user/username/projects/transitiveReferences` } - ), + sys: () => + createSystemWithSolutionBuild( + ["tsconfig.c.json"], + [ + libFile, + getTsBuildProjectFile("transitiveReferences", "tsconfig.a.json"), + getTsBuildProjectFile("transitiveReferences", "tsconfig.b.json"), + getTsBuildProjectFile("transitiveReferences", "tsconfig.c.json"), + getTsBuildProjectFile("transitiveReferences", "a.ts"), + getTsBuildProjectFile("transitiveReferences", "b.ts"), + getTsBuildProjectFile("transitiveReferences", "c.ts"), + getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), + ], + { currentDirectory: `/user/username/projects/transitiveReferences` }, + ), commandLineArgs: ["-w", "-p", "tsconfig.c.json", "--traceResolution", "--explainFiles"], edits: [ { @@ -99,53 +106,53 @@ describe("unittests:: tsc-watch:: projects with references: invoking when refere const solutionBuilder = createSolutionBuilder(sys, ["tsconfig.b.json"]); solutionBuilder.build(); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "edit on config file", edit: sys => { sys.ensureFileOrFolder({ path: getTsBuildProjectFilePath("transitiveReferences", "nrefs/a.d.ts"), - content: sys.readFile(getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))! + content: sys.readFile(getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))!, }); changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "tsconfig.c.json"), { "@ref/*": ["./nrefs/*"] }); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert config file edit", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "tsconfig.c.json"), { "@ref/*": ["./refs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "edit in referenced config file", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json"), { "@ref/*": ["./nrefs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert referenced config file edit", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json"), { "@ref/*": ["./refs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "deleting referenced config file", edit: sys => sys.deleteFile(getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json")), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert deleting referenced config file", edit: sys => sys.ensureFileOrFolder(getTsBuildProjectFile("transitiveReferences", "tsconfig.b.json")), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "deleting transitively referenced config file", edit: sys => sys.deleteFile(getTsBuildProjectFilePath("transitiveReferences", "tsconfig.a.json")), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert deleting transitively referenced config file", edit: sys => sys.ensureFileOrFolder(getTsBuildProjectFile("transitiveReferences", "tsconfig.a.json")), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], baselineDependencies: true, @@ -154,30 +161,31 @@ describe("unittests:: tsc-watch:: projects with references: invoking when refere verifyTscWatch({ scenario: "projectsWithReferences", subScenario: "when referenced project uses different module resolution", - sys: () => createSystemWithSolutionBuild( - ["tsconfig.c.json"], - [ - libFile, - getTsBuildProjectFile("transitiveReferences", "tsconfig.a.json"), - { - path: getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json"), - content: JSON.stringify({ - compilerOptions: { composite: true, moduleResolution: "classic" }, - files: ["b.ts"], - references: [{ path: "tsconfig.a.json" }] - }) - }, - getTsBuildProjectFile("transitiveReferences", "tsconfig.c.json"), - getTsBuildProjectFile("transitiveReferences", "a.ts"), - { - path: getTsBuildProjectFilePath("transitiveReferences", "b.ts"), - content: `import {A} from "a";export const b = new A();` - }, - getTsBuildProjectFile("transitiveReferences", "c.ts"), - getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), - ], - { currentDirectory: `/user/username/projects/transitiveReferences` } - ), + sys: () => + createSystemWithSolutionBuild( + ["tsconfig.c.json"], + [ + libFile, + getTsBuildProjectFile("transitiveReferences", "tsconfig.a.json"), + { + path: getTsBuildProjectFilePath("transitiveReferences", "tsconfig.b.json"), + content: JSON.stringify({ + compilerOptions: { composite: true, moduleResolution: "classic" }, + files: ["b.ts"], + references: [{ path: "tsconfig.a.json" }], + }), + }, + getTsBuildProjectFile("transitiveReferences", "tsconfig.c.json"), + getTsBuildProjectFile("transitiveReferences", "a.ts"), + { + path: getTsBuildProjectFilePath("transitiveReferences", "b.ts"), + content: `import {A} from "a";export const b = new A();`, + }, + getTsBuildProjectFile("transitiveReferences", "c.ts"), + getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), + ], + { currentDirectory: `/user/username/projects/transitiveReferences` }, + ), commandLineArgs: ["-w", "-p", "tsconfig.c.json", "--traceResolution", "--explainFiles"], baselineDependencies: true, }); @@ -185,53 +193,54 @@ describe("unittests:: tsc-watch:: projects with references: invoking when refere verifyTscWatch({ scenario: "projectsWithReferences", subScenario: "on transitive references in different folders", - sys: () => createSystemWithSolutionBuild( - ["c"], - [ - libFile, - { - path: getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), - content: JSON.stringify({ - compilerOptions: { composite: true }, - files: ["index.ts"] - }), - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), - content: JSON.stringify({ - compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, - files: ["index.ts"], - references: [{ path: `../a` }] - }), - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), - content: JSON.stringify({ - compilerOptions: { baseUrl: "./", paths: { "@ref/*": ["../refs/*"] } }, - files: ["index.ts"], - references: [{ path: `../b` }] - }), - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "a/index.ts"), - content: `export class A {}`, - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "b/index.ts"), - content: `import {A} from '@ref/a'; + sys: () => + createSystemWithSolutionBuild( + ["c"], + [ + libFile, + { + path: getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { composite: true }, + files: ["index.ts"], + }), + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + files: ["index.ts"], + references: [{ path: `../a` }], + }), + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { baseUrl: "./", paths: { "@ref/*": ["../refs/*"] } }, + files: ["index.ts"], + references: [{ path: `../b` }], + }), + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "a/index.ts"), + content: `export class A {}`, + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "b/index.ts"), + content: `import {A} from '@ref/a'; export const b = new A();`, - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "c/index.ts"), - content: `import {b} from '../b'; + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "c/index.ts"), + content: `import {b} from '../b'; import {X} from "@ref/a"; b; X;`, - }, - getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), - ], - { currentDirectory: `/user/username/projects/transitiveReferences` } - ), + }, + getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), + ], + { currentDirectory: `/user/username/projects/transitiveReferences` }, + ), commandLineArgs: ["-w", "-p", "c", "--traceResolution", "--explainFiles"], edits: [ { @@ -241,66 +250,68 @@ X;`, const solutionBuilder = createSolutionBuilder(sys, ["b"]); solutionBuilder.build(); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "edit on config file", edit: sys => { sys.ensureFileOrFolder({ path: getTsBuildProjectFilePath("transitiveReferences", "nrefs/a.d.ts"), - content: sys.readFile(getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))! + content: sys.readFile(getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))!, }); changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), { "@ref/*": ["../nrefs/*"] }); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert config file edit", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), { "@ref/*": ["../refs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "edit in referenced config file", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), { "@ref/*": ["../nrefs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert referenced config file edit", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), { "@ref/*": ["../refs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "deleting referenced config file", edit: sys => sys.deleteFile(getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json")), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert deleting referenced config file", - edit: sys => sys.writeFile( - getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), - JSON.stringify({ - compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, - files: ["index.ts"], - references: [{ path: `../a` }] - }) - ), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + edit: sys => + sys.writeFile( + getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), + JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + files: ["index.ts"], + references: [{ path: `../a` }], + }), + ), + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "deleting transitively referenced config file", edit: sys => sys.deleteFile(getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json")), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert deleting transitively referenced config file", - edit: sys => sys.writeFile( - getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), - JSON.stringify({ - compilerOptions: { composite: true }, - files: ["index.ts"] - }), - ), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + edit: sys => + sys.writeFile( + getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), + JSON.stringify({ + compilerOptions: { composite: true }, + files: ["index.ts"], + }), + ), + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], baselineDependencies: true, @@ -309,48 +320,49 @@ X;`, verifyTscWatch({ scenario: "projectsWithReferences", subScenario: "on transitive references in different folders with no files clause", - sys: () => createSystemWithSolutionBuild( - ["c"], - [ - libFile, - { - path: getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), - content: JSON.stringify({ compilerOptions: { composite: true } }), - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), - content: JSON.stringify({ - compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, - references: [{ path: `../a` }] - }), - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), - content: JSON.stringify({ - compilerOptions: { baseUrl: "./", paths: { "@ref/*": ["../refs/*"] } }, - references: [{ path: `../b` }] - }), - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "a/index.ts"), - content: `export class A {}`, - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "b/index.ts"), - content: `import {A} from '@ref/a'; + sys: () => + createSystemWithSolutionBuild( + ["c"], + [ + libFile, + { + path: getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), + content: JSON.stringify({ compilerOptions: { composite: true } }), + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + references: [{ path: `../a` }], + }), + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), + content: JSON.stringify({ + compilerOptions: { baseUrl: "./", paths: { "@ref/*": ["../refs/*"] } }, + references: [{ path: `../b` }], + }), + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "a/index.ts"), + content: `export class A {}`, + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "b/index.ts"), + content: `import {A} from '@ref/a'; export const b = new A();`, - }, - { - path: getTsBuildProjectFilePath("transitiveReferences", "c/index.ts"), - content: `import {b} from '../b'; + }, + { + path: getTsBuildProjectFilePath("transitiveReferences", "c/index.ts"), + content: `import {b} from '../b'; import {X} from "@ref/a"; b; X;`, - }, - getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), - ], - { currentDirectory: `/user/username/projects/transitiveReferences` } - ), + }, + getTsBuildProjectFile("transitiveReferences", "refs/a.d.ts"), + ], + { currentDirectory: `/user/username/projects/transitiveReferences` }, + ), commandLineArgs: ["-w", "-p", "c", "--traceResolution", "--explainFiles"], edits: [ { @@ -360,62 +372,64 @@ X;`, const solutionBuilder = createSolutionBuilder(sys, ["b"]); solutionBuilder.build(); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "edit on config file", edit: sys => { sys.ensureFileOrFolder({ path: getTsBuildProjectFilePath("transitiveReferences", "nrefs/a.d.ts"), - content: sys.readFile(getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))! + content: sys.readFile(getTsBuildProjectFilePath("transitiveReferences", "refs/a.d.ts"))!, }); changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), { "@ref/*": ["../nrefs/*"] }); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert config file edit", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "c/tsconfig.json"), { "@ref/*": ["../refs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "edit in referenced config file", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), { "@ref/*": ["../nrefs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert referenced config file edit", edit: sys => changeCompilerOpitonsPaths(sys, getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), { "@ref/*": ["../refs/*"] }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "deleting referenced config file", edit: sys => sys.deleteFile(getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json")), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert deleting referenced config file", - edit: sys => sys.writeFile( - getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), - JSON.stringify({ - compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, - references: [{ path: `../a` }] - }) - ), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + edit: sys => + sys.writeFile( + getTsBuildProjectFilePath("transitiveReferences", "b/tsconfig.json"), + JSON.stringify({ + compilerOptions: { composite: true, baseUrl: "./", paths: { "@ref/*": ["../*"] } }, + references: [{ path: `../a` }], + }), + ), + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "deleting transitively referenced config file", edit: sys => sys.deleteFile(getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json")), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Revert deleting transitively referenced config file", - edit: sys => sys.writeFile( - getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), - JSON.stringify({ compilerOptions: { composite: true } }), - ), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + edit: sys => + sys.writeFile( + getTsBuildProjectFilePath("transitiveReferences", "a/tsconfig.json"), + JSON.stringify({ compilerOptions: { composite: true } }), + ), + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], baselineDependencies: true, @@ -424,19 +438,20 @@ X;`, verifyTscWatch({ scenario: "projectsWithReferences", subScenario: "when declarationMap changes for dependency", - sys: () => createSystemWithSolutionBuild( - ["core"], - [ - libFile, - getTsBuildProjectFile("sample1", "core/tsconfig.json"), - getTsBuildProjectFile("sample1", "core/index.ts"), - getTsBuildProjectFile("sample1", "core/anotherModule.ts"), - getTsBuildProjectFile("sample1", "core/some_decl.d.ts"), - getTsBuildProjectFile("sample1", "logic/tsconfig.json"), - getTsBuildProjectFile("sample1", "logic/index.ts"), - ], - { currentDirectory: `/user/username/projects/sample1` } - ), + sys: () => + createSystemWithSolutionBuild( + ["core"], + [ + libFile, + getTsBuildProjectFile("sample1", "core/tsconfig.json"), + getTsBuildProjectFile("sample1", "core/index.ts"), + getTsBuildProjectFile("sample1", "core/anotherModule.ts"), + getTsBuildProjectFile("sample1", "core/some_decl.d.ts"), + getTsBuildProjectFile("sample1", "logic/tsconfig.json"), + getTsBuildProjectFile("sample1", "logic/index.ts"), + ], + { currentDirectory: `/user/username/projects/sample1` }, + ), commandLineArgs: ["-w", "-p", "logic", "--traceResolution", "--explainFiles"], edits: [ { @@ -449,6 +464,6 @@ X;`, timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], - baselineDependencies: true + baselineDependencies: true, }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tscWatch/resolutionCache.ts b/src/testRunner/unittests/tscWatch/resolutionCache.ts index e40425630e63a..0ab9c2bbf0c58 100644 --- a/src/testRunner/unittests/tscWatch/resolutionCache.ts +++ b/src/testRunner/unittests/tscWatch/resolutionCache.ts @@ -1,6 +1,8 @@ import * as ts from "../../_namespaces/ts"; import * as Utils from "../../_namespaces/Utils"; -import { libContent } from "../helpers/contents"; +import { + libContent, +} from "../helpers/contents"; import { createBaseline, createWatchCompilerHostOfFilesAndCompilerOptionsForBaseline, @@ -19,11 +21,11 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution it("caching works", () => { const root = { path: "/users/username/projects/project/d/f0.ts", - content: `import {x} from "f1"` + content: `import {x} from "f1"`, }; const imported = { path: "/users/username/projects/project/f1.ts", - content: `foo()` + content: `foo()`, }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem([root, imported, libFile])); @@ -32,7 +34,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution system: sys, options: { module: ts.ModuleKind.AMD }, cb, - watchOptions: undefined + watchOptions: undefined, }); const originalFileExists = host.fileExists; const watch = ts.createWatchProgram(host); @@ -51,10 +53,13 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution edit: sys => { // patch fileExists to make sure that disk is not touched host.fileExists = ts.notImplemented; - sys.writeFile(root.path, `import {x} from "f1" - var x: string = 1;`); + sys.writeFile( + root.path, + `import {x} from "f1" + var x: string = 1;`, + ); }, - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Resolves f2", @@ -91,22 +96,22 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution timeouts: sys => { sys.runQueuedTimeoutCallbacks(); assert.isTrue(fileExistsIsCalled); - } + }, }, ], - watchOrSolution: watch + watchOrSolution: watch, }); }); it("loads missing files from disk", () => { const root = { path: `/users/username/projects/project/foo.ts`, - content: `import {x} from "bar"` + content: `import {x} from "bar"`, }; const imported = { path: `/users/username/projects/project/bar.d.ts`, - content: `export const y = 1;` + content: `export const y = 1;`, }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem([root, libFile])); @@ -115,7 +120,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution system: sys, options: { module: ts.ModuleKind.AMD }, cb, - watchOptions: undefined + watchOptions: undefined, }); const originalFileExists = host.fileExists; let fileExistsCalledForBar = false; @@ -144,27 +149,27 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution caption: "write imported file", edit: sys => { fileExistsCalledForBar = false; - sys.writeFile(root.path,`import {y} from "bar"`); + sys.writeFile(root.path, `import {y} from "bar"`); sys.writeFile(imported.path, imported.content); }, timeouts: sys => { sys.runQueuedTimeoutCallbacks(); assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called."); - } + }, }], - watchOrSolution: watch + watchOrSolution: watch, }); }); it("should compile correctly when resolved module goes missing and then comes back (module is not part of the root)", () => { const root = { path: `/users/username/projects/project/foo.ts`, - content: `import {x} from "bar"` + content: `import {x} from "bar"`, }; const imported = { path: `/users/username/projects/project/bar.d.ts`, - content: `export const y = 1;export const x = 10;` + content: `export const y = 1;export const x = 10;`, }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem([root, imported, libFile])); @@ -173,7 +178,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution system: sys, options: { module: ts.ModuleKind.AMD }, cb, - watchOptions: undefined + watchOptions: undefined, }); const originalFileExists = host.fileExists; let fileExistsCalledForBar = false; @@ -221,7 +226,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution }, }, ], - watchOrSolution: watch + watchOrSolution: watch, }); }); @@ -229,10 +234,11 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution scenario, subScenario: "works when module resolution changes to ambient module", commandLineArgs: ["-w", "/users/username/projects/project/foo.ts"], - sys: () => createWatchedSystem([{ - path: "/users/username/projects/project/foo.ts", - content: `import * as fs from "fs";` - }, libFile], { currentDirectory: "/users/username/projects/project" }), + sys: () => + createWatchedSystem([{ + path: "/users/username/projects/project/foo.ts", + content: `import * as fs from "fs";`, + }, libFile], { currentDirectory: "/users/username/projects/project" }), edits: [ { caption: "npm install node types", @@ -243,7 +249,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution { "main": "" } -` +`, }); sys.ensureFileOrFolder({ path: "/users/username/projects/project/node_modules/@types/node/index.d.ts", @@ -252,12 +258,12 @@ declare module "fs" { export interface Stats { isFile(): boolean; } -}` +}`, }); }, timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -270,7 +276,7 @@ declare module "fs" { content: ` import * as fs from "fs"; import * as u from "url"; -` +`, }; const file = { @@ -281,23 +287,27 @@ declare module "url" { href?: string; } } -` +`, }; return createWatchedSystem([root, file, libFile], { currentDirectory: "/users/username/projects/project" }); }, edits: [ { caption: "Add fs definition", - edit: sys => sys.appendFile("/users/username/projects/project/bar.d.ts", ` + edit: sys => + sys.appendFile( + "/users/username/projects/project/bar.d.ts", + ` declare module "fs" { export interface Stats { isFile(): boolean; } } -`), +`, + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -308,15 +318,15 @@ declare module "fs" { const configDir = "/a/b/projects/myProject/src/"; const file1: File = { path: configDir + "file1.ts", - content: 'import module1 = require("module1");\nmodule1("hello");' + content: 'import module1 = require("module1");\nmodule1("hello");', }; const file2: File = { path: configDir + "file2.ts", - content: 'import module11 = require("module1");\nmodule11("hello");' + content: 'import module11 = require("module1");\nmodule11("hello");', }; const module1: File = { path: "/a/b/projects/myProject/node_modules/module1/index.js", - content: "module.exports = options => { return options.toString(); }" + content: "module.exports = options => { return options.toString(); }", }; const configFile: File = { path: configDir + "tsconfig.json", @@ -326,9 +336,9 @@ declare module "fs" { rootDir: ".", outDir: "../dist", moduleResolution: "node", - maxNodeModuleJsDepth: 1 - } - }) + maxNodeModuleJsDepth: 1, + }, + }), }; return createWatchedSystem([file1, file2, module1, libFile, configFile], { currentDirectory: "/a/b/projects/myProject/" }); }, @@ -337,8 +347,8 @@ declare module "fs" { caption: "Add new line to file1", edit: sys => sys.appendFile("/a/b/projects/myProject/src/file1.ts", "\n;"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); verifyTscWatch({ @@ -348,11 +358,11 @@ declare module "fs" { sys: () => { const file: File = { path: `/user/username/projects/myproject/a.ts`, - content: `import * as q from "qqq";` + content: `import * as q from "qqq";`, }; const module: File = { path: `/user/username/projects/myproject/node_modules2/@types/qqq/index.d.ts`, - content: "export {}" + content: "export {}", }; return createWatchedSystem([file, libFile, module], { currentDirectory: "/user/username/projects/myproject" }); }, @@ -361,8 +371,8 @@ declare module "fs" { caption: "npm install", edit: sys => sys.renameFolder(`/user/username/projects/myproject/node_modules2`, `/user/username/projects/myproject/node_modules`), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); describe("ignores files/folder changes in node_modules that start with '.'", () => { @@ -374,28 +384,29 @@ declare module "fs" { sys: () => { const file1: File = { path: `/user/username/projects/myproject/test.ts`, - content: `import { x } from "somemodule";` + content: `import { x } from "somemodule";`, }; const file2: File = { path: `/user/username/projects/myproject/node_modules/somemodule/index.d.ts`, - content: `export const x = 10;` + content: `export const x = 10;`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; return createWatchedSystem([libFile, file1, file2, config]); }, edits: [ { caption: "npm install file and folder that start with '.'", - edit: sys => sys.ensureFileOrFolder({ - path: `/user/username/projects/myproject/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, - content: JSON.stringify({ something: 10 }) - }), + edit: sys => + sys.ensureFileOrFolder({ + path: `/user/username/projects/myproject/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, + content: JSON.stringify({ something: 10 }), + }), timeouts: sys => sys.logTimeoutQueueLength(), - } - ] + }, + ], }); } verifyIgnore("watch without configFile", ["--w", `/user/username/projects/myproject/test.ts`]); @@ -409,16 +420,16 @@ declare module "fs" { sys: () => { const app: File = { path: `/user/username/projects/myproject/lib/app.ts`, - content: `myapp.component("hello");` + content: `myapp.component("hello");`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { module: "none", - types: ["@myapp/ts-types"] - } - }) + types: ["@myapp/ts-types"], + }, + }), }; return createWatchedSystem([app, tsconfig, libFile]); }, @@ -430,15 +441,15 @@ declare module "fs" { path: `/user/username/projects/myproject/node_modules/@myapp/ts-types/package.json`, content: JSON.stringify({ version: "1.65.1", - types: "types/somefile.define.d.ts" - }) + types: "types/somefile.define.d.ts", + }), }); sys.ensureFileOrFolder({ path: `/user/username/projects/myproject/node_modules/@myapp/ts-types/types/somefile.define.d.ts`, content: ` declare namespace myapp { function component(str: string): number; -}` +}`, }); }, timeouts: sys => { @@ -454,9 +465,9 @@ declare namespace myapp { const newProgram = (watchorSolution as ts.WatchOfConfigFile).getProgram(); assert.strictEqual(newProgram, oldBuilderProgram, "No change so builder program should be same"); assert.strictEqual(newProgram.getProgram(), oldProgram, "No change so program should be same"); - } - } - ] + }, + }, + ], }); verifyTscWatch({ @@ -468,30 +479,30 @@ declare namespace myapp { const linkedPackageRoot = `/user/username/projects/myproject/linked-package`; const mainFile: File = { path: `${mainPackageRoot}/index.ts`, - content: "import { Foo } from '@scoped/linked-package'" + content: "import { Foo } from '@scoped/linked-package'", }; const config: File = { path: `${mainPackageRoot}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { module: "commonjs", moduleResolution: "node", baseUrl: ".", rootDir: "." }, - files: ["index.ts"] - }) + files: ["index.ts"], + }), }; const linkedPackageInMain: SymLink = { path: `${mainPackageRoot}/node_modules/@scoped/linked-package`, - symLink: `${linkedPackageRoot}` + symLink: `${linkedPackageRoot}`, }; const linkedPackageJson: File = { path: `${linkedPackageRoot}/package.json`, - content: JSON.stringify({ name: "@scoped/linked-package", version: "0.0.1", types: "dist/index.d.ts", main: "dist/index.js" }) + content: JSON.stringify({ name: "@scoped/linked-package", version: "0.0.1", types: "dist/index.d.ts", main: "dist/index.js" }), }; const linkedPackageIndex: File = { path: `${linkedPackageRoot}/dist/index.d.ts`, - content: "export * from './other';" + content: "export * from './other';", }; const linkedPackageOther: File = { path: `${linkedPackageRoot}/dist/other.d.ts`, - content: 'export declare const Foo = "BAR";' + content: 'export declare const Foo = "BAR";', }; const files = [libFile, mainFile, config, linkedPackageInMain, linkedPackageJson, linkedPackageIndex, linkedPackageOther]; return createWatchedSystem(files, { currentDirectory: mainPackageRoot }); @@ -502,16 +513,16 @@ declare namespace myapp { function getNodeAtTypes() { const nodeAtTypesIndex: File = { path: `/user/username/projects/myproject/node_modules/@types/node/index.d.ts`, - content: `/// ` + content: `/// `, }; const nodeAtTypesBase: File = { path: `/user/username/projects/myproject/node_modules/@types/node/base.d.ts`, content: `// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -/// ` +/// `, }; const nodeAtTypes36Base: File = { path: `/user/username/projects/myproject/node_modules/@types/node/ts3.6/base.d.ts`, - content: `/// ` + content: `/// `, }; const nodeAtTypesGlobals: File = { path: `/user/username/projects/myproject/node_modules/@types/node/globals.d.ts`, @@ -520,7 +531,7 @@ declare namespace NodeJS { interface Process { on(msg: string): void; } -}` +}`, }; return { nodeAtTypesIndex, nodeAtTypesBase, nodeAtTypes36Base, nodeAtTypesGlobals }; } @@ -531,11 +542,11 @@ declare namespace NodeJS { sys: () => { const file: File = { path: `/user/username/projects/myproject/worker.ts`, - content: `process.on("uncaughtException");` + content: `process.on("uncaughtException");`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const { nodeAtTypesIndex, nodeAtTypesBase, nodeAtTypes36Base, nodeAtTypesGlobals } = getNodeAtTypes(); return createWatchedSystem([file, libFile, tsconfig, nodeAtTypesIndex, nodeAtTypesBase, nodeAtTypes36Base, nodeAtTypesGlobals], { currentDirectory: "/user/username/projects/myproject" }); @@ -548,16 +559,17 @@ declare namespace NodeJS { }, { caption: `npm ci step two: create atTypes but something else in the @types folder`, - edit: sys => sys.ensureFileOrFolder({ - path: `/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts`, - content: `export const foo = 10;` - }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + edit: sys => + sys.ensureFileOrFolder({ + path: `/user/username/projects/myproject/node_modules/@types/mocha/index.d.ts`, + content: `export const foo = 10;`, + }), + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: `npm ci step three: create atTypes node folder`, edit: sys => sys.ensureFileOrFolder({ path: `/user/username/projects/myproject/node_modules/@types/node` }), - timeouts: sys => sys.runQueuedTimeoutCallbacks() + timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: `npm ci step four: create atTypes write all the files but dont invoke watcher for index.d.ts`, @@ -573,35 +585,36 @@ declare namespace NodeJS { sys.runQueuedTimeoutCallbacks(); // actual program update }, }, - ] + ], }); }); verifyTscWatch({ scenario, subScenario: "reusing type ref resolution", - sys: () => createWatchedSystem({ - "/users/username/projects/project/tsconfig.json": JSON.stringify({ - compilerOptions: { - composite: true, - traceResolution: true, - outDir: "outDir", - }, - }), - "/users/username/projects/project/fileWithImports.ts": Utils.dedent` + sys: () => + createWatchedSystem({ + "/users/username/projects/project/tsconfig.json": JSON.stringify({ + compilerOptions: { + composite: true, + traceResolution: true, + outDir: "outDir", + }, + }), + "/users/username/projects/project/fileWithImports.ts": Utils.dedent` import type { Import0 } from "pkg0"; import type { Import1 } from "pkg1"; `, - "/users/username/projects/project/node_modules/pkg0/index.d.ts": `export interface Import0 {}`, - "/users/username/projects/project/fileWithTypeRefs.ts": Utils.dedent` + "/users/username/projects/project/node_modules/pkg0/index.d.ts": `export interface Import0 {}`, + "/users/username/projects/project/fileWithTypeRefs.ts": Utils.dedent` /// /// interface LocalInterface extends Import2, Import3 {} export {} `, - "/users/username/projects/project/node_modules/pkg2/index.d.ts": `interface Import2 {}`, - [libFile.path]: libFile.content, - }, { currentDirectory: "/users/username/projects/project" }), + "/users/username/projects/project/node_modules/pkg2/index.d.ts": `interface Import2 {}`, + [libFile.path]: libFile.content, + }, { currentDirectory: "/users/username/projects/project" }), commandLineArgs: ["-w", "--explainFiles", "--extendedDiagnostics"], edits: [ { @@ -610,7 +623,7 @@ declare namespace NodeJS { timeouts: sys => { sys.runQueuedTimeoutCallbacks(); // failed lookup sys.runQueuedTimeoutCallbacks(); // actual update - } + }, }, { caption: "write file not resolved by typeRef", @@ -618,30 +631,32 @@ declare namespace NodeJS { timeouts: sys => { sys.runQueuedTimeoutCallbacks(); // failed lookup sys.runQueuedTimeoutCallbacks(); // actual update - } + }, }, - ] + ], }); verifyTscWatch({ scenario, subScenario: "scoped package installation", commandLineArgs: ["--w", "-p", `.`, "--traceResolution", "--extendedDiagnostics"], - sys: () => createWatchedSystem({ - "/user/username/projects/myproject/lib/app.ts": Utils.dedent` + sys: () => + createWatchedSystem({ + "/user/username/projects/myproject/lib/app.ts": Utils.dedent` import { myapp } from "@myapp/ts-types"; const x: 10 = myapp; `, - "/user/username/projects/myproject/tsconfig.json": "{}", - [libFile.path]: libContent, - }, { currentDirectory: "/user/username/projects/myproject" }), + "/user/username/projects/myproject/tsconfig.json": "{}", + [libFile.path]: libContent, + }, { currentDirectory: "/user/username/projects/myproject" }), edits: [ { caption: "npm install unrelated non scoped", - edit: sys => sys.ensureFileOrFolder({ - path: `/user/username/projects/myproject/node_modules/unrelated/index.d.ts`, - content: `export const unrelated = 10;` - }), + edit: sys => + sys.ensureFileOrFolder({ + path: `/user/username/projects/myproject/node_modules/unrelated/index.d.ts`, + content: `export const unrelated = 10;`, + }), timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); @@ -649,10 +664,11 @@ declare namespace NodeJS { }, { caption: "npm install unrelated scoped in myapp", - edit: sys => sys.ensureFileOrFolder({ - path: `/user/username/projects/myproject/node_modules/@myapp/unrelated/index.d.ts`, - content: `export const myappUnrelated = 10;` - }), + edit: sys => + sys.ensureFileOrFolder({ + path: `/user/username/projects/myproject/node_modules/@myapp/unrelated/index.d.ts`, + content: `export const myappUnrelated = 10;`, + }), timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); @@ -660,10 +676,11 @@ declare namespace NodeJS { }, { caption: "npm install unrelated2 scoped in myapp", - edit: sys => sys.ensureFileOrFolder({ - path: `/user/username/projects/myproject/node_modules/@myapp/unrelated2/index.d.ts`, - content: `export const myappUnrelated2 = 10;` - }), + edit: sys => + sys.ensureFileOrFolder({ + path: `/user/username/projects/myproject/node_modules/@myapp/unrelated2/index.d.ts`, + content: `export const myappUnrelated2 = 10;`, + }), timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); @@ -671,15 +688,16 @@ declare namespace NodeJS { }, { caption: "npm install ts-types", - edit: sys => sys.ensureFileOrFolder({ - path: `/user/username/projects/myproject/node_modules/@myapp/ts-types/index.d.ts`, - content: `export const myapp = 10;` - }), + edit: sys => + sys.ensureFileOrFolder({ + path: `/user/username/projects/myproject/node_modules/@myapp/ts-types/index.d.ts`, + content: `export const myapp = 10;`, + }), timeouts: sys => { sys.runQueuedTimeoutCallbacks(); sys.runQueuedTimeoutCallbacks(); }, }, - ] + ], }); }); diff --git a/src/testRunner/unittests/tscWatch/resolveJsonModuleWithIncremental.ts b/src/testRunner/unittests/tscWatch/resolveJsonModuleWithIncremental.ts index e4a1d09ac2019..ca6bd441fa680 100644 --- a/src/testRunner/unittests/tscWatch/resolveJsonModuleWithIncremental.ts +++ b/src/testRunner/unittests/tscWatch/resolveJsonModuleWithIncremental.ts @@ -10,18 +10,19 @@ describe("unittests:: tsc-watch:: resolveJsonModuleWithIncremental:: emit file - verifyTscWatch({ scenario: "resolveJsonModule", subScenario: "incremental always prefers declaration file over document", - sys: () => createWatchedSystem({ - "/src/project/main.ts": `import data from "./data.json"; let x: string = data;`, - "/src/project/data.json": `{}`, // this file intentionally left blank - "/src/project/data.d.json.ts": `declare var val: string; export default val;`, - "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { resolveJsonModule: true } }, null, 4), // eslint-disable-line no-null/no-null - [libFile.path]: libFile.content, - }), + sys: () => + createWatchedSystem({ + "/src/project/main.ts": `import data from "./data.json"; let x: string = data;`, + "/src/project/data.json": `{}`, // this file intentionally left blank + "/src/project/data.d.json.ts": `declare var val: string; export default val;`, + "/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { resolveJsonModule: true } }, null, 4), // eslint-disable-line no-null/no-null + [libFile.path]: libFile.content, + }), commandLineArgs: ["--p", "src/project", "-i", "-w"], edits: [{ caption: "Change json setting", edit: sys => sys.writeFile("/src/project/tsconfig.json", JSON.stringify({ compilerOptions: { resolveJsonModule: false } }, null, 4)), // eslint-disable-line no-null/no-null timeouts: sys => sys.runQueuedTimeoutCallbacks(), - }] + }], }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tscWatch/sourceOfProjectReferenceRedirect.ts b/src/testRunner/unittests/tscWatch/sourceOfProjectReferenceRedirect.ts index e8f6810564ca4..9977c12c6c604 100644 --- a/src/testRunner/unittests/tscWatch/sourceOfProjectReferenceRedirect.ts +++ b/src/testRunner/unittests/tscWatch/sourceOfProjectReferenceRedirect.ts @@ -1,6 +1,10 @@ import * as ts from "../../_namespaces/ts"; -import { libContent } from "../helpers/contents"; -import { solutionBuildWithBaseline } from "../helpers/solutionBuilder"; +import { + libContent, +} from "../helpers/contents"; +import { + solutionBuildWithBaseline, +} from "../helpers/solutionBuilder"; import { createBaseline, createWatchCompilerHostOfConfigFileForBaseline, @@ -28,7 +32,7 @@ describe("unittests:: tsc-watch:: watchAPI:: with sourceOfProjectReferenceRedire alreadyBuilt ? (sys, originalRead) => { solutionBuildWithBaseline(sys, [config], originalRead); sys.clearOutput(); - } : undefined + } : undefined, ); const host = createWatchCompilerHostOfConfigFileForBaseline({ configFileName: config, @@ -45,7 +49,7 @@ describe("unittests:: tsc-watch:: watchAPI:: with sourceOfProjectReferenceRedire baseline, oldSnap, getPrograms, - watchOrSolution: watch + watchOrSolution: watch, }); } @@ -71,7 +75,7 @@ describe("unittests:: tsc-watch:: watchAPI:: with sourceOfProjectReferenceRedire return { files: [{ path: libFile.path, content: libContent }, baseConfig, coreTs, coreConfig, animalTs, dogTs, indexTs, animalsConfig], config: animalsConfig.path, - subScenario: "with simple project" + subScenario: "with simple project", }; }); }); @@ -102,7 +106,7 @@ describe("unittests:: tsc-watch:: watchAPI:: with sourceOfProjectReferenceRedire return { files: [libFile, bPackageJson, aConfig, bConfig, aTest, bFoo, bBar, bSymlink], config: aConfig.path, - subScenario: `${subScenario}${extraOptions.preserveSymlinks ? " with preserveSymlinks" : ""}` + subScenario: `${subScenario}${extraOptions.preserveSymlinks ? " with preserveSymlinks" : ""}`, }; }); } @@ -115,18 +119,18 @@ describe("unittests:: tsc-watch:: watchAPI:: with sourceOfProjectReferenceRedire outDir: "lib", rootDir: "src", composite: true, - ...extraOptions + ...extraOptions, }, include: ["src"], - ...(references ? { references: references.map(path => ({ path })) } : {}) - }) + ...(references ? { references: references.map(path => ({ path })) } : {}), + }), }; } function file(packageName: string, fileName: string, content: string): File { return { path: `/user/username/projects/myproject/packages/${packageName}/src/${fileName}`, - content + content, }; } @@ -137,21 +141,25 @@ describe("unittests:: tsc-watch:: watchAPI:: with sourceOfProjectReferenceRedire path: `/user/username/projects/myproject/packages/B/package.json`, content: JSON.stringify({ main: "lib/index.js", - types: "lib/index.d.ts" - }) + types: "lib/index.d.ts", + }), }, - aTest: file("A", "index.ts", `import { foo } from '${scope}b'; + aTest: file( + "A", + "index.ts", + `import { foo } from '${scope}b'; import { bar } from '${scope}b/lib/bar'; foo(); bar(); -`), +`, + ), bFoo: file("B", "index.ts", `export function foo() { }`), bBar: file("B", "bar.ts", `export function bar() { }`), bSymlink: { path: `/user/username/projects/myproject/node_modules/${scope}b`, - symLink: `/user/username/projects/myproject/packages/B` + symLink: `/user/username/projects/myproject/packages/B`, }, - subScenario: `when packageJson has types field${scope ? " with scoped package" : ""}` + subScenario: `when packageJson has types field${scope ? " with scoped package" : ""}`, })); }); @@ -159,20 +167,24 @@ bar(); verifySymlinkScenario(() => ({ bPackageJson: { path: `/user/username/projects/myproject/packages/B/package.json`, - content: "{}" + content: "{}", }, - aTest: file("A", "test.ts", `import { foo } from '${scope}b/lib/foo'; + aTest: file( + "A", + "test.ts", + `import { foo } from '${scope}b/lib/foo'; import { bar } from '${scope}b/lib/bar/foo'; foo(); bar(); -`), +`, + ), bFoo: file("B", "foo.ts", `export function foo() { }`), bBar: file("B", "bar/foo.ts", `export function bar() { }`), bSymlink: { path: `/user/username/projects/myproject/node_modules/${scope}b`, - symLink: `/user/username/projects/myproject/packages/B` + symLink: `/user/username/projects/myproject/packages/B`, }, - subScenario: `when referencing file from subFolder${scope ? " with scoped package" : ""}` + subScenario: `when referencing file from subFolder${scope ? " with scoped package" : ""}`, })); }); } diff --git a/src/testRunner/unittests/tscWatch/watchApi.ts b/src/testRunner/unittests/tscWatch/watchApi.ts index 81274cbbf1932..2620266a6028d 100644 --- a/src/testRunner/unittests/tscWatch/watchApi.ts +++ b/src/testRunner/unittests/tscWatch/watchApi.ts @@ -1,8 +1,14 @@ import * as Harness from "../../_namespaces/Harness"; import * as ts from "../../_namespaces/ts"; -import { dedent } from "../../_namespaces/Utils"; -import { commandLineCallbacks } from "../helpers/baseline"; -import { libContent } from "../helpers/contents"; +import { + dedent, +} from "../../_namespaces/Utils"; +import { + commandLineCallbacks, +} from "../helpers/baseline"; +import { + libContent, +} from "../helpers/contents"; import { applyEdit, createBaseline, @@ -22,39 +28,40 @@ describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolu it("verify that module resolution with json extension works when returned without extension", () => { const configFileJson: any = { compilerOptions: { module: "commonjs", resolveJsonModule: true }, - files: ["index.ts"] + files: ["index.ts"], }; const mainFile: File = { path: `/user/username/projects/myproject/index.ts`, - content: "import settings from './settings.json';" + content: "import settings from './settings.json';", }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify(configFileJson) + content: JSON.stringify(configFileJson), }; const settingsJson: File = { path: `/user/username/projects/myproject/settings.json`, - content: JSON.stringify({ content: "Print this" }) + content: JSON.stringify({ content: "Print this" }), }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem( [libFile, mainFile, config, settingsJson], - { currentDirectory: "/user/username/projects/myproject" }), - ); + { currentDirectory: "/user/username/projects/myproject" }, + )); const host = createWatchCompilerHostOfConfigFileForBaseline({ configFileName: config.path, system: sys, cb, }); const parsedCommandResult = ts.parseJsonConfigFileContent(configFileJson, sys, config.path); - host.resolveModuleNames = (moduleNames, containingFile) => moduleNames.map(m => { - const result = ts.resolveModuleName(m, containingFile, parsedCommandResult.options, host); - const resolvedModule = result.resolvedModule!; - return { - resolvedFileName: resolvedModule.resolvedFileName, - isExternalLibraryImport: resolvedModule.isExternalLibraryImport, - originalFileName: resolvedModule.originalPath, - }; - }); + host.resolveModuleNames = (moduleNames, containingFile) => + moduleNames.map(m => { + const result = ts.resolveModuleName(m, containingFile, parsedCommandResult.options, host); + const resolvedModule = result.resolvedModule!; + return { + resolvedFileName: resolvedModule.resolvedFileName, + isExternalLibraryImport: resolvedModule.isExternalLibraryImport, + originalFileName: resolvedModule.originalPath, + }; + }); const watch = ts.createWatchProgram(host); runWatchBaseline({ scenario: "watchApi", @@ -64,7 +71,7 @@ describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolu baseline, oldSnap, getPrograms, - watchOrSolution: watch + watchOrSolution: watch, }); }); @@ -74,7 +81,7 @@ describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolu const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem({ [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ compilerOptions: { traceResolution: true, extendedDiagnostics: true }, - files: ["main.ts"] + files: ["main.ts"], }), [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./other";`, [`/user/username/projects/myproject/other.d.ts`]: "export function foo(): void;", @@ -85,8 +92,7 @@ describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolu system: sys, cb, }); - host.resolveModuleNames = (moduleNames, containingFile, _reusedNames, _redirectedReference, options) => - moduleNames.map(m => ts.resolveModuleName(m, containingFile, options, host).resolvedModule); + host.resolveModuleNames = (moduleNames, containingFile, _reusedNames, _redirectedReference, options) => moduleNames.map(m => ts.resolveModuleName(m, containingFile, options, host).resolvedModule); // Invalidate resolutions only when ts file is created if (implementHasInvalidatedResolution) host.hasInvalidatedResolutions = () => sys.fileExists(`/user/username/projects/myproject/other.ts`); const watch = ts.createWatchProgram(host); @@ -118,7 +124,7 @@ describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolu timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], - watchOrSolution: watch + watchOrSolution: watch, }); }); } @@ -133,17 +139,17 @@ describe("unittests:: tsc-watch:: watchAPI:: tsc-watch expose error count to wat path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { module: "commonjs" }, - files: ["index.ts"] - }) + files: ["index.ts"], + }), }; const mainFile: File = { path: `/user/username/projects/myproject/index.ts`, - content: "let compiler = new Compiler(); for (let i = 0; j < 5; i++) {}" + content: "let compiler = new Compiler(); for (let i = 0; j < 5; i++) {}", }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem( [libFile, mainFile, config], - { currentDirectory: "/user/username/projects/myproject" }), - ); + { currentDirectory: "/user/username/projects/myproject" }, + )); const host = createWatchCompilerHostOfConfigFileForBaseline({ configFileName: config.path, system: sys, @@ -165,7 +171,7 @@ describe("unittests:: tsc-watch:: watchAPI:: tsc-watch expose error count to wat baseline, oldSnap, getPrograms, - watchOrSolution: watch + watchOrSolution: watch, }); }); }); @@ -174,11 +180,11 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost does not implement s it("verifies that getProgram gets updated program if new file is added to the program", () => { const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const mainFile: File = { path: `/user/username/projects/myproject/main.ts`, - content: "const x = 10;" + content: "const x = 10;", }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem([config, mainFile, libFile])); const host = createWatchCompilerHostOfConfigFileForBaseline({ @@ -203,9 +209,9 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost does not implement s timeouts: sys => { sys.logTimeoutQueueLength(); watch.getProgram(); - } + }, }], - watchOrSolution: watch + watchOrSolution: watch, }); }); }); @@ -214,18 +220,18 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost can add extraFileExt it("verifies that extraFileExtensions are supported to get the program with other extensions", () => { const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const mainFile: File = { path: `/user/username/projects/myproject/main.ts`, - content: "const x = 10;" + content: "const x = 10;", }; const otherFile: File = { path: `/user/username/projects/myproject/other.vue`, - content: "" + content: "", }; const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline( - createWatchedSystem([config, mainFile, otherFile, libFile]) + createWatchedSystem([config, mainFile, otherFile, libFile]), ); const host = createWatchCompilerHostOfConfigFileForBaseline({ configFileName: config.path, @@ -248,7 +254,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost can add extraFileExt edit: sys => sys.writeFile(`/user/username/projects/myproject/other2.vue`, otherFile.content), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }], - watchOrSolution: watch + watchOrSolution: watch, }); }); }); @@ -257,15 +263,15 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost uses createSemanticD function createSystem(configText: string, mainText: string) { const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: configText + content: configText, }; const mainFile: File = { path: `/user/username/projects/myproject/main.ts`, - content: mainText + content: mainText, }; const otherFile: File = { path: `/user/username/projects/myproject/other.ts`, - content: "export const y = 10;" + content: "export const y = 10;", }; return { ...createBaseline(createWatchedSystem([config, mainFile, otherFile, libFile])), @@ -323,7 +329,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost uses createSemanticD sys: TscWatchSystem, emitSys: TscWatchSystem, change: (sys: TscWatchSystem) => void, - caption: string + caption: string, ) { // Change file applyEdit(sys, baseline, change, caption); @@ -337,7 +343,8 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost uses createSemanticD sys: TscWatchSystem, emitSys: TscWatchSystem, createProgram: ts.CreateProgram, - optionsToExtend?: ts.CompilerOptions) { + optionsToExtend?: ts.CompilerOptions, + ) { createWatch(baseline, config, sys, createProgram, optionsToExtend); createWatch(emitBaseline, config, emitSys, ts.createEmitAndSemanticDiagnosticsBuilderProgram, optionsToExtend); verifyOutputs(baseline, sys, emitSys); @@ -366,7 +373,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost uses createSemanticD edit: sys => sys.appendFile(mainFile.path, "\n// SomeComment"), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }], - watchOrSolution: watch + watchOrSolution: watch, }); }); @@ -478,7 +485,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when watchHost uses createSemanticD ts.createCompilerDiagnostic(ts.getWatchErrorSummaryDiagnosticMessage(diagnostics.length), diagnostics.length), sys.newLine, program.getCompilerOptions(), - diagnostics.length + diagnostics.length, ); cb(program); }; @@ -501,34 +508,34 @@ describe("unittests:: tsc-watch:: watchAPI:: when getParsedCommandLine is implem content: JSON.stringify({ compilerOptions: { module: "none", - composite: true + composite: true, }, - exclude: ["temp"] - }) + exclude: ["temp"], + }), }; const class1: File = { path: `/user/username/projects/myproject/projects/project1/class1.ts`, - content: `class class1 {}` + content: `class class1 {}`, }; const class1Dts: File = { path: `/user/username/projects/myproject/projects/project1/class1.d.ts`, - content: `declare class class1 {}` + content: `declare class class1 {}`, }; const config2: File = { path: `/user/username/projects/myproject/projects/project2/tsconfig.json`, content: JSON.stringify({ compilerOptions: { module: "none", - composite: true + composite: true, }, references: [ - { path: "../project1" } - ] - }) + { path: "../project1" }, + ], + }), }; const class2: File = { path: `/user/username/projects/myproject/projects/project2/class2.ts`, - content: `class class2 {}` + content: `class class2 {}`, }; const system = createWatchedSystem([config1, class1, class1Dts, config2, class2, libFile]); const baseline = createBaseline(system); @@ -536,7 +543,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when getParsedCommandLine is implem cb: baseline.cb, system, configFileName: config2.path, - optionsToExtend: { extendedDiagnostics: true } + optionsToExtend: { extendedDiagnostics: true }, }); compilerHost.useSourceOfProjectReferenceRedirect = useSourceOfProjectReferenceRedirect; const calledGetParsedCommandLine = new Set(); @@ -583,7 +590,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when getParsedCommandLine is implem timeouts: sys => sys.logTimeoutQueueLength(), }, ], - watchOrSolution: watch + watchOrSolution: watch, }); }); @@ -624,7 +631,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when getParsedCommandLine is implem timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], - watchOrSolution: watch + watchOrSolution: watch, }); }); }); @@ -646,7 +653,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when builder emit occurs with emitO cb: baseline.cb, system, configFileName: `/user/username/projects/myproject/tsconfig.json`, - optionsToExtend: { extendedDiagnostics: true } + optionsToExtend: { extendedDiagnostics: true }, }); const originalEmitProgram = compilerHost.afterProgramCreate; compilerHost.afterProgramCreate = myAfterProgramCreate; @@ -703,7 +710,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when builder emit occurs with emitO timeouts: sys => sys.logTimeoutQueueLength(), }, ], - watchOrSolution: watch + watchOrSolution: watch, }); function myAfterProgramCreate(program: ts.EmitAndSemanticDiagnosticsBuilderProgram) { @@ -728,7 +735,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when creating program with project "/user/username/projects/project/tsconfig.json": JSON.stringify({ compilerOptions: { types: [] }, files: ["app.ts"], - references: [{ path: "./lib" }] + references: [{ path: "./lib" }], }), "/user/username/projects/project/app.ts": dedent` import { one } from './lib'; @@ -757,7 +764,7 @@ describe("unittests:: tsc-watch:: watchAPI:: when creating program with project getCurrentDirectory: () => system.getCurrentDirectory(), readDirectory: (path, extensions, excludes, includes, depth) => system.readDirectory(path, extensions, excludes, includes, depth), onUnRecoverableConfigFileDiagnostic: ts.noop, - } + }, )!; const compilerHost = createWatchCompilerHostOfFilesAndCompilerOptionsForBaseline({ cb: baseline.cb, @@ -781,14 +788,18 @@ describe("unittests:: tsc-watch:: watchAPI:: when creating program with project edits: [ { caption: "Modify lib tsconfig", - edit: sys => sys.writeFile(`/user/username/projects/project/lib/tsconfig.json`, JSON.stringify({ - compilerOptions: { composite: true }, - files: ["index.ts"], - })), + edit: sys => + sys.writeFile( + `/user/username/projects/project/lib/tsconfig.json`, + JSON.stringify({ + compilerOptions: { composite: true }, + files: ["index.ts"], + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], - watchOrSolution: watch + watchOrSolution: watch, }); }); @@ -802,22 +813,30 @@ describe("unittests:: tsc-watch:: watchAPI:: when creating program with project edits: [ { caption: "Modify lib tsconfig", - edit: sys => sys.writeFile(`/user/username/projects/project/lib/tsconfig.json`, JSON.stringify({ - extends: "./tsconfig.base.json", - compilerOptions: { typeRoots: [] }, - files: ["index.ts"], - })), + edit: sys => + sys.writeFile( + `/user/username/projects/project/lib/tsconfig.json`, + JSON.stringify({ + extends: "./tsconfig.base.json", + compilerOptions: { typeRoots: [] }, + files: ["index.ts"], + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Modify lib extends", - edit: sys => sys.writeFile(`/user/username/projects/project/lib/tsconfig.base.json`, JSON.stringify({ - compilerOptions: { composite: true }, - })), + edit: sys => + sys.writeFile( + `/user/username/projects/project/lib/tsconfig.base.json`, + JSON.stringify({ + compilerOptions: { composite: true }, + }), + ), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, ], - watchOrSolution: watch + watchOrSolution: watch, }); }); }); diff --git a/src/testRunner/unittests/tscWatch/watchEnvironment.ts b/src/testRunner/unittests/tscWatch/watchEnvironment.ts index 79afff507cf16..fb9b5c362540c 100644 --- a/src/testRunner/unittests/tscWatch/watchEnvironment.ts +++ b/src/testRunner/unittests/tscWatch/watchEnvironment.ts @@ -25,7 +25,7 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po const projectFolder = "/a/username/project"; const file1: File = { path: `${projectFolder}/typescript.ts`, - content: "var z = 10;" + content: "var z = 10;", }; const environmentVariables = new Map(); environmentVariables.set("TSC_WATCHFILE", Tsc_WatchFile.DynamicPolling); @@ -77,8 +77,8 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po sys.runQueuedTimeoutCallbacks(); return; }, - } - ] + }, + ], }); verifyTscWatch({ @@ -90,9 +90,9 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po path: "/a/b/tsconfig.json", content: JSON.stringify({ watchOptions: { - watchFile: "FixedChunkSizePolling" - } - }) + watchFile: "FixedChunkSizePolling", + }, + }), }; const files = [libFile, commonFile1, commonFile2, configFile]; return createWatchedSystem(files); @@ -132,7 +132,7 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po assert.deepEqual(programs[0][0], initialProgram); }, }, - ] + ], }); describe("tsc-watch when watchDirectories implementation", () => { @@ -143,13 +143,13 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po path: `${projectFolder}/tsconfig.json`, content: JSON.stringify({ watchOptions: { - synchronousWatchDirectory: true - } - }) + synchronousWatchDirectory: true, + }, + }), }; const file: File = { path: `${projectSrcFolder}/file1.ts`, - content: "" + content: "", }; verifyTscWatch({ scenario, @@ -194,35 +194,35 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po const cwd = "/home/user/projects/myproject"; const file1: File = { path: `${cwd}/src/file.ts`, - content: `import * as a from "a"` + content: `import * as a from "a"`, }; const tsconfig: File = { path: `${cwd}/tsconfig.json`, - content: `{ "compilerOptions": { "extendedDiagnostics": true, "traceResolution": true }}` + content: `{ "compilerOptions": { "extendedDiagnostics": true, "traceResolution": true }}`, }; const realA: File = { path: `${cwd}/node_modules/reala/index.d.ts`, - content: `export {}` + content: `export {}`, }; const realB: File = { path: `${cwd}/node_modules/realb/index.d.ts`, - content: `export {}` + content: `export {}`, }; const symLinkA: SymLink = { path: `${cwd}/node_modules/a`, - symLink: `${cwd}/node_modules/reala` + symLink: `${cwd}/node_modules/reala`, }; const symLinkB: SymLink = { path: `${cwd}/node_modules/b`, - symLink: `${cwd}/node_modules/realb` + symLink: `${cwd}/node_modules/realb`, }; const symLinkBInA: SymLink = { path: `${cwd}/node_modules/reala/node_modules/b`, - symLink: `${cwd}/node_modules/b` + symLink: `${cwd}/node_modules/b`, }; const symLinkAInB: SymLink = { path: `${cwd}/node_modules/realb/node_modules/a`, - symLink: `${cwd}/node_modules/a` + symLink: `${cwd}/node_modules/a`, }; const files = [libFile, file1, tsconfig, realA, realB, symLinkA, symLinkB, symLinkBInA, symLinkAInB]; const environmentVariables = new Map(); @@ -238,15 +238,15 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po sys: () => { const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const file1: File = { path: `/user/username/projects/myproject/src/file1.ts`, - content: `import { x } from "file2";` + content: `import { x } from "file2";`, }; const file2: File = { path: `/user/username/projects/myproject/node_modules/file2/index.d.ts`, - content: `export const x = 10;` + content: `export const x = 10;`, }; const files = [libFile, file1, file2, configFile]; return createWatchedSystem(files, { runWithoutRecursiveWatches: true }); @@ -316,15 +316,15 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po sys: () => { const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { outDir: "dist", declaration: true } }) + content: JSON.stringify({ compilerOptions: { outDir: "dist", declaration: true } }), }; const file1: File = { path: `/user/username/projects/myproject/src/file1.ts`, - content: `import { x } from "file2";` + content: `import { x } from "file2";`, }; const file2: File = { path: `/user/username/projects/myproject/node_modules/file2/index.d.ts`, - content: `export const x = 10;` + content: `export const x = 10;`, }; const files = [libFile, file1, file2, configFile]; return createWatchedSystem(files, { runWithoutRecursiveWatches: true }); @@ -357,15 +357,15 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po sys: () => { const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { outDir: "dist" } }) + content: JSON.stringify({ compilerOptions: { outDir: "dist" } }), }; const file1: File = { path: `/user/username/projects/myproject/src/file1.ts`, - content: `import { x } from "./file2";` + content: `import { x } from "./file2";`, }; const file2: File = { path: `/user/username/projects/myproject/src/file2.ts`, - content: `export const x = 10;` + content: `export const x = 10;`, }; const files = [libFile, file1, file2, configFile]; return createWatchedSystem(files, { runWithoutRecursiveWatches: true }); @@ -401,9 +401,9 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po path: "/a/b/tsconfig.json", content: JSON.stringify({ watchOptions: { - watchFile: "UseFsEvents" - } - }) + watchFile: "UseFsEvents", + }, + }), }; const files = [libFile, commonFile1, commonFile2, configFile]; return createWatchedSystem(files); @@ -419,9 +419,9 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po path: "/a/b/tsconfig.json", content: JSON.stringify({ watchOptions: { - watchDirectory: "UseFsEvents" - } - }) + watchDirectory: "UseFsEvents", + }, + }), }; const files = [libFile, commonFile1, commonFile2, configFile]; return createWatchedSystem(files, { runWithoutRecursiveWatches: true }); @@ -437,9 +437,9 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po path: "/a/b/tsconfig.json", content: JSON.stringify({ watchOptions: { - fallbackPolling: "PriorityInterval" - } - }) + fallbackPolling: "PriorityInterval", + }, + }), }; const files = [libFile, commonFile1, commonFile2, configFile]; return createWatchedSystem(files, { runWithoutRecursiveWatches: true, runWithFallbackPolling: true }); @@ -453,7 +453,7 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po sys: () => { const configFile: File = { path: "/a/b/tsconfig.json", - content: "{}" + content: "{}", }; const files = [libFile, commonFile1, commonFile2, configFile]; return createWatchedSystem(files); @@ -464,27 +464,27 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po function sys(watchOptions: ts.WatchOptions, runWithoutRecursiveWatches?: boolean): TestServerHost { const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ exclude: ["node_modules"], watchOptions }) + content: JSON.stringify({ exclude: ["node_modules"], watchOptions }), }; const main: File = { path: `/user/username/projects/myproject/src/main.ts`, - content: `import { foo } from "bar"; foo();` + content: `import { foo } from "bar"; foo();`, }; const bar: File = { path: `/user/username/projects/myproject/node_modules/bar/index.d.ts`, - content: `export { foo } from "./foo";` + content: `export { foo } from "./foo";`, }; const foo: File = { path: `/user/username/projects/myproject/node_modules/bar/foo.d.ts`, - content: `export function foo(): string;` + content: `export function foo(): string;`, }; const fooBar: File = { path: `/user/username/projects/myproject/node_modules/bar/fooBar.d.ts`, - content: `export function fooBar(): string;` + content: `export function fooBar(): string;`, }; const temp: File = { path: `/user/username/projects/myproject/node_modules/bar/temp/index.d.ts`, - content: "export function temp(): string;" + content: "export function temp(): string;", }; const files = [libFile, main, bar, foo, fooBar, temp, configFile]; return createWatchedSystem(files, { currentDirectory: "/user/username/projects/myproject", runWithoutRecursiveWatches }); @@ -501,8 +501,8 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po caption: "Change foo", edit: sys => sys.replaceFileText(`/user/username/projects/myproject/node_modules/bar/foo.d.ts`, "foo", "fooBar"), timeouts: sys => sys.logTimeoutQueueLength(), - } - ] + }, + ], }); verifyTscWatch({ @@ -514,8 +514,9 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po { caption: "delete fooBar", edit: sys => sys.deleteFile(`/user/username/projects/myproject/node_modules/bar/fooBar.d.ts`), - timeouts: sys => sys.logTimeoutQueueLength(), } - ] + timeouts: sys => sys.logTimeoutQueueLength(), + }, + ], }); verifyTscWatch({ @@ -533,8 +534,8 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po caption: "add new folder to temp", edit: sys => sys.ensureFileOrFolder({ path: `/user/username/projects/myproject/node_modules/bar/temp/fooBar/index.d.ts`, content: "export function temp(): string;" }), timeouts: sys => sys.logTimeoutQueueLength(), - } - ] + }, + ], }); } @@ -547,35 +548,37 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po scenario, subScenario: `fsWatch/when using file watching thats when rename occurs when file is still on the disk`, commandLineArgs: ["-w", "--extendedDiagnostics"], - sys: () => createWatchedSystem( - { - [libFile.path]: libFile.content, - [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./foo"; foo();`, - [`/user/username/projects/myproject/foo.ts`]: `export declare function foo(): string;`, - [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ - watchOptions: { watchFile: "useFsEvents" }, - files: ["foo.ts", "main.ts"] - }), - }, - { currentDirectory: "/user/username/projects/myproject", } - ), + sys: () => + createWatchedSystem( + { + [libFile.path]: libFile.content, + [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./foo"; foo();`, + [`/user/username/projects/myproject/foo.ts`]: `export declare function foo(): string;`, + [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ + watchOptions: { watchFile: "useFsEvents" }, + files: ["foo.ts", "main.ts"], + }), + }, + { currentDirectory: "/user/username/projects/myproject" }, + ), edits: [ { caption: "Introduce error such that when callback happens file is already appeared", // vm's wq generates this kind of event // Skip delete event so inode changes but when the create's rename occurs file is on disk - edit: sys => sys.modifyFile(`/user/username/projects/myproject/foo.ts`, `export declare function foo2(): string;`, { - invokeFileDeleteCreateAsPartInsteadOfChange: true, - ignoreDelete: true, - }), + edit: sys => + sys.modifyFile(`/user/username/projects/myproject/foo.ts`, `export declare function foo2(): string;`, { + invokeFileDeleteCreateAsPartInsteadOfChange: true, + ignoreDelete: true, + }), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Replace file with rename event that fixes error", - edit: sys => sys.modifyFile(`/user/username/projects/myproject/foo.ts`, `export declare function foo(): string;`, { invokeFileDeleteCreateAsPartInsteadOfChange: true, }), + edit: sys => sys.modifyFile(`/user/username/projects/myproject/foo.ts`, `export declare function foo(): string;`, { invokeFileDeleteCreateAsPartInsteadOfChange: true }), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); describe("with fsWatch on inodes", () => { @@ -583,18 +586,19 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po scenario, subScenario: `fsWatch/when using file watching thats on inode`, commandLineArgs: ["-w", "--extendedDiagnostics"], - sys: () => createWatchedSystem( - { - [libFile.path]: libFile.content, - [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./foo"; foo();`, - [`/user/username/projects/myproject/foo.d.ts`]: `export function foo(): string;`, - [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ watchOptions: { watchFile: "useFsEvents" }, files: ["foo.d.ts", "main.ts"] }), - }, - { - currentDirectory: "/user/username/projects/myproject", - inodeWatching: true - } - ), + sys: () => + createWatchedSystem( + { + [libFile.path]: libFile.content, + [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./foo"; foo();`, + [`/user/username/projects/myproject/foo.d.ts`]: `export function foo(): string;`, + [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ watchOptions: { watchFile: "useFsEvents" }, files: ["foo.d.ts", "main.ts"] }), + }, + { + currentDirectory: "/user/username/projects/myproject", + inodeWatching: true, + }, + ), edits: [ { caption: "Replace file with rename event that introduces error", @@ -606,25 +610,26 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po edit: sys => sys.modifyFile(`/user/username/projects/myproject/foo.d.ts`, `export function foo(): string;`, { invokeFileDeleteCreateAsPartInsteadOfChange: true }), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ scenario, subScenario: `fsWatch/when using file watching thats on inode when rename event ends with tilde`, commandLineArgs: ["-w", "--extendedDiagnostics"], - sys: () => createWatchedSystem( - { - [libFile.path]: libFile.content, - [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./foo"; foo();`, - [`/user/username/projects/myproject/foo.d.ts`]: `export function foo(): string;`, - [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ watchOptions: { watchFile: "useFsEvents" }, files: ["foo.d.ts", "main.ts"] }), - }, - { - currentDirectory: "/user/username/projects/myproject", - inodeWatching: true - } - ), + sys: () => + createWatchedSystem( + { + [libFile.path]: libFile.content, + [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./foo"; foo();`, + [`/user/username/projects/myproject/foo.d.ts`]: `export function foo(): string;`, + [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ watchOptions: { watchFile: "useFsEvents" }, files: ["foo.d.ts", "main.ts"] }), + }, + { + currentDirectory: "/user/username/projects/myproject", + inodeWatching: true, + }, + ), edits: [ { caption: "Replace file with rename event that introduces error", @@ -636,46 +641,48 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po edit: sys => sys.modifyFile(`/user/username/projects/myproject/foo.d.ts`, `export function foo(): string;`, { invokeFileDeleteCreateAsPartInsteadOfChange: true, useTildeAsSuffixInRenameEventFileName: true }), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); verifyTscWatch({ scenario, subScenario: `fsWatch/when using file watching thats on inode when rename occurs when file is still on the disk`, commandLineArgs: ["-w", "--extendedDiagnostics"], - sys: () => createWatchedSystem( - { - [libFile.path]: libFile.content, - [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./foo"; foo();`, - [`/user/username/projects/myproject/foo.ts`]: `export declare function foo(): string;`, - [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ - watchOptions: { watchFile: "useFsEvents" }, - files: ["foo.ts", "main.ts"] - }), - }, - { - currentDirectory: "/user/username/projects/myproject", - inodeWatching: true, - } - ), + sys: () => + createWatchedSystem( + { + [libFile.path]: libFile.content, + [`/user/username/projects/myproject/main.ts`]: `import { foo } from "./foo"; foo();`, + [`/user/username/projects/myproject/foo.ts`]: `export declare function foo(): string;`, + [`/user/username/projects/myproject/tsconfig.json`]: JSON.stringify({ + watchOptions: { watchFile: "useFsEvents" }, + files: ["foo.ts", "main.ts"], + }), + }, + { + currentDirectory: "/user/username/projects/myproject", + inodeWatching: true, + }, + ), edits: [ { caption: "Introduce error such that when callback happens file is already appeared", // vm's wq generates this kind of event // Skip delete event so inode changes but when the create's rename occurs file is on disk - edit: sys => sys.modifyFile(`/user/username/projects/myproject/foo.ts`, `export declare function foo2(): string;`, { - invokeFileDeleteCreateAsPartInsteadOfChange: true, - ignoreDelete: true, - skipInodeCheckOnCreate: true - }), + edit: sys => + sys.modifyFile(`/user/username/projects/myproject/foo.ts`, `export declare function foo2(): string;`, { + invokeFileDeleteCreateAsPartInsteadOfChange: true, + ignoreDelete: true, + skipInodeCheckOnCreate: true, + }), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, { caption: "Replace file with rename event that fixes error", - edit: sys => sys.modifyFile(`/user/username/projects/myproject/foo.ts`, `export declare function foo(): string;`, { invokeFileDeleteCreateAsPartInsteadOfChange: true, }), + edit: sys => sys.modifyFile(`/user/username/projects/myproject/foo.ts`, `export declare function foo(): string;`, { invokeFileDeleteCreateAsPartInsteadOfChange: true }), timeouts: sys => sys.runQueuedTimeoutCallbacks(), }, - ] + ], }); }); @@ -683,10 +690,11 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po scenario, subScenario: "fsEvent for change is repeated", commandLineArgs: ["-w", "main.ts", "--extendedDiagnostics"], - sys: () => createWatchedSystem({ - "/user/username/projects/project/main.ts": `let a: string = "Hello"`, - [libFile.path]: libFile.content, - }, { currentDirectory: "/user/username/projects/project" }), + sys: () => + createWatchedSystem({ + "/user/username/projects/project/main.ts": `let a: string = "Hello"`, + [libFile.path]: libFile.content, + }, { currentDirectory: "/user/username/projects/project" }), edits: [ { caption: "change main.ts", @@ -707,7 +715,7 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po caption: "receive another change event without modifying the file", edit: sys => sys.invokeFsWatches("/user/username/projects/project/main.ts", "change", /*modifiedTime*/ undefined, /*useTildeSuffix*/ undefined), timeouts: sys => sys.runQueuedTimeoutCallbacks(), - } - ] + }, + ], }); }); diff --git a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts index d78e6168b0470..03cbe2c5cebee 100644 --- a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts +++ b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts @@ -23,28 +23,28 @@ ${file.content}`; function setup() { const configFile: File = { path: "/a/b/tsconfig.json", - content: "{}" + content: "{}", }; const file3: File = { path: "/a/b/file3.ts", - content: "let xyz = 1;" + content: "let xyz = 1;", }; const app: File = { path: "/a/b/app.ts", - content: "let z = 1;" + content: "let z = 1;", }; const host = createServerHost([app, file3, commonFile1, commonFile2, libFile, configFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Open, - arguments: { file: app.path } + arguments: { file: app.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Open, arguments: { file: file3.path, - fileContent: fileContentWithComment(file3) - } + fileContent: fileContentWithComment(file3), + }, }); return { session, file3, app }; } @@ -58,12 +58,12 @@ ${file.content}`; openFiles: [ { fileName: commonFile1.path, - content: fileContentWithComment(commonFile1) + content: fileContentWithComment(commonFile1), }, { fileName: commonFile2.path, - content: fileContentWithComment(commonFile2) - } + content: fileContentWithComment(commonFile2), + }, ], changedFiles: [ { @@ -71,19 +71,19 @@ ${file.content}`; changes: [ { span: { start: 0, length: 0 }, - newText: "let zzz = 10;" + newText: "let zzz = 10;", }, { span: { start: 0, length: 0 }, - newText: "let zz = 10;" - } - ] - } + newText: "let zz = 10;", + }, + ], + }, ], closedFiles: [ - file3.path - ] - } + file3.path, + ], + }, }); // Open file1 again session.executeCommandSeq({ @@ -91,9 +91,9 @@ ${file.content}`; arguments: { openFiles: [{ fileName: commonFile1.path, - content: commonFile1.content - }] - } + content: commonFile1.content, + }], + }, }); baselineTsserverLogs("applyChangesToOpenFiles", "with applyChangedToOpenFiles request", session); }); @@ -107,12 +107,12 @@ ${file.content}`; openFiles: [ { file: commonFile1.path, - fileContent: fileContentWithComment(commonFile1) + fileContent: fileContentWithComment(commonFile1), }, { file: commonFile2.path, - fileContent: fileContentWithComment(commonFile2) - } + fileContent: fileContentWithComment(commonFile2), + }, ], changedFiles: [ { @@ -127,14 +127,14 @@ ${file.content}`; start: { line: 1, offset: 1 }, end: { line: 1, offset: 1 }, newText: "let zz = 10;", - } - ] - } + }, + ], + }, ], closedFiles: [ - file3.path - ] - } + file3.path, + ], + }, }); // Open file1 again session.executeCommandSeq({ @@ -142,9 +142,9 @@ ${file.content}`; arguments: { openFiles: [{ file: commonFile1.path, - fileContent: commonFile1.content - }] - } + fileContent: commonFile1.content, + }], + }, }); baselineTsserverLogs("applyChangesToOpenFiles", "with updateOpen request", session); }); diff --git a/src/testRunner/unittests/tsserver/autoImportProvider.ts b/src/testRunner/unittests/tsserver/autoImportProvider.ts index f07a52f9112eb..dfa7eb11506cd 100644 --- a/src/testRunner/unittests/tsserver/autoImportProvider.ts +++ b/src/testRunner/unittests/tsserver/autoImportProvider.ts @@ -32,11 +32,11 @@ const tsconfig: File = { }; const packageJson: File = { path: "/package.json", - content: `{ "dependencies": { "@angular/forms": "*", "@angular/core": "*" } }` + content: `{ "dependencies": { "@angular/forms": "*", "@angular/core": "*" } }`, }; const indexTs: File = { path: "/index.ts", - content: "" + content: "", }; describe("unittests:: tsserver:: autoImportProvider", () => { @@ -46,7 +46,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularFormsPackageJson, tsconfig, { path: packageJson.path, content: `{ "dependencies": {} }` }, - indexTs + indexTs, ]); openFilesForSession([indexTs], session); assert.isUndefined(projectService.configuredProjects.get(tsconfig.path)!.getLanguageService().getAutoImportProvider()); @@ -59,7 +59,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularFormsPackageJson, tsconfig, packageJson, - { path: indexTs.path, content: "import '@angular/forms';" } + { path: indexTs.path, content: "import '@angular/forms';" }, ]); openFilesForSession([indexTs], session); assert.isUndefined(projectService.configuredProjects.get(tsconfig.path)!.getLanguageService().getAutoImportProvider()); @@ -77,10 +77,12 @@ describe("unittests:: tsserver:: autoImportProvider", () => { ]); openFilesForSession([angularFormsDts], session); - assert.isUndefined(projectService - .getDefaultProjectForFile(angularFormsDts.path as ts.server.NormalizedPath, /*ensureProject*/ true)! - .getLanguageService() - .getAutoImportProvider()); + assert.isUndefined( + projectService + .getDefaultProjectForFile(angularFormsDts.path as ts.server.NormalizedPath, /*ensureProject*/ true)! + .getLanguageService() + .getAutoImportProvider(), + ); baselineTsserverLogs("autoImportProvider", "projects already inside node_modules", session); }); @@ -102,7 +104,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularFormsPackageJson, tsconfig, { path: "/package.json", content: "{}" }, - indexTs + indexTs, ]); openFilesForSession([indexTs], session); @@ -119,7 +121,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularFormsPackageJson, tsconfig, packageJson, - indexTs + indexTs, ]); openFilesForSession([indexTs], session); @@ -129,7 +131,8 @@ describe("unittests:: tsserver:: autoImportProvider", () => { updateFile(indexTs.path, "console.log(0)"); assert.strictEqual( projectService.configuredProjects.get(tsconfig.path)!.getLanguageService().getAutoImportProvider(), - autoImportProvider); + autoImportProvider, + ); baselineTsserverLogs("autoImportProvider", "Reuses autoImportProvider when program structure is unchanged", session); }); @@ -139,7 +142,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularFormsPackageJson, tsconfig, packageJson, - indexTs + indexTs, ]); openFilesForSession([indexTs], session); @@ -159,7 +162,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularFormsDts, angularFormsPackageJson, tsconfig, - indexTs + indexTs, ]); // Create configured project only, ensure !projectService.pendingEnsureProjectForOpenFiles @@ -184,7 +187,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularCorePackageJson, tsconfig, packageJson, - indexTs + indexTs, ]); openFilesForSession([indexTs], session); @@ -212,7 +215,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularCorePackageJson, tsconfig, packageJson, - indexTs + indexTs, ]); openFilesForSession([indexTs, angularFormsDts], session); @@ -233,7 +236,7 @@ describe("unittests:: tsserver:: autoImportProvider", () => { angularFormsPackageJson, tsconfig, { path: packageJson.path, content: "{" }, - indexTs + indexTs, ]); openFilesForSession([indexTs], session); @@ -245,10 +248,10 @@ describe("unittests:: tsserver:: autoImportProvider", () => { }); it("Does not create an auto import provider if there are too many dependencies", () => { - const createPackage = (i: number): File[] => ([ + const createPackage = (i: number): File[] => [ { path: `/node_modules/package${i}/package.json`, content: `{ "name": "package${i}" }` }, - { path: `/node_modules/package${i}/index.d.ts`, content: `` } - ]); + { path: `/node_modules/package${i}/index.d.ts`, content: `` }, + ]; const packages = []; for (let i = 0; i < 11; i++) { @@ -321,7 +324,7 @@ describe("unittests:: tsserver:: autoImportProvider - monorepo", () => { // packages/b { path: "/packages/b/package.json", content: packageJson.content }, { path: "/packages/b/tsconfig.json", content: `{ "compilerOptions": { "composite": true } }` }, - { path: "/packages/b/index.ts", content: `export class B {}` } + { path: "/packages/b/index.ts", content: `export class B {}` }, ]; const { projectService, session, findAllReferences } = setup(files); @@ -344,7 +347,7 @@ describe("unittests:: tsserver:: autoImportProvider - monorepo", () => { // packages/b { path: "/packages/a/node_modules/b/package.json", content: `{ "types": "dist/index.d.ts" }` }, { path: "/packages/a/node_modules/b/tsconfig.json", content: `{ "compilerOptions": { "composite": true, "outDir": "dist" } }` }, - { path: "/packages/a/node_modules/b/index.ts", content: `export class B {}` } + { path: "/packages/a/node_modules/b/index.ts", content: `export class B {}` }, ]; const { projectService, session } = setup(files); @@ -358,7 +361,7 @@ describe("unittests:: tsserver:: autoImportProvider - monorepo", () => { for (const option of ts.sourceFileAffectingCompilerOptions) { assert( !ts.hasProperty(ts.server.AutoImportProviderProject.compilerOptionsOverrides, option.name), - `'${option.name}' may cause AutoImportProviderProject not to share source files with main program` + `'${option.name}' may cause AutoImportProviderProject not to share source files with main program`, ); } }); @@ -384,9 +387,9 @@ function setup(files: File[]) { arguments: { openFiles: [{ fileName: path, - content: newText - }] - } + content: newText, + }], + }, }); } @@ -397,8 +400,8 @@ function setup(files: File[]) { arguments: { file, line, - offset - } + offset, + }, }); } @@ -413,7 +416,7 @@ function setup(files: File[]) { arguments: { ...requestLocation, includeExternalModuleExports: true, - } + }, }); } } diff --git a/src/testRunner/unittests/tsserver/auxiliaryProject.ts b/src/testRunner/unittests/tsserver/auxiliaryProject.ts index 36f0e6cb45a69..65f99d06f0a29 100644 --- a/src/testRunner/unittests/tsserver/auxiliaryProject.ts +++ b/src/testRunner/unittests/tsserver/auxiliaryProject.ts @@ -12,15 +12,15 @@ import { const aTs: File = { path: "/a.ts", - content: `import { B } from "./b";` + content: `import { B } from "./b";`, }; const bDts: File = { path: "/b.d.ts", - content: `export declare class B {}` + content: `export declare class B {}`, }; const bJs: File = { path: "/b.js", - content: `export class B {}` + content: `export class B {}`, }; describe("unittests:: tsserver:: auxiliaryProject", () => { it("AuxiliaryProject does not remove scrips from InferredProject", () => { diff --git a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts index 250a9ffc94a8f..56ffdffa297bb 100644 --- a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts +++ b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts @@ -23,10 +23,10 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS fileExists = "fileExists", directoryExists = "directoryExists", getDirectories = "getDirectories", - readFile = "readFile" + readFile = "readFile", } enum CalledMapsWithFiveArgs { - readDirectory = "readDirectory" + readDirectory = "readDirectory", } type CalledMaps = CalledMapsWithSingleArg | CalledMapsWithFiveArgs; type CalledWithFiveArgs = [readonly string[], readonly string[], readonly string[], number]; @@ -36,7 +36,7 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS directoryExists: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.directoryExists), getDirectories: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.getDirectories), readFile: setCallsTrackingWithSingleArgFn(CalledMapsWithSingleArg.readFile), - readDirectory: setCallsTrackingWithFiveArgFn(CalledMapsWithFiveArgs.readDirectory) + readDirectory: setCallsTrackingWithFiveArgFn(CalledMapsWithFiveArgs.readDirectory), }; return logCacheAndClear; @@ -62,7 +62,7 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS } function logCacheEntry(logger: Logger, callback: CalledMaps) { - const result = Array.from<[string, (true | CalledWithFiveArgs)[]], { key: string, count: number }>(calledMaps[callback].entries(), ([key, arr]) => ({ key, count: arr.length })); + const result = Array.from<[string, (true | CalledWithFiveArgs)[]], { key: string; count: number; }>(calledMaps[callback].entries(), ([key, arr]) => ({ key, count: arr.length })); logger.info(`${callback}:: ${JSON.stringify(result)}`); calledMaps[callback].clear(); } @@ -89,12 +89,12 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS let rootContent = `import {x} from "f1"`; const root: File = { path: "/c/d/f0.ts", - content: rootContent + content: rootContent, }; const imported: File = { path: "/c/f1.ts", - content: `foo()` + content: `foo()`, }; const host = createServerHost([root, imported]); @@ -147,12 +147,12 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS it("loads missing files from disk", () => { const root: File = { path: "/users/username/projects/project/foo.ts", - content: `import {y} from "bar"` + content: `import {y} from "bar"`, }; const imported: File = { path: "/users/username/projects/project/bar.d.ts", - content: `export var y = 1` + content: `export var y = 1`, }; const host = createServerHost([root]); @@ -180,18 +180,18 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS content: ` import { Vessel } from '~/models/vessel'; const v = new Vessel(); - ` + `, }; const anotherModuleFile: File = { path: "/a/b/utils/db.ts", - content: "export class Bookshelf { }" + content: "export class Bookshelf { }", }; const moduleFile: File = { path: "/a/b/models/vessel.ts", content: ` import { Bookshelf } from '~/utils/db'; export class Vessel extends Bookshelf {} - ` + `, }; const tsconfigFile: File = { path: "/a/b/tsconfig.json", @@ -199,10 +199,10 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS compilerOptions: { target: "es6", module: "es6", - baseUrl: "./", // all paths are relative to the baseUrl + baseUrl: "./", // all paths are relative to the baseUrl paths: { - "~/*": ["*"] // resolve any `~/foo/bar` to `/foo/bar` - } + "~/*": ["*"], // resolve any `~/foo/bar` to `/foo/bar` + }, }, exclude: [ "api", @@ -211,9 +211,9 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS "public", "seeds", "sql_updates", - "tests.build" - ] - }) + "tests.build", + ], + }), }; const projectFiles = [clientFile, anotherModuleFile, moduleFile, tsconfigFile]; const host = createServerHost(projectFiles); @@ -228,8 +228,8 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS file: clientFile.path, position: clientFile.content.indexOf("/vessel") + 1, line: undefined!, // TODO: GH#18217 - offset: undefined! // TODO: GH#18217 - } + offset: undefined!, // TODO: GH#18217 + }, }); logCacheAndClear(session.logger); @@ -246,19 +246,19 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS const frontendDir = "/Users/someuser/work/applications/frontend"; const file1: File = { path: `${frontendDir}/src/app/utils/Analytic.ts`, - content: "export class SomeClass { };" + content: "export class SomeClass { };", }; const file2: File = { path: `${frontendDir}/src/app/redux/configureStore.ts`, - content: "export class configureStore { }" + content: "export class configureStore { }", }; const file3: File = { path: `${frontendDir}/src/app/utils/Cookie.ts`, - content: "export class Cookie { }" + content: "export class Cookie { }", }; const es2016LibFile: File = { path: "/a/lib/lib.es2016.full.d.ts", - content: libFile.content + content: libFile.content, }; const typeRoots = ["types", "node_modules/@types"]; const types = ["node", "jest"]; @@ -282,18 +282,18 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS baseUrl: ".", paths: { "*": [ - "types/*" - ] - } + "types/*", + ], + }, }, include: [ - "src/**/*" + "src/**/*", ], exclude: [ "node_modules", - "compiled" - ] - }) + "compiled", + ], + }), }; const projectFiles = [file1, file2, es2016LibFile, tsconfigFile]; const host = createServerHost(projectFiles, { useCaseSensitiveFileNames }); @@ -321,18 +321,18 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS const projectLocation = "/users/username/projects/proj"; const file1: File = { path: `${projectLocation}/foo/boo/app.ts`, - content: `import * as debug from "debug"` + content: `import * as debug from "debug"`, }; const file2: File = { path: `${projectLocation}/foo/boo/moo/app.ts`, - content: `import * as debug from "debug"` + content: `import * as debug from "debug"`, }; const tsconfig: File = { path: `${projectLocation}/tsconfig.json`, content: JSON.stringify({ files: ["foo/boo/app.ts", "foo/boo/moo/app.ts"], - moduleResolution: resolution - }) + moduleResolution: resolution, + }), }; const files = [file1, file2, tsconfig, libFile]; @@ -346,7 +346,7 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS const debugTypesFile: File = { path: `${projectLocation}/node_modules/debug/index.d.ts`, - content: "export {}" + content: "export {}", }; host.writeFile(debugTypesFile.path, debugTypesFile.content); host.runQueuedTimeoutCallbacks(); // Scheduled invalidation of resolutions @@ -374,11 +374,11 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS }; const app: File = getRootedFileOrFolder({ path: "/a/b/app.ts", - content: "import _ from 'lodash';" + content: "import _ from 'lodash';", }); const tsconfigJson: File = getRootedFileOrFolder({ path: "/a/b/tsconfig.json", - content: '{ "compilerOptions": { } }' + content: '{ "compilerOptions": { } }', }); const packageJson: File = getRootedFileOrFolder({ path: "/a/b/package.json", @@ -403,7 +403,7 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS "author": "", "license": "ISC" } -` +`, }); const host = createServerHost([app, libFile, tsconfigJson, packageJson]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -421,10 +421,18 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff" }, { path: "/a/b/node_modules/.staging/rxjs-22375c61" }, { path: "/a/b/node_modules/.staging/typescript-8493ea5d" }, - { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/package.json", content: "{\n \"name\": \"symbol-observable\",\n \"version\": \"1.0.4\",\n \"description\": \"Symbol.observable ponyfill\",\n \"license\": \"MIT\",\n \"repository\": \"blesh/symbol-observable\",\n \"author\": {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n \"engines\": {\n \"node\": \">=0.10.0\"\n },\n \"scripts\": {\n \"test\": \"npm run build && mocha && tsc ./ts-test/test.ts && node ./ts-test/test.js && check-es3-syntax -p lib/ --kill\",\n \"build\": \"babel es --out-dir lib\",\n \"prepublish\": \"npm test\"\n },\n \"files\": [\n \"" }, - { path: "/a/b/node_modules/.staging/lodash-b0733faa/package.json", content: "{\n \"name\": \"lodash\",\n \"version\": \"4.17.4\",\n \"description\": \"Lodash modular utilities.\",\n \"keywords\": \"modules, stdlib, util\",\n \"homepage\": \"https://lodash.com/\",\n \"repository\": \"lodash/lodash\",\n \"icon\": \"https://lodash.com/icon.svg\",\n \"license\": \"MIT\",\n \"main\": \"lodash.js\",\n \"author\": \"John-David Dalton (http://allyoucanleet.com/)\",\n \"contributors\": [\n \"John-David Dalton (http://allyoucanleet.com/)\",\n \"Mathias Bynens \",\n \"contributors\": [\n {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n {\n \"name\": \"Paul Taylor\",\n \"email\": \"paul.e.taylor@me.com\"\n },\n {\n \"name\": \"Jeff Cross\",\n \"email\": \"crossj@google.com\"\n },\n {\n \"name\": \"Matthew Podwysocki\",\n \"email\": \"matthewp@microsoft.com\"\n },\n {\n \"name\": \"OJ Kwon\",\n \"email\": \"kwon.ohjoong@gmail.com\"\n },\n {\n \"name\": \"Andre Staltz\",\n \"email\": \"andre@staltz.com\"\n }\n ],\n \"license\": \"Apache-2.0\",\n \"bugs\": {\n \"url\": \"https://github.com/ReactiveX/RxJS/issues\"\n },\n \"homepage\": \"https://github.com/ReactiveX/RxJS\",\n \"devDependencies\": {\n \"babel-polyfill\": \"^6.23.0\",\n \"benchmark\": \"^2.1.0\",\n \"benchpress\": \"2.0.0-beta.1\",\n \"chai\": \"^3.5.0\",\n \"color\": \"^0.11.1\",\n \"colors\": \"1.1.2\",\n \"commitizen\": \"^2.8.6\",\n \"coveralls\": \"^2.11.13\",\n \"cz-conventional-changelog\": \"^1.2.0\",\n \"danger\": \"^1.1.0\",\n \"doctoc\": \"^1.0.0\",\n \"escape-string-regexp\": \"^1.0.5 \",\n \"esdoc\": \"^0.4.7\",\n \"eslint\": \"^3.8.0\",\n \"fs-extra\": \"^2.1.2\",\n \"get-folder-size\": \"^1.0.0\",\n \"glob\": \"^7.0.3\",\n \"gm\": \"^1.22.0\",\n \"google-closure-compiler-js\": \"^20170218.0.0\",\n \"gzip-size\": \"^3.0.0\",\n \"http-server\": \"^0.9.0\",\n \"husky\": \"^0.13.3\",\n \"lint-staged\": \"3.2.5\",\n \"lodash\": \"^4.15.0\",\n \"madge\": \"^1.4.3\",\n \"markdown-doctest\": \"^0.9.1\",\n \"minimist\": \"^1.2.0\",\n \"mkdirp\": \"^0.5.1\",\n \"mocha\": \"^3.0.2\",\n \"mocha-in-sauce\": \"0.0.1\",\n \"npm-run-all\": \"^4.0.2\",\n \"npm-scripts-info\": \"^0.3.4\",\n \"nyc\": \"^10.2.0\",\n \"opn-cli\": \"^3.1.0\",\n \"platform\": \"^1.3.1\",\n \"promise\": \"^7.1.1\",\n \"protractor\": \"^3.1.1\",\n \"rollup\": \"0.36.3\",\n \"rollup-plugin-inject\": \"^2.0.0\",\n \"rollup-plugin-node-resolve\": \"^2.0.0\",\n \"rx\": \"latest\",\n \"rxjs\": \"latest\",\n \"shx\": \"^0.2.2\",\n \"sinon\": \"^2.1.0\",\n \"sinon-chai\": \"^2.9.0\",\n \"source-map-support\": \"^0.4.0\",\n \"tslib\": \"^1.5.0\",\n \"eslint\": \"^4.4.2\",\n \"typescript\": \"~2.0.6\",\n \"typings\": \"^2.0.0\",\n \"validate-commit-msg\": \"^2.14.0\",\n \"watch\": \"^1.0.1\",\n \"webpack\": \"^1.13.1\",\n \"xmlhttprequest\": \"1.8.0\"\n },\n \"engines\": {\n \"npm\": \">=2.0.0\"\n },\n \"typings\": \"Rx.d.ts\",\n \"dependencies\": {\n \"symbol-observable\": \"^1.0.1\"\n }\n}" }, - { path: "/a/b/node_modules/.staging/typescript-8493ea5d/package.json", content: "{\n \"name\": \"typescript\",\n \"author\": \"Microsoft Corp.\",\n \"homepage\": \"http://typescriptlang.org/\",\n \"version\": \"2.4.2\",\n \"license\": \"Apache-2.0\",\n \"description\": \"TypeScript is a language for application scale JavaScript development\",\n \"keywords\": [\n \"TypeScript\",\n \"Microsoft\",\n \"compiler\",\n \"language\",\n \"javascript\"\n ],\n \"bugs\": {\n \"url\": \"https://github.com/Microsoft/TypeScript/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Microsoft/TypeScript.git\"\n },\n \"main\": \"./lib/typescript.js\",\n \"typings\": \"./lib/typescript.d.ts\",\n \"bin\": {\n \"tsc\": \"./bin/tsc\",\n \"tsserver\": \"./bin/tsserver\"\n },\n \"engines\": {\n \"node\": \">=4.2.0\"\n },\n \"devDependencies\": {\n \"@types/browserify\": \"latest\",\n \"@types/chai\": \"latest\",\n \"@types/convert-source-map\": \"latest\",\n \"@types/del\": \"latest\",\n \"@types/glob\": \"latest\",\n \"@types/gulp\": \"latest\",\n \"@types/gulp-concat\": \"latest\",\n \"@types/gulp-help\": \"latest\",\n \"@types/gulp-newer\": \"latest\",\n \"@types/gulp-sourcemaps\": \"latest\",\n \"@types/merge2\": \"latest\",\n \"@types/minimatch\": \"latest\",\n \"@types/minimist\": \"latest\",\n \"@types/mkdirp\": \"latest\",\n \"@types/mocha\": \"latest\",\n \"@types/node\": \"latest\",\n \"@types/q\": \"latest\",\n \"@types/run-sequence\": \"latest\",\n \"@types/through2\": \"latest\",\n \"browserify\": \"latest\",\n \"chai\": \"latest\",\n \"convert-source-map\": \"latest\",\n \"del\": \"latest\",\n \"gulp\": \"latest\",\n \"gulp-clone\": \"latest\",\n \"gulp-concat\": \"latest\",\n \"gulp-help\": \"latest\",\n \"gulp-insert\": \"latest\",\n \"gulp-newer\": \"latest\",\n \"gulp-sourcemaps\": \"latest\",\n \"gulp-typescript\": \"latest\",\n \"into-stream\": \"latest\",\n \"istanbul\": \"latest\",\n \"jake\": \"latest\",\n \"merge2\": \"latest\",\n \"minimist\": \"latest\",\n \"mkdirp\": \"latest\",\n \"mocha\": \"latest\",\n \"mocha-fivemat-progress-reporter\": \"latest\",\n \"q\": \"latest\",\n \"run-sequence\": \"latest\",\n \"sorcery\": \"latest\",\n \"through2\": \"latest\",\n \"travis-fold\": \"latest\",\n \"ts-node\": \"latest\",\n \"eslint\": \"5.16.0\",\n \"typescript\": \"^2.4\"\n },\n \"scripts\": {\n \"pretest\": \"jake tests\",\n \"test\": \"jake runtests-parallel\",\n \"build\": \"npm run build:compiler && npm run build:tests\",\n \"build:compiler\": \"jake local\",\n \"build:tests\": \"jake tests\",\n \"start\": \"node lib/tsc\",\n \"clean\": \"jake clean\",\n \"gulp\": \"gulp\",\n \"jake\": \"jake\",\n \"lint\": \"jake lint\",\n \"setup-hooks\": \"node scripts/link-hooks.js\"\n },\n \"browser\": {\n \"buffer\": false,\n \"fs\": false,\n \"os\": false,\n \"path\": false\n }\n}" }, + { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/package.json", content: '{\n "name": "symbol-observable",\n "version": "1.0.4",\n "description": "Symbol.observable ponyfill",\n "license": "MIT",\n "repository": "blesh/symbol-observable",\n "author": {\n "name": "Ben Lesh",\n "email": "ben@benlesh.com"\n },\n "engines": {\n "node": ">=0.10.0"\n },\n "scripts": {\n "test": "npm run build && mocha && tsc ./ts-test/test.ts && node ./ts-test/test.js && check-es3-syntax -p lib/ --kill",\n "build": "babel es --out-dir lib",\n "prepublish": "npm test"\n },\n "files": [\n "' }, + { path: "/a/b/node_modules/.staging/lodash-b0733faa/package.json", content: '{\n "name": "lodash",\n "version": "4.17.4",\n "description": "Lodash modular utilities.",\n "keywords": "modules, stdlib, util",\n "homepage": "https://lodash.com/",\n "repository": "lodash/lodash",\n "icon": "https://lodash.com/icon.svg",\n "license": "MIT",\n "main": "lodash.js",\n "author": "John-David Dalton (http://allyoucanleet.com/)",\n "contributors": [\n "John-David Dalton (http://allyoucanleet.com/)",\n "Mathias Bynens ",\n "contributors": [\n {\n "name": "Ben Lesh",\n "email": "ben@benlesh.com"\n },\n {\n "name": "Paul Taylor",\n "email": "paul.e.taylor@me.com"\n },\n {\n "name": "Jeff Cross",\n "email": "crossj@google.com"\n },\n {\n "name": "Matthew Podwysocki",\n "email": "matthewp@microsoft.com"\n },\n {\n "name": "OJ Kwon",\n "email": "kwon.ohjoong@gmail.com"\n },\n {\n "name": "Andre Staltz",\n "email": "andre@staltz.com"\n }\n ],\n "license": "Apache-2.0",\n "bugs": {\n "url": "https://github.com/ReactiveX/RxJS/issues"\n },\n "homepage": "https://github.com/ReactiveX/RxJS",\n "devDependencies": {\n "babel-polyfill": "^6.23.0",\n "benchmark": "^2.1.0",\n "benchpress": "2.0.0-beta.1",\n "chai": "^3.5.0",\n "color": "^0.11.1",\n "colors": "1.1.2",\n "commitizen": "^2.8.6",\n "coveralls": "^2.11.13",\n "cz-conventional-changelog": "^1.2.0",\n "danger": "^1.1.0",\n "doctoc": "^1.0.0",\n "escape-string-regexp": "^1.0.5 ",\n "esdoc": "^0.4.7",\n "eslint": "^3.8.0",\n "fs-extra": "^2.1.2",\n "get-folder-size": "^1.0.0",\n "glob": "^7.0.3",\n "gm": "^1.22.0",\n "google-closure-compiler-js": "^20170218.0.0",\n "gzip-size": "^3.0.0",\n "http-server": "^0.9.0",\n "husky": "^0.13.3",\n "lint-staged": "3.2.5",\n "lodash": "^4.15.0",\n "madge": "^1.4.3",\n "markdown-doctest": "^0.9.1",\n "minimist": "^1.2.0",\n "mkdirp": "^0.5.1",\n "mocha": "^3.0.2",\n "mocha-in-sauce": "0.0.1",\n "npm-run-all": "^4.0.2",\n "npm-scripts-info": "^0.3.4",\n "nyc": "^10.2.0",\n "opn-cli": "^3.1.0",\n "platform": "^1.3.1",\n "promise": "^7.1.1",\n "protractor": "^3.1.1",\n "rollup": "0.36.3",\n "rollup-plugin-inject": "^2.0.0",\n "rollup-plugin-node-resolve": "^2.0.0",\n "rx": "latest",\n "rxjs": "latest",\n "shx": "^0.2.2",\n "sinon": "^2.1.0",\n "sinon-chai": "^2.9.0",\n "source-map-support": "^0.4.0",\n "tslib": "^1.5.0",\n "eslint": "^4.4.2",\n "typescript": "~2.0.6",\n "typings": "^2.0.0",\n "validate-commit-msg": "^2.14.0",\n "watch": "^1.0.1",\n "webpack": "^1.13.1",\n "xmlhttprequest": "1.8.0"\n },\n "engines": {\n "npm": ">=2.0.0"\n },\n "typings": "Rx.d.ts",\n "dependencies": {\n "symbol-observable": "^1.0.1"\n }\n}', + }, + { + path: "/a/b/node_modules/.staging/typescript-8493ea5d/package.json", + content: + '{\n "name": "typescript",\n "author": "Microsoft Corp.",\n "homepage": "http://typescriptlang.org/",\n "version": "2.4.2",\n "license": "Apache-2.0",\n "description": "TypeScript is a language for application scale JavaScript development",\n "keywords": [\n "TypeScript",\n "Microsoft",\n "compiler",\n "language",\n "javascript"\n ],\n "bugs": {\n "url": "https://github.com/Microsoft/TypeScript/issues"\n },\n "repository": {\n "type": "git",\n "url": "https://github.com/Microsoft/TypeScript.git"\n },\n "main": "./lib/typescript.js",\n "typings": "./lib/typescript.d.ts",\n "bin": {\n "tsc": "./bin/tsc",\n "tsserver": "./bin/tsserver"\n },\n "engines": {\n "node": ">=4.2.0"\n },\n "devDependencies": {\n "@types/browserify": "latest",\n "@types/chai": "latest",\n "@types/convert-source-map": "latest",\n "@types/del": "latest",\n "@types/glob": "latest",\n "@types/gulp": "latest",\n "@types/gulp-concat": "latest",\n "@types/gulp-help": "latest",\n "@types/gulp-newer": "latest",\n "@types/gulp-sourcemaps": "latest",\n "@types/merge2": "latest",\n "@types/minimatch": "latest",\n "@types/minimist": "latest",\n "@types/mkdirp": "latest",\n "@types/mocha": "latest",\n "@types/node": "latest",\n "@types/q": "latest",\n "@types/run-sequence": "latest",\n "@types/through2": "latest",\n "browserify": "latest",\n "chai": "latest",\n "convert-source-map": "latest",\n "del": "latest",\n "gulp": "latest",\n "gulp-clone": "latest",\n "gulp-concat": "latest",\n "gulp-help": "latest",\n "gulp-insert": "latest",\n "gulp-newer": "latest",\n "gulp-sourcemaps": "latest",\n "gulp-typescript": "latest",\n "into-stream": "latest",\n "istanbul": "latest",\n "jake": "latest",\n "merge2": "latest",\n "minimist": "latest",\n "mkdirp": "latest",\n "mocha": "latest",\n "mocha-fivemat-progress-reporter": "latest",\n "q": "latest",\n "run-sequence": "latest",\n "sorcery": "latest",\n "through2": "latest",\n "travis-fold": "latest",\n "ts-node": "latest",\n "eslint": "5.16.0",\n "typescript": "^2.4"\n },\n "scripts": {\n "pretest": "jake tests",\n "test": "jake runtests-parallel",\n "build": "npm run build:compiler && npm run build:tests",\n "build:compiler": "jake local",\n "build:tests": "jake tests",\n "start": "node lib/tsc",\n "clean": "jake clean",\n "gulp": "gulp",\n "jake": "jake",\n "lint": "jake lint",\n "setup-hooks": "node scripts/link-hooks.js"\n },\n "browser": {\n "buffer": false,\n "fs": false,\n "os": false,\n "path": false\n }\n}', + }, { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/index.js", content: "module.exports = require('./lib/index');\n" }, { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/index.d.ts", content: "declare const observableSymbol: symbol;\nexport default observableSymbol;\n" }, { path: "/a/b/node_modules/.staging/symbol-observable-24bcbbff/lib" }, @@ -435,9 +443,13 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS filesAndFoldersToAdd.push(...[ { path: "/a/b/node_modules/.staging/typescript-8493ea5d/lib" }, { path: "/a/b/node_modules/.staging/rxjs-22375c61/add/operator" }, - { path: "/a/b/node_modules/.staging/@types/lodash-e56c4fe7/package.json", content: "{\n \"name\": \"@types/lodash\",\n \"version\": \"4.14.74\",\n \"description\": \"TypeScript definitions for Lo-Dash\",\n \"license\": \"MIT\",\n \"contributors\": [\n {\n \"name\": \"Brian Zengel\",\n \"url\": \"https://github.com/bczengel\"\n },\n {\n \"name\": \"Ilya Mochalov\",\n \"url\": \"https://github.com/chrootsu\"\n },\n {\n \"name\": \"Stepan Mikhaylyuk\",\n \"url\": \"https://github.com/stepancar\"\n },\n {\n \"name\": \"Eric L Anderson\",\n \"url\": \"https://github.com/ericanderson\"\n },\n {\n \"name\": \"AJ Richardson\",\n \"url\": \"https://github.com/aj-r\"\n },\n {\n \"name\": \"Junyoung Clare Jang\",\n \"url\": \"https://github.com/ailrun\"\n }\n ],\n \"main\": \"\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://www.github.com/DefinitelyTyped/DefinitelyTyped.git\"\n },\n \"scripts\": {},\n \"dependencies\": {},\n \"typesPublisherContentHash\": \"12af578ffaf8d86d2df37e591857906a86b983fa9258414326544a0fe6af0de8\",\n \"typeScriptVersion\": \"2.2\"\n}" }, + { + path: "/a/b/node_modules/.staging/@types/lodash-e56c4fe7/package.json", + content: + '{\n "name": "@types/lodash",\n "version": "4.14.74",\n "description": "TypeScript definitions for Lo-Dash",\n "license": "MIT",\n "contributors": [\n {\n "name": "Brian Zengel",\n "url": "https://github.com/bczengel"\n },\n {\n "name": "Ilya Mochalov",\n "url": "https://github.com/chrootsu"\n },\n {\n "name": "Stepan Mikhaylyuk",\n "url": "https://github.com/stepancar"\n },\n {\n "name": "Eric L Anderson",\n "url": "https://github.com/ericanderson"\n },\n {\n "name": "AJ Richardson",\n "url": "https://github.com/aj-r"\n },\n {\n "name": "Junyoung Clare Jang",\n "url": "https://github.com/ailrun"\n }\n ],\n "main": "",\n "repository": {\n "type": "git",\n "url": "https://www.github.com/DefinitelyTyped/DefinitelyTyped.git"\n },\n "scripts": {},\n "dependencies": {},\n "typesPublisherContentHash": "12af578ffaf8d86d2df37e591857906a86b983fa9258414326544a0fe6af0de8",\n "typeScriptVersion": "2.2"\n}', + }, { path: "/a/b/node_modules/.staging/lodash-b0733faa/index.js", content: "module.exports = require('./lodash');" }, - { path: "/a/b/node_modules/.staging/typescript-8493ea5d/package.json.3017591594", content: "" } + { path: "/a/b/node_modules/.staging/typescript-8493ea5d/package.json.3017591594", content: "" }, ].map(getRootedFileOrFolder)); // Since we added/removed in .staging no timeout verifyAfterPartialOrCompleteNpmInstall(); @@ -451,7 +463,7 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS { path: "/a/b/node_modules/.staging/rxjs-22375c61/bundles" }, { path: "/a/b/node_modules/.staging/rxjs-22375c61/operator" }, { path: "/a/b/node_modules/.staging/rxjs-22375c61/src/add/observable/dom" }, - { path: "/a/b/node_modules/.staging/@types/lodash-e56c4fe7/index.d.ts", content: "\n// Stub for lodash\nexport = _;\nexport as namespace _;\ndeclare var _: _.LoDashStatic;\ndeclare namespace _ {\n interface LoDashStatic {\n someProp: string;\n }\n class SomeClass {\n someMethod(): void;\n }\n}" } + { path: "/a/b/node_modules/.staging/@types/lodash-e56c4fe7/index.d.ts", content: "\n// Stub for lodash\nexport = _;\nexport as namespace _;\ndeclare var _: _.LoDashStatic;\ndeclare namespace _ {\n interface LoDashStatic {\n someProp: string;\n }\n class SomeClass {\n someMethod(): void;\n }\n}" }, ].map(getRootedFileOrFolder)); verifyAfterPartialOrCompleteNpmInstall(); @@ -460,7 +472,11 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS { path: "/a/b/node_modules/.staging/rxjs-22375c61/src/util" }, { path: "/a/b/node_modules/.staging/rxjs-22375c61/symbol" }, { path: "/a/b/node_modules/.staging/rxjs-22375c61/testing" }, - { path: "/a/b/node_modules/.staging/rxjs-22375c61/package.json.2252192041", content: "{\n \"_args\": [\n [\n {\n \"raw\": \"rxjs@^5.4.2\",\n \"scope\": null,\n \"escapedName\": \"rxjs\",\n \"name\": \"rxjs\",\n \"rawSpec\": \"^5.4.2\",\n \"spec\": \">=5.4.2 <6.0.0\",\n \"type\": \"range\"\n },\n \"C:\\\\Users\\\\shkamat\\\\Desktop\\\\app\"\n ]\n ],\n \"_from\": \"rxjs@>=5.4.2 <6.0.0\",\n \"_id\": \"rxjs@5.4.3\",\n \"_inCache\": true,\n \"_location\": \"/rxjs\",\n \"_nodeVersion\": \"7.7.2\",\n \"_npmOperationalInternal\": {\n \"host\": \"s3://npm-registry-packages\",\n \"tmp\": \"tmp/rxjs-5.4.3.tgz_1502407898166_0.6800217325799167\"\n },\n \"_npmUser\": {\n \"name\": \"blesh\",\n \"email\": \"ben@benlesh.com\"\n },\n \"_npmVersion\": \"5.3.0\",\n \"_phantomChildren\": {},\n \"_requested\": {\n \"raw\": \"rxjs@^5.4.2\",\n \"scope\": null,\n \"escapedName\": \"rxjs\",\n \"name\": \"rxjs\",\n \"rawSpec\": \"^5.4.2\",\n \"spec\": \">=5.4.2 <6.0.0\",\n \"type\": \"range\"\n },\n \"_requiredBy\": [\n \"/\"\n ],\n \"_resolved\": \"https://registry.npmjs.org/rxjs/-/rxjs-5.4.3.tgz\",\n \"_shasum\": \"0758cddee6033d68e0fd53676f0f3596ce3d483f\",\n \"_shrinkwrap\": null,\n \"_spec\": \"rxjs@^5.4.2\",\n \"_where\": \"C:\\\\Users\\\\shkamat\\\\Desktop\\\\app\",\n \"author\": {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/ReactiveX/RxJS/issues\"\n },\n \"config\": {\n \"commitizen\": {\n \"path\": \"cz-conventional-changelog\"\n }\n },\n \"contributors\": [\n {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n {\n \"name\": \"Paul Taylor\",\n \"email\": \"paul.e.taylor@me.com\"\n },\n {\n \"name\": \"Jeff Cross\",\n \"email\": \"crossj@google.com\"\n },\n {\n \"name\": \"Matthew Podwysocki\",\n \"email\": \"matthewp@microsoft.com\"\n },\n {\n \"name\": \"OJ Kwon\",\n \"email\": \"kwon.ohjoong@gmail.com\"\n },\n {\n \"name\": \"Andre Staltz\",\n \"email\": \"andre@staltz.com\"\n }\n ],\n \"dependencies\": {\n \"symbol-observable\": \"^1.0.1\"\n },\n \"description\": \"Reactive Extensions for modern JavaScript\",\n \"devDependencies\": {\n \"babel-polyfill\": \"^6.23.0\",\n \"benchmark\": \"^2.1.0\",\n \"benchpress\": \"2.0.0-beta.1\",\n \"chai\": \"^3.5.0\",\n \"color\": \"^0.11.1\",\n \"colors\": \"1.1.2\",\n \"commitizen\": \"^2.8.6\",\n \"coveralls\": \"^2.11.13\",\n \"cz-conventional-changelog\": \"^1.2.0\",\n \"danger\": \"^1.1.0\",\n \"doctoc\": \"^1.0.0\",\n \"escape-string-regexp\": \"^1.0.5 \",\n \"esdoc\": \"^0.4.7\",\n \"eslint\": \"^3.8.0\",\n \"fs-extra\": \"^2.1.2\",\n \"get-folder-size\": \"^1.0.0\",\n \"glob\": \"^7.0.3\",\n \"gm\": \"^1.22.0\",\n \"google-closure-compiler-js\": \"^20170218.0.0\",\n \"gzip-size\": \"^3.0.0\",\n \"http-server\": \"^0.9.0\",\n \"husky\": \"^0.13.3\",\n \"lint-staged\": \"3.2.5\",\n \"lodash\": \"^4.15.0\",\n \"madge\": \"^1.4.3\",\n \"markdown-doctest\": \"^0.9.1\",\n \"minimist\": \"^1.2.0\",\n \"mkdirp\": \"^0.5.1\",\n \"mocha\": \"^3.0.2\",\n \"mocha-in-sauce\": \"0.0.1\",\n \"npm-run-all\": \"^4.0.2\",\n \"npm-scripts-info\": \"^0.3.4\",\n \"nyc\": \"^10.2.0\",\n \"opn-cli\": \"^3.1.0\",\n \"platform\": \"^1.3.1\",\n \"promise\": \"^7.1.1\",\n \"protractor\": \"^3.1.1\",\n \"rollup\": \"0.36.3\",\n \"rollup-plugin-inject\": \"^2.0.0\",\n \"rollup-plugin-node-resolve\": \"^2.0.0\",\n \"rx\": \"latest\",\n \"rxjs\": \"latest\",\n \"shx\": \"^0.2.2\",\n \"sinon\": \"^2.1.0\",\n \"sinon-chai\": \"^2.9.0\",\n \"source-map-support\": \"^0.4.0\",\n \"tslib\": \"^1.5.0\",\n \"eslint\": \"^5.16.0\",\n \"typescript\": \"~2.0.6\",\n \"typings\": \"^2.0.0\",\n \"validate-commit-msg\": \"^2.14.0\",\n \"watch\": \"^1.0.1\",\n \"webpack\": \"^1.13.1\",\n \"xmlhttprequest\": \"1.8.0\"\n },\n \"directories\": {},\n \"dist\": {\n \"integrity\": \"sha512-fSNi+y+P9ss+EZuV0GcIIqPUK07DEaMRUtLJvdcvMyFjc9dizuDjere+A4V7JrLGnm9iCc+nagV/4QdMTkqC4A==\",\n \"shasum\": \"0758cddee6033d68e0fd53676f0f3596ce3d483f\",\n \"tarball\": \"https://registry.npmjs.org/rxjs/-/rxjs-5.4.3.tgz\"\n },\n \"engines\": {\n \"npm\": \">=2.0.0\"\n },\n \"homepage\": \"https://github.com/ReactiveX/RxJS\",\n \"keywords\": [\n \"Rx\",\n \"RxJS\",\n \"ReactiveX\",\n \"ReactiveExtensions\",\n \"Streams\",\n \"Observables\",\n \"Observable\",\n \"Stream\",\n \"ES6\",\n \"ES2015\"\n ],\n \"license\": \"Apache-2.0\",\n \"lint-staged\": {\n \"*.@(js)\": [\n \"eslint --fix\",\n \"git add\"\n ],\n \"*.@(ts)\": [\n \"eslint -c .eslintrc --ext .ts . --fix\",\n \"git add\"\n ]\n },\n \"main\": \"Rx.js\",\n \"maintainers\": [\n {\n \"name\": \"blesh\",\n \"email\": \"ben@benlesh.com\"\n }\n ],\n \"name\": \"rxjs\",\n \"optionalDependencies\": {},\n \"readme\": \"ERROR: No README data found!\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+ssh://git@github.com/ReactiveX/RxJS.git\"\n },\n \"scripts-info\": {\n \"info\": \"List available script\",\n \"build_all\": \"Build all packages (ES6, CJS, UMD) and generate packages\",\n \"build_cjs\": \"Build CJS package with clean up existing build, copy source into dist\",\n \"build_es6\": \"Build ES6 package with clean up existing build, copy source into dist\",\n \"build_closure_core\": \"Minify Global core build using closure compiler\",\n \"build_global\": \"Build Global package, then minify build\",\n \"build_perf\": \"Build CJS & Global build, run macro performance test\",\n \"build_test\": \"Build CJS package & test spec, execute mocha test runner\",\n \"build_cover\": \"Run lint to current code, build CJS & test spec, execute test coverage\",\n \"build_docs\": \"Build ES6 & global package, create documentation using it\",\n \"build_spec\": \"Build test specs\",\n \"check_circular_dependencies\": \"Check codebase has circular dependencies\",\n \"clean_spec\": \"Clean up existing test spec build output\",\n \"clean_dist_cjs\": \"Clean up existing CJS package output\",\n \"clean_dist_es6\": \"Clean up existing ES6 package output\",\n \"clean_dist_global\": \"Clean up existing Global package output\",\n \"commit\": \"Run git commit wizard\",\n \"compile_dist_cjs\": \"Compile codebase into CJS module\",\n \"compile_module_es6\": \"Compile codebase into ES6\",\n \"cover\": \"Execute test coverage\",\n \"lint_perf\": \"Run lint against performance test suite\",\n \"lint_spec\": \"Run lint against test spec\",\n \"lint_src\": \"Run lint against source\",\n \"lint\": \"Run lint against everything\",\n \"perf\": \"Run macro performance benchmark\",\n \"perf_micro\": \"Run micro performance benchmark\",\n \"test_mocha\": \"Execute mocha test runner against existing test spec build\",\n \"test_browser\": \"Execute mocha test runner on browser against existing test spec build\",\n \"test\": \"Clean up existing test spec build, build test spec and execute mocha test runner\",\n \"tests2png\": \"Generate marble diagram image from test spec\",\n \"watch\": \"Watch codebase, trigger compile when source code changes\"\n },\n \"typings\": \"Rx.d.ts\",\n \"version\": \"5.4.3\"\n}\n" } + { + path: "/a/b/node_modules/.staging/rxjs-22375c61/package.json.2252192041", + content: + '{\n "_args": [\n [\n {\n "raw": "rxjs@^5.4.2",\n "scope": null,\n "escapedName": "rxjs",\n "name": "rxjs",\n "rawSpec": "^5.4.2",\n "spec": ">=5.4.2 <6.0.0",\n "type": "range"\n },\n "C:\\\\Users\\\\shkamat\\\\Desktop\\\\app"\n ]\n ],\n "_from": "rxjs@>=5.4.2 <6.0.0",\n "_id": "rxjs@5.4.3",\n "_inCache": true,\n "_location": "/rxjs",\n "_nodeVersion": "7.7.2",\n "_npmOperationalInternal": {\n "host": "s3://npm-registry-packages",\n "tmp": "tmp/rxjs-5.4.3.tgz_1502407898166_0.6800217325799167"\n },\n "_npmUser": {\n "name": "blesh",\n "email": "ben@benlesh.com"\n },\n "_npmVersion": "5.3.0",\n "_phantomChildren": {},\n "_requested": {\n "raw": "rxjs@^5.4.2",\n "scope": null,\n "escapedName": "rxjs",\n "name": "rxjs",\n "rawSpec": "^5.4.2",\n "spec": ">=5.4.2 <6.0.0",\n "type": "range"\n },\n "_requiredBy": [\n "/"\n ],\n "_resolved": "https://registry.npmjs.org/rxjs/-/rxjs-5.4.3.tgz",\n "_shasum": "0758cddee6033d68e0fd53676f0f3596ce3d483f",\n "_shrinkwrap": null,\n "_spec": "rxjs@^5.4.2",\n "_where": "C:\\\\Users\\\\shkamat\\\\Desktop\\\\app",\n "author": {\n "name": "Ben Lesh",\n "email": "ben@benlesh.com"\n },\n "bugs": {\n "url": "https://github.com/ReactiveX/RxJS/issues"\n },\n "config": {\n "commitizen": {\n "path": "cz-conventional-changelog"\n }\n },\n "contributors": [\n {\n "name": "Ben Lesh",\n "email": "ben@benlesh.com"\n },\n {\n "name": "Paul Taylor",\n "email": "paul.e.taylor@me.com"\n },\n {\n "name": "Jeff Cross",\n "email": "crossj@google.com"\n },\n {\n "name": "Matthew Podwysocki",\n "email": "matthewp@microsoft.com"\n },\n {\n "name": "OJ Kwon",\n "email": "kwon.ohjoong@gmail.com"\n },\n {\n "name": "Andre Staltz",\n "email": "andre@staltz.com"\n }\n ],\n "dependencies": {\n "symbol-observable": "^1.0.1"\n },\n "description": "Reactive Extensions for modern JavaScript",\n "devDependencies": {\n "babel-polyfill": "^6.23.0",\n "benchmark": "^2.1.0",\n "benchpress": "2.0.0-beta.1",\n "chai": "^3.5.0",\n "color": "^0.11.1",\n "colors": "1.1.2",\n "commitizen": "^2.8.6",\n "coveralls": "^2.11.13",\n "cz-conventional-changelog": "^1.2.0",\n "danger": "^1.1.0",\n "doctoc": "^1.0.0",\n "escape-string-regexp": "^1.0.5 ",\n "esdoc": "^0.4.7",\n "eslint": "^3.8.0",\n "fs-extra": "^2.1.2",\n "get-folder-size": "^1.0.0",\n "glob": "^7.0.3",\n "gm": "^1.22.0",\n "google-closure-compiler-js": "^20170218.0.0",\n "gzip-size": "^3.0.0",\n "http-server": "^0.9.0",\n "husky": "^0.13.3",\n "lint-staged": "3.2.5",\n "lodash": "^4.15.0",\n "madge": "^1.4.3",\n "markdown-doctest": "^0.9.1",\n "minimist": "^1.2.0",\n "mkdirp": "^0.5.1",\n "mocha": "^3.0.2",\n "mocha-in-sauce": "0.0.1",\n "npm-run-all": "^4.0.2",\n "npm-scripts-info": "^0.3.4",\n "nyc": "^10.2.0",\n "opn-cli": "^3.1.0",\n "platform": "^1.3.1",\n "promise": "^7.1.1",\n "protractor": "^3.1.1",\n "rollup": "0.36.3",\n "rollup-plugin-inject": "^2.0.0",\n "rollup-plugin-node-resolve": "^2.0.0",\n "rx": "latest",\n "rxjs": "latest",\n "shx": "^0.2.2",\n "sinon": "^2.1.0",\n "sinon-chai": "^2.9.0",\n "source-map-support": "^0.4.0",\n "tslib": "^1.5.0",\n "eslint": "^5.16.0",\n "typescript": "~2.0.6",\n "typings": "^2.0.0",\n "validate-commit-msg": "^2.14.0",\n "watch": "^1.0.1",\n "webpack": "^1.13.1",\n "xmlhttprequest": "1.8.0"\n },\n "directories": {},\n "dist": {\n "integrity": "sha512-fSNi+y+P9ss+EZuV0GcIIqPUK07DEaMRUtLJvdcvMyFjc9dizuDjere+A4V7JrLGnm9iCc+nagV/4QdMTkqC4A==",\n "shasum": "0758cddee6033d68e0fd53676f0f3596ce3d483f",\n "tarball": "https://registry.npmjs.org/rxjs/-/rxjs-5.4.3.tgz"\n },\n "engines": {\n "npm": ">=2.0.0"\n },\n "homepage": "https://github.com/ReactiveX/RxJS",\n "keywords": [\n "Rx",\n "RxJS",\n "ReactiveX",\n "ReactiveExtensions",\n "Streams",\n "Observables",\n "Observable",\n "Stream",\n "ES6",\n "ES2015"\n ],\n "license": "Apache-2.0",\n "lint-staged": {\n "*.@(js)": [\n "eslint --fix",\n "git add"\n ],\n "*.@(ts)": [\n "eslint -c .eslintrc --ext .ts . --fix",\n "git add"\n ]\n },\n "main": "Rx.js",\n "maintainers": [\n {\n "name": "blesh",\n "email": "ben@benlesh.com"\n }\n ],\n "name": "rxjs",\n "optionalDependencies": {},\n "readme": "ERROR: No README data found!",\n "repository": {\n "type": "git",\n "url": "git+ssh://git@github.com/ReactiveX/RxJS.git"\n },\n "scripts-info": {\n "info": "List available script",\n "build_all": "Build all packages (ES6, CJS, UMD) and generate packages",\n "build_cjs": "Build CJS package with clean up existing build, copy source into dist",\n "build_es6": "Build ES6 package with clean up existing build, copy source into dist",\n "build_closure_core": "Minify Global core build using closure compiler",\n "build_global": "Build Global package, then minify build",\n "build_perf": "Build CJS & Global build, run macro performance test",\n "build_test": "Build CJS package & test spec, execute mocha test runner",\n "build_cover": "Run lint to current code, build CJS & test spec, execute test coverage",\n "build_docs": "Build ES6 & global package, create documentation using it",\n "build_spec": "Build test specs",\n "check_circular_dependencies": "Check codebase has circular dependencies",\n "clean_spec": "Clean up existing test spec build output",\n "clean_dist_cjs": "Clean up existing CJS package output",\n "clean_dist_es6": "Clean up existing ES6 package output",\n "clean_dist_global": "Clean up existing Global package output",\n "commit": "Run git commit wizard",\n "compile_dist_cjs": "Compile codebase into CJS module",\n "compile_module_es6": "Compile codebase into ES6",\n "cover": "Execute test coverage",\n "lint_perf": "Run lint against performance test suite",\n "lint_spec": "Run lint against test spec",\n "lint_src": "Run lint against source",\n "lint": "Run lint against everything",\n "perf": "Run macro performance benchmark",\n "perf_micro": "Run micro performance benchmark",\n "test_mocha": "Execute mocha test runner against existing test spec build",\n "test_browser": "Execute mocha test runner on browser against existing test spec build",\n "test": "Clean up existing test spec build, build test spec and execute mocha test runner",\n "tests2png": "Generate marble diagram image from test spec",\n "watch": "Watch codebase, trigger compile when source code changes"\n },\n "typings": "Rx.d.ts",\n "version": "5.4.3"\n}\n', + }, ].map(getRootedFileOrFolder)); verifyAfterPartialOrCompleteNpmInstall(); @@ -475,7 +491,7 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS { path: "/a/b/node_modules/lodash" }, { path: "/a/b/node_modules/rxjs" }, { path: "/a/b/node_modules/typescript" }, - { path: "/a/b/node_modules/.bin" } + { path: "/a/b/node_modules/.bin" }, ].map(getRootedFileOrFolder)); // From the type root update verifyAfterPartialOrCompleteNpmInstall(); @@ -494,7 +510,7 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS baselineTsserverLogs( "cachingFileSystemInformation", `npm install works when ${timeoutDuringPartialInstallation ? "timeout occurs inbetween installation" : "timeout occurs after installation"}`, - projectService + projectService, ); function verifyAfterPartialOrCompleteNpmInstall() { @@ -521,11 +537,11 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS const projectLocation = "/user/username/folder/myproject"; const app: File = { path: `${projectLocation}/app.ts`, - content: `import * as debug from "debug"` + content: `import * as debug from "debug"`, }; const tsconfig: File = { path: `${projectLocation}/tsconfig.json`, - content: "" + content: "", }; const files = [app, tsconfig, libFile]; @@ -538,7 +554,7 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS const debugTypesFile: File = { path: `${projectLocation}/node_modules/@types/debug/index.d.ts`, - content: "export {}" + content: "export {}", }; // Do not invoke recursive directory watcher for anything other than node_module/@types const invoker = host.invokeFsWatchesRecursiveCallbacks; @@ -556,11 +572,11 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS it("when creating new file in symlinked folder", () => { const module1: File = { path: `/user/username/projects/myproject/client/folder1/module1.ts`, - content: `export class Module1Class { }` + content: `export class Module1Class { }`, }; const module2: File = { path: `/user/username/projects/myproject/folder2/module2.ts`, - content: `import * as M from "folder1/module1";` + content: `import * as M from "folder1/module1";`, }; const symlink: SymLink = { path: `/user/username/projects/myproject/client/linktofolder2`, @@ -573,8 +589,8 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS baseUrl: "client", paths: { "*": ["*"] }, }, - include: ["client/**/*", "folder2"] - }) + include: ["client/**/*", "folder2"], + }), }; const host = createServerHost([module1, module2, symlink, config, libFile]); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); diff --git a/src/testRunner/unittests/tsserver/cancellationToken.ts b/src/testRunner/unittests/tsserver/cancellationToken.ts index b095bd690de59..5fc573e00f3fb 100644 --- a/src/testRunner/unittests/tsserver/cancellationToken.ts +++ b/src/testRunner/unittests/tsserver/cancellationToken.ts @@ -6,7 +6,9 @@ import { TestServerCancellationToken, TestSessionRequest, } from "../helpers/tsserver"; -import { createServerHost } from "../helpers/virtualFileSystemWithWatch"; +import { + createServerHost, +} from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: tsserver:: cancellationToken", () => { // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test @@ -23,30 +25,30 @@ describe("unittests:: tsserver:: cancellationToken", () => { it("is attached to request", () => { const f1 = { path: "/a/b/app.ts", - content: "let xyz = 1;" + content: "let xyz = 1;", }; const host = createServerHost([f1]); const cancellationToken: ts.server.ServerCancellationToken = { isCancellationRequested: () => false, setRequest: requestId => session.logger.log(`ServerCancellationToken:: Cancellation Request id:: ${requestId}`), - resetRequest: ts.noop + resetRequest: ts.noop, }; const session = createSession(host, { cancellationToken, logger: createLoggerWithInMemoryLogs(host) }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Open, - arguments: { file: f1.path } + arguments: { file: f1.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Geterr, - arguments: { files: [f1.path], delay: 0 } + arguments: { files: [f1.path], delay: 0 }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DocumentHighlights, - arguments: { file: f1.path, line: 1, offset: 6, filesToSearch: [f1.path] } + arguments: { file: f1.path, line: 1, offset: 6, filesToSearch: [f1.path] }, }); host.runQueuedTimeoutCallbacks(); @@ -58,13 +60,13 @@ describe("unittests:: tsserver:: cancellationToken", () => { it("Geterr is cancellable", () => { const f1 = { path: "/a/app.ts", - content: "let x = 1" + content: "let x = 1", }; const config = { path: "/a/tsconfig.json", content: JSON.stringify({ - compilerOptions: {} - }) + compilerOptions: {}, + }), }; const host = createServerHost([f1, config]); @@ -79,12 +81,12 @@ describe("unittests:: tsserver:: cancellationToken", () => { { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Open, - arguments: { file: f1.path } + arguments: { file: f1.path }, }); // send geterr for missing file session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Geterr, - arguments: { files: ["/a/missing"], delay: 0 } + arguments: { files: ["/a/missing"], delay: 0 }, }); // Queued files host.runQueuedTimeoutCallbacks(); @@ -95,13 +97,13 @@ describe("unittests:: tsserver:: cancellationToken", () => { // send geterr for a valid file session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Geterr, - arguments: { files: [f1.path], delay: 0 } + arguments: { files: [f1.path], delay: 0 }, }); // run new request session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.ProjectInfo, - arguments: { file: f1.path, needFileNameList: false } + arguments: { file: f1.path, needFileNameList: false }, }); // cancel previously issued Geterr @@ -113,7 +115,7 @@ describe("unittests:: tsserver:: cancellationToken", () => { const getErrId = session.getNextSeq(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Geterr, - arguments: { files: [f1.path], delay: 0 } + arguments: { files: [f1.path], delay: 0 }, }); // run first step @@ -127,7 +129,7 @@ describe("unittests:: tsserver:: cancellationToken", () => { { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Geterr, - arguments: { files: [f1.path], delay: 0 } + arguments: { files: [f1.path], delay: 0 }, }); // run first step host.runQueuedTimeoutCallbacks(); @@ -139,13 +141,13 @@ describe("unittests:: tsserver:: cancellationToken", () => { { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Geterr, - arguments: { files: [f1.path], delay: 0 } + arguments: { files: [f1.path], delay: 0 }, }); // run first step host.runQueuedTimeoutCallbacks(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Geterr, - arguments: { files: [f1.path], delay: 0 } + arguments: { files: [f1.path], delay: 0 }, }); // make sure that getErr1 is completed } @@ -155,13 +157,13 @@ describe("unittests:: tsserver:: cancellationToken", () => { it("Lower priority tasks are cancellable", () => { const f1 = { path: "/a/app.ts", - content: `{ let x = 1; } var foo = "foo"; var bar = "bar"; var fooBar = "fooBar";` + content: `{ let x = 1; } var foo = "foo"; var bar = "bar"; var fooBar = "fooBar";`, }; const config = { path: "/a/tsconfig.json", content: JSON.stringify({ - compilerOptions: {} - }) + compilerOptions: {}, + }), }; const host = createServerHost([f1, config]); const logger = createLoggerWithInMemoryLogs(host); @@ -176,31 +178,31 @@ describe("unittests:: tsserver:: cancellationToken", () => { { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Open, - arguments: { file: f1.path } + arguments: { file: f1.path }, }); // send navbar request (normal priority) session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.NavBar, - arguments: { file: f1.path } + arguments: { file: f1.path }, }); // ensure the nav bar request can be canceled verifyExecuteCommandSeqIsCancellable({ command: ts.server.protocol.CommandTypes.NavBar, - arguments: { file: f1.path } + arguments: { file: f1.path }, }); // send outlining spans request (normal priority) session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetOutliningSpansFull, - arguments: { file: f1.path } + arguments: { file: f1.path }, }); // ensure the outlining spans request can be canceled verifyExecuteCommandSeqIsCancellable({ command: ts.server.protocol.CommandTypes.GetOutliningSpansFull, - arguments: { file: f1.path } + arguments: { file: f1.path }, }); } baselineTsserverLogs("cancellationT", "Lower priority tasks are cancellable", session); diff --git a/src/testRunner/unittests/tsserver/compileOnSave.ts b/src/testRunner/unittests/tsserver/compileOnSave.ts index 9e8f783d65186..0dcd6bb7dd740 100644 --- a/src/testRunner/unittests/tsserver/compileOnSave.ts +++ b/src/testRunner/unittests/tsserver/compileOnSave.ts @@ -21,34 +21,34 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { function files() { const moduleFile1: File = { path: "/a/b/moduleFile1.ts", - content: "export function Foo() { };" + content: "export function Foo() { };", }; const file1Consumer1: File = { path: "/a/b/file1Consumer1.ts", - content: `import {Foo} from "./moduleFile1"; export var y = 10;` + content: `import {Foo} from "./moduleFile1"; export var y = 10;`, }; const file1Consumer2: File = { path: "/a/b/file1Consumer2.ts", - content: `import {Foo} from "./moduleFile1"; let z = 10;` + content: `import {Foo} from "./moduleFile1"; let z = 10;`, }; const moduleFile2: File = { path: "/a/b/moduleFile2.ts", - content: `export var Foo4 = 10;` + content: `export var Foo4 = 10;`, }; const globalFile3: File = { path: "/a/b/globalFile3.ts", - content: `interface GlobalFoo { age: number }` + content: `interface GlobalFoo { age: number }`, }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "compileOnSave": true - }` + }`, }; return { moduleFile1, file1Consumer1, file1Consumer2, moduleFile2, globalFile3, configFile }; } @@ -63,7 +63,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { // Send an initial compileOnSave request session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Change, @@ -73,12 +73,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `export var T: number;` - } + insertString: `export var T: number;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); // Change the content of file1 to `export var T: number;export function Foo() { console.log('hi'); };` @@ -90,12 +90,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 46, endLine: 1, endOffset: 46, - insertString: `console.log('hi');` - } + insertString: `console.log('hi');`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects module shape changed", session); }); @@ -110,7 +110,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { // Send an initial compileOnSave request session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); // Change file2 content to `let y = Foo();` @@ -122,8 +122,8 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 28, - insertString: "" - } + insertString: "", + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Change, @@ -133,12 +133,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `export var T: number;` - } + insertString: `export var T: number;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); // Add the import statements back to file2 @@ -150,8 +150,8 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `import {Foo} from "./moduleFile1";` - } + insertString: `import {Foo} from "./moduleFile1";`, + }, }); // Change the content of file1 to `export var T2: string;export var T: number;export function Foo() { };` @@ -163,12 +163,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `export var T2: string;` - } + insertString: `export var T2: string;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects uptodate with reference map changes", session); }); @@ -183,7 +183,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { // Send an initial compileOnSave request session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); host.writeFile(file1Consumer1.path, `let y = 10;`); @@ -196,12 +196,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `export var T: number;` - } + insertString: `export var T: number;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects uptodate with changes in non open files", session); }); @@ -214,7 +214,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([moduleFile1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); session.executeCommandSeq({ @@ -225,14 +225,14 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `export var T: number;` - } + insertString: `export var T: number;`, + }, }); // Delete file1Consumer2 host.deleteFile(file1Consumer2.path); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects uptodate with deleted files", session); }); @@ -245,12 +245,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([moduleFile1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); const file1Consumer3: File = { path: "/a/b/file1Consumer3.ts", - content: `import {Foo} from "./moduleFile1"; let y = Foo();` + content: `import {Foo} from "./moduleFile1"; let y = Foo();`, }; host.writeFile(file1Consumer3.path, file1Consumer3.content); host.runQueuedTimeoutCallbacks(); @@ -262,12 +262,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `export var T: number;` - } + insertString: `export var T: number;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects uptodate with new files", session); }); @@ -275,12 +275,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { it("should detect changes in non-root files", () => { const moduleFile1: File = { path: "/a/b/moduleFile1.ts", - content: "export function Foo() { };" + content: "export function Foo() { };", }; const file1Consumer1: File = { path: "/a/b/file1Consumer1.ts", - content: `import {Foo} from "./moduleFile1"; let y = Foo();` + content: `import {Foo} from "./moduleFile1"; let y = Foo();`, }; const configFile: File = { @@ -288,7 +288,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { content: `{ "compileOnSave": true, "files": ["${file1Consumer1.path}"] - }` + }`, }; const host = createServerHost([moduleFile1, file1Consumer1, configFile, libFile]); @@ -297,7 +297,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([moduleFile1, file1Consumer1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); // change file1 shape now, and verify both files are affected @@ -309,12 +309,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `export var T: number;` - } + insertString: `export var T: number;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); // change file1 internal, and verify only file1 is affected @@ -326,12 +326,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `var T1: number;` - } + insertString: `var T1: number;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects detect changes in non-root files", session); }); @@ -352,12 +352,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `var T2: string;` - } + insertString: `var T2: string;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: globalFile3.path } + arguments: { file: globalFile3.path }, }); baselineTsserverLogs("compileOnSave", "configProjects global file shape changed", session); }); @@ -366,7 +366,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { const { moduleFile1, file1Consumer1, file1Consumer2 } = files(); const configFile: File = { path: "/a/b/tsconfig.json", - content: `{}` + content: `{}`, }; const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, configFile, libFile]); @@ -374,7 +374,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([moduleFile1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects compileOnSave disabled", session); }); @@ -388,7 +388,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { "compilerOptions": { "noEmit": true } - }` + }`, }; const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, configFile, libFile]); @@ -396,7 +396,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([moduleFile1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects noEmit", session); }); @@ -407,14 +407,14 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { path: "/a/b/tsconfig.json", content: `{ "extends": "/a/tsconfig.json" - }` + }`, }; const configFile2: File = { path: "/a/tsconfig.json", content: `{ "compileOnSave": true - }` + }`, }; const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, configFile2, configFile, libFile]); @@ -423,7 +423,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([moduleFile1, file1Consumer1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects compileOnSave in base tsconfig", session); }); @@ -437,7 +437,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { "compilerOptions": { "isolatedModules": true } - }` + }`, }; const host = createServerHost([moduleFile1, file1Consumer1, configFile, libFile]); @@ -452,12 +452,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 27, endLine: 1, endOffset: 27, - insertString: `Point,` - } + insertString: `Point,`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects isolatedModules", session); }); @@ -472,7 +472,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { "module": "system", "outFile": "/a/b/out.js" } - }` + }`, }; const host = createServerHost([moduleFile1, file1Consumer1, configFile, libFile]); @@ -487,12 +487,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 27, endLine: 1, endOffset: 27, - insertString: `Point,` - } + insertString: `Point,`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects outFile", session); }); @@ -501,7 +501,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { const { moduleFile1, file1Consumer1, globalFile3, configFile } = files(); const file1Consumer1Consumer1: File = { path: "/a/b/file1Consumer1Consumer1.ts", - content: `import {y} from "./file1Consumer1";` + content: `import {y} from "./file1Consumer1";`, }; const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer1Consumer1, globalFile3, configFile, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -509,7 +509,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([moduleFile1, file1Consumer1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); session.executeCommandSeq({ @@ -520,8 +520,8 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 1, endOffset: 1, - insertString: `export var T: number;` - } + insertString: `export var T: number;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Change, @@ -531,12 +531,12 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { offset: 1, endLine: 2, endOffset: 1, - insertString: `export var T: number;` - } + insertString: `export var T: number;`, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path, projectFileName: configFile.path } + arguments: { file: moduleFile1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "configProjects cascaded affected file list", session); }); @@ -547,13 +547,13 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { path: "/a/b/file1.ts", content: ` /// - export var t1 = 10;` + export var t1 = 10;`, }; const file2: File = { path: "/a/b/file2.ts", content: ` /// - export var t2 = 10;` + export var t2 = 10;`, }; const host = createServerHost([file1, file2, configFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -561,7 +561,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([file1, file2], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); baselineTsserverLogs("compileOnSave", "configProjects circular references", session); }); @@ -579,7 +579,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([file1, file2, file3], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); baselineTsserverLogs("compileOnSave", "configProjects all projects without projectPath", session); }); @@ -590,7 +590,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { path: "/a/b/referenceFile1.ts", content: ` /// - export var x = Foo();` + export var x = Foo();`, }; const host = createServerHost([moduleFile1, referenceFile1, configFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -600,11 +600,11 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: referenceFile1.path } + arguments: { file: referenceFile1.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: moduleFile1.path } + arguments: { file: moduleFile1.path }, }); baselineTsserverLogs("compileOnSave", "configProjects removed code", session); }); @@ -615,7 +615,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { path: "/a/b/referenceFile1.ts", content: ` /// - export var x = Foo();` + export var x = Foo();`, }; const host = createServerHost([referenceFile1, configFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -623,7 +623,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([referenceFile1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: referenceFile1.path } + arguments: { file: referenceFile1.path }, }); baselineTsserverLogs("compileOnSave", "configProjects non existing code", session); }); @@ -634,18 +634,18 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { it(subScenario, () => { const dtsFile = { path: "/a/runtime/a.d.ts", - content: dtsFileContents + content: dtsFileContents, }; const f2 = { path: "/a/b.ts", - content: tsFileContents + content: tsFileContents, }; const config = { path: "/a/tsconfig.json", content: JSON.stringify({ compilerOptions: opts, - compileOnSave: true - }) + compileOnSave: true, + }), }; const host = createServerHost([dtsFile, f2, config]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -653,11 +653,11 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { openFilesForSession([f2], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dtsFile.path } + arguments: { file: dtsFile.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: f2.path } + arguments: { file: f2.path }, }); baselineTsserverLogs("compileOnSave", subScenario, session); }); @@ -673,7 +673,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { testDTS( "dtsFileChange in module file", /*dtsFileContents*/ "export const x: string;", - /*tsFileContents*/ "import { x } from './runtime/a;", + /*tsFileContents*/ "import { x } from './runtime/a;", /*opts*/ {}, ); @@ -704,25 +704,25 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { it(subScenario, () => { const f1 = { path: "/a/a.ts", - content: "let x = 1" + content: "let x = 1", }; const f2 = { path: "/a/b.ts", - content: "let y = 1" + content: "let y = 1", }; const config = { path: "/a/tsconfig.json", content: JSON.stringify({ compilerOptions: opts, - compileOnSave: true - }) + compileOnSave: true, + }), }; const host = createServerHost([f1, f2, config]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); openFilesForSession([f1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: f1.path } + arguments: { file: f1.path }, }); baselineTsserverLogs("compileOnSave", subScenario, session); }); @@ -735,7 +735,7 @@ describe("unittests:: tsserver:: compileOnSave:: affected list", () => { describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { it("should respect line endings", () => { - const logger = createLoggerWithInMemoryLogs(/*host*/ undefined!); //special handling + const logger = createLoggerWithInMemoryLogs(/*host*/ undefined!); // special handling test("\n", logger); test("\r\n", logger); baselineTsserverLogs("compileOnSave", "line endings", { logger }); @@ -745,7 +745,7 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { const path = "/a/app"; const f = { path: path + ts.Extension.Ts, - content: lines.join(newLine) + content: lines.join(newLine), }; const host = createServerHost([f], { newLine }); logger.host = host; @@ -754,7 +754,7 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { openFilesForSession([f], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: f.path } + arguments: { file: f.path }, }); return logger; } @@ -763,15 +763,15 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { it("should emit specified file", () => { const file1 = { path: "/a/b/f1.ts", - content: `export function Foo() { return 10; }` + content: `export function Foo() { return 10; }`, }; const file2 = { path: "/a/b/f2.ts", - content: `import {Foo} from "./f1"; let y = Foo();` + content: `import {Foo} from "./f1"; let y = Foo();`, }; const configFile = { path: "/a/b/tsconfig.json", - content: `{}` + content: `{}`, }; const host = createServerHost([file1, file2, configFile, libFile], { newLine: "\r\n" }); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -779,7 +779,7 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { openFilesForSession([file1, file2], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: file1.path, projectFileName: configFile.path } + arguments: { file: file1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("compileOnSave", "emit specified file", session); @@ -788,16 +788,16 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { it("shoud not emit js files in external projects", () => { const file1 = { path: "/a/b/file1.ts", - content: "consonle.log('file1');" + content: "consonle.log('file1');", }; // file2 has errors. The emitting should not be blocked. const file2 = { path: "/a/b/file2.js", - content: "console.log'file2');" + content: "console.log'file2');", }; const file3 = { path: "/a/b/file3.js", - content: "console.log('file3');" + content: "console.log('file3');", }; const externalProjectName = "/a/b/externalproject"; const host = createServerHost([file1, file2, file3, libFile]); @@ -807,14 +807,14 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { options: { allowJs: true, outFile: "dist.js", - compileOnSave: true + compileOnSave: true, }, - projectFileName: externalProjectName + projectFileName: externalProjectName, }, session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); baselineTsserverLogs("compileOnSave", "should not emit js files in external projects", session); @@ -824,7 +824,7 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { const inputFileName = "Foo.ts"; const file1 = { path: `/root/TypeScriptProject3/TypeScriptProject3/${inputFileName}`, - content: "consonle.log('file1');" + content: "consonle.log('file1');", }; const externalProjectName = "/root/TypeScriptProject3/TypeScriptProject3/TypeScriptProject3.csproj"; const host = createServerHost([file1, libFile]); @@ -834,13 +834,13 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { options: { outFile: "bar.js", sourceMap: true, - compileOnSave: true + compileOnSave: true, }, - projectFileName: externalProjectName + projectFileName: externalProjectName, }, session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); baselineTsserverLogs("compileOnSave", "use projectRoot as current directory", session); }); @@ -866,16 +866,16 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { noEmitOnError: true, declaration: true, }, - exclude: ["node_modules"] - }) + exclude: ["node_modules"], + }), }; const file1: File = { path: `/user/username/projects/myproject/file1.ts`, - content: "const x = 1;" + content: "const x = 1;", }; const file2: File = { path: `/user/username/projects/myproject/file2.ts`, - content: "const y = 2;" + content: "const y = 2;", }; const host = createServerHost([file1, file2, config, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -883,15 +883,15 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: file1.path, richResponse } + arguments: { file: file1.path, richResponse }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: file2.path, richResponse } + arguments: { file: file2.path, richResponse }, }); baselineTsserverLogs("compileOnSave", `emit with richRepsonse as ${richResponse}`, session); } @@ -921,31 +921,31 @@ describe("unittests:: tsserver:: compileOnSave:: EmitFile test", () => { compileOnSave: true, compilerOptions: { declaration, - module: hasModule ? undefined : "none" + module: hasModule ? undefined : "none", }, - }) + }), }; const file1: File = { path: `/user/username/projects/myproject/file1.ts`, content: `const x = 1; function foo() { return "hello"; -}` +}`, }; const file2: File = { path: `/user/username/projects/myproject/file2.ts`, content: `const y = 2; function bar() { return "world"; -}` +}`, }; const file3: File = { path: `/user/username/projects/myproject/file3.ts`, - content: "const xy = 3;" + content: "const xy = 3;", }; const module: File = { path: `/user/username/projects/myproject/module.ts`, - content: "export const xyz = 4;" + content: "export const xyz = 4;", }; const files = [file1, file2, file3, ...(hasModule ? [module] : ts.emptyArray)]; const host = createServerHost([...files, config, libFile]); @@ -954,7 +954,7 @@ function bar() { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); verifyFileSave(file1); @@ -974,7 +974,7 @@ function bar() { function verifyFileSave(file: File) { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: file.path } + arguments: { file: file.path }, }); } @@ -987,14 +987,14 @@ function bar() { fileName: file.path, textChanges: [{ newText, - ...protocolTextSpanFromSubstring(file.content, oldText) - }] - }] - } + ...protocolTextSpanFromSubstring(file.content, oldText), + }], + }], + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: file.path } + arguments: { file: file.path }, }); file.content = file.content.replace(oldText, newText); verifyFileSave(file); @@ -1013,8 +1013,8 @@ describe("unittests:: tsserver:: compileOnSave:: CompileOnSaveAffectedFileListRe offset: 1, endLine: 1, endOffset: 1, - insertString: "let k = 1" - } + insertString: "let k = 1", + }, }); } @@ -1027,31 +1027,31 @@ describe("unittests:: tsserver:: compileOnSave:: CompileOnSaveAffectedFileListRe it(subScenario, () => { const core: File = { path: `/user/username/projects/myproject/core/core.ts`, - content: "let z = 10;" + content: "let z = 10;", }; const app1: File = { path: `/user/username/projects/myproject/app1/app.ts`, - content: "let x = 10;" + content: "let x = 10;", }; const app2: File = { path: `/user/username/projects/myproject/app2/app.ts`, - content: "let y = 10;" + content: "let y = 10;", }; const app1Config: File = { path: `/user/username/projects/myproject/app1/tsconfig.json`, content: JSON.stringify({ files: ["app.ts", "../core/core.ts"], compilerOptions: { outFile: "build/output.js" }, - compileOnSave: true - }) + compileOnSave: true, + }), }; const app2Config: File = { path: `/user/username/projects/myproject/app2/tsconfig.json`, content: JSON.stringify({ files: ["app.ts", "../core/core.ts"], compilerOptions: { outFile: "build/output.js" }, - compileOnSave: true - }) + compileOnSave: true, + }), }; const files = [libFile, core, app1, app2, app1Config, app2Config]; const host = createServerHost(files); @@ -1062,7 +1062,7 @@ describe("unittests:: tsserver:: compileOnSave:: CompileOnSaveAffectedFileListRe logDirtyOfProjects(session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: commandArgs + arguments: commandArgs, }); logDirtyOfProjects(session); baselineTsserverLogs("compileOnSave", subScenario, session); @@ -1070,7 +1070,7 @@ describe("unittests:: tsserver:: compileOnSave:: CompileOnSaveAffectedFileListRe } verify("CompileOnSaveAffectedFileListRequest when projectFile is specified", { file: `/user/username/projects/myproject/core/core.ts`, - projectFileName: `/user/username/projects/myproject/app1/tsconfig.json` + projectFileName: `/user/username/projects/myproject/app1/tsconfig.json`, }); verify("CompileOnSaveAffectedFileListRequest when projectFile is not specified", { file: `/user/username/projects/myproject/core/core.ts`, diff --git a/src/testRunner/unittests/tsserver/completions.ts b/src/testRunner/unittests/tsserver/completions.ts index e385dad6c06e6..01f6415a0cb8a 100644 --- a/src/testRunner/unittests/tsserver/completions.ts +++ b/src/testRunner/unittests/tsserver/completions.ts @@ -43,7 +43,7 @@ describe("unittests:: tsserver:: completions", () => { ...requestLocation, includeExternalModuleExports: true, prefix: "foo", - } + }, }).response as ts.server.protocol.CompletionInfo; const exportMapKey = (response?.entries[0].data as any)?.exportMapKey; session.executeCommandSeq({ @@ -51,7 +51,7 @@ describe("unittests:: tsserver:: completions", () => { arguments: { ...requestLocation, entryNames: [{ name: "foo", source: "/a", data: { exportName: "foo", fileName: "/a.ts", exportMapKey } }], - } + }, }); interface CompletionDetailsFullRequest extends ts.server.protocol.FileLocationRequest { @@ -63,7 +63,7 @@ describe("unittests:: tsserver:: completions", () => { arguments: { ...requestLocation, entryNames: [{ name: "foo", source: "/a", data: { exportName: "foo", fileName: "/a.ts", exportMapKey } }], - } + }, }); baselineTsserverLogs("completions", "works", session); }); @@ -78,8 +78,8 @@ describe("unittests:: tsserver:: completions", () => { dependencies: { "react": "^16.12.0", "react-router-dom": "^5.1.2", - } - }) + }, + }), }; const appFile: File = { path: `${projectRoot}/src/app.js`, @@ -87,7 +87,7 @@ describe("unittests:: tsserver:: completions", () => { import { BrowserRouter as Router, } from "react-router-dom"; -` +`, }; const localNodeModules = `${projectRoot}/node_modules`; const localAtTypes = `${localNodeModules}/@types`; @@ -96,30 +96,30 @@ import { content: JSON.stringify({ name: "@types/react", version: "16.9.14", - }) + }), }; const localReact: File = { path: `${localAtTypes}/react/index.d.ts`, content: `import * as PropTypes from 'prop-types'; -` +`, }; const localReactRouterDomPackage: File = { path: `${localNodeModules}/react-router-dom/package.json`, content: JSON.stringify({ name: "react-router-dom", version: "5.1.2", - }) + }), }; const localReactRouterDom: File = { path: `${localNodeModules}/react-router-dom/index.js`, - content: `export function foo() {}` + content: `export function foo() {}`, }; const localPropTypesPackage: File = { path: `${localAtTypes}/prop-types/package.json`, content: JSON.stringify({ name: "@types/prop-types", version: "15.7.3", - }) + }), }; const localPropTypes: File = { path: `${localAtTypes}/prop-types/index.d.ts`, @@ -127,7 +127,7 @@ import { | string | ((props: any, context?: any) => any) | (new (props: any, context?: any) => any); -` +`, }; const globalCacheLocation = `c:/typescript`; @@ -137,7 +137,7 @@ import { content: JSON.stringify({ name: "@types/react-router-dom", version: "5.1.2", - }) + }), }; const globalReactRouterDom: File = { path: `${globalAtTypes}/react-router-dom/index.d.ts`, @@ -147,15 +147,15 @@ export interface BrowserRouterProps { getUserConfirmation?: ((message: string, callback: (ok: boolean) => void) => void); forceRefresh?: boolean; keyLength?: number; -}` +}`, }; const globalReactPackage: File = { path: `${globalAtTypes}/react/package.json`, - content: localReactPackage.content + content: localReactPackage.content, }; const globalReact: File = { path: `${globalAtTypes}/react/index.d.ts`, - content: localReact.content + content: localReact.content, }; const filesInProject = [ @@ -167,9 +167,11 @@ export interface BrowserRouterProps { ]; const files = [ ...filesInProject, - appPackage, libFile, + appPackage, + libFile, localReactPackage, - localReactRouterDomPackage, localReactRouterDom, + localReactRouterDomPackage, + localReactRouterDom, localPropTypesPackage, globalReactRouterDomPackage, globalReactPackage, @@ -189,8 +191,8 @@ export interface BrowserRouterProps { line: 5, offset: 1, includeExternalModuleExports: true, - includeInsertTextCompletions: true - } + includeInsertTextCompletions: true, + }, }); baselineTsserverLogs("completions", "works when files are included from two different drives of windows", session); }); diff --git a/src/testRunner/unittests/tsserver/completionsIncomplete.ts b/src/testRunner/unittests/tsserver/completionsIncomplete.ts index ad52b6ebe3c16..e98ffd9b7742c 100644 --- a/src/testRunner/unittests/tsserver/completionsIncomplete.ts +++ b/src/testRunner/unittests/tsserver/completionsIncomplete.ts @@ -18,10 +18,12 @@ function createExportingModuleFile(path: string, exportPrefix: string, exportCou } function createExportingModuleFiles(pathPrefix: string, fileCount: number, exportCount: number, getExportPrefix: (fileIndex: number) => string): File[] { - return ts.arrayOf(fileCount, fileIndex => createExportingModuleFile( - `${pathPrefix}_${fileIndex}.ts`, - getExportPrefix(fileIndex), - exportCount)); + return ts.arrayOf(fileCount, fileIndex => + createExportingModuleFile( + `${pathPrefix}_${fileIndex}.ts`, + getExportPrefix(fileIndex), + exportCount, + )); } function createNodeModulesPackage(packageName: string, fileCount: number, exportCount: number, getExportPrefix: (fileIndex: number) => string): File[] { @@ -43,12 +45,12 @@ function createNodeModulesPackage(packageName: string, fileCount: number, export const indexFile: File = { path: "/index.ts", - content: "" + content: "", }; const tsconfigFile: File = { path: "/tsconfig.json", - content: `{ "compilerOptions": { "module": "commonjs" } }` + content: `{ "compilerOptions": { "module": "commonjs" } }`, }; const packageJsonFile: File = { @@ -133,7 +135,8 @@ describe("unittests:: tsserver:: completionsIncomplete", () => { assert.lengthOf(completions.entries.filter(entry => (entry.data as any)?.moduleSpecifier?.startsWith("dep-a")), 50); assertCompletionDetailsOk( indexFile.path, - completions.entries.find(entry => (entry.data as any)?.moduleSpecifier?.startsWith("dep-a"))!); + completions.entries.find(entry => (entry.data as any)?.moduleSpecifier?.startsWith("dep-a"))!, + ); }); baselineTsserverLogs("completionsIncomplete", "works with PackageJsonAutoImportProvider", session); }); @@ -176,8 +179,8 @@ function setup(files: File[]) { includeCompletionsWithInsertText: true, includeCompletionsForImportStatements: true, includePackageJsonAutoImports: "auto", - } - } + }, + }, }); return { host, session, projectService, typeToTriggerCompletions, assertCompletionDetailsOk }; @@ -213,7 +216,7 @@ function setup(files: File[]) { triggerKind: isIncompleteContinuation ? ts.server.protocol.CompletionTriggerKind.TriggerForIncompleteCompletions : undefined, - } + }, }).response as ts.server.protocol.CompletionInfo; cb?.(ts.Debug.checkDefined(response)); @@ -268,8 +271,8 @@ function setup(files: File[]) { name: entry.name, source: entry.source, data: entry.data, - }] - } + }], + }, }).response as ts.server.protocol.CompletionEntryDetails[]; assert(details[0]); diff --git a/src/testRunner/unittests/tsserver/configFileSearch.ts b/src/testRunner/unittests/tsserver/configFileSearch.ts index 17682e3042056..e250ae54fa965 100644 --- a/src/testRunner/unittests/tsserver/configFileSearch.ts +++ b/src/testRunner/unittests/tsserver/configFileSearch.ts @@ -13,11 +13,11 @@ describe("unittests:: tsserver:: configFileSearch:: searching for config file", it("should stop at projectRootPath if given", () => { const f1 = { path: "/a/file1.ts", - content: "" + content: "", }; const configFile = { path: "/tsconfig.json", - content: "{}" + content: "{}", }; const host = createServerHost([f1, configFile]); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -33,15 +33,15 @@ describe("unittests:: tsserver:: configFileSearch:: searching for config file", const configFileLocation = `${projectDir}/src`; const f1 = { path: `${configFileLocation}/file1.ts`, - content: "" + content: "", }; const configFile = { path: `${configFileLocation}/tsconfig.json`, - content: "{}" + content: "{}", }; const configFile2 = { path: "/a/b/projects/tsconfig.json", - content: "{}" + content: "{}", }; const host = createServerHost([f1, libFile, configFile, configFile2]); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -58,15 +58,15 @@ describe("unittests:: tsserver:: configFileSearch:: searching for config file", const configFileLocation = `${projectDir}/src`; const f1 = { path: `${configFileLocation}/file1.ts`, - content: "" + content: "", }; const configFile = { path: `${configFileLocation}/tsconfig.json`, - content: "{}" + content: "{}", }; const configFile2 = { path: "/a/b/projects/tsconfig.json", - content: "{}" + content: "{}", }; const host = createServerHost([f1, libFile, configFile, configFile2]); const service = createProjectService(host, { @@ -86,11 +86,11 @@ describe("unittests:: tsserver:: configFileSearch:: searching for config file", const projectRoot = "/a/b/projects/project"; const file: File = { path: `${projectRoot}/src/index.ts`, - content: "let y = 10" + content: "let y = 10", }; const tsconfig: File = { path: `${projectRoot}/tsconfig.json`, - content: "{}" + content: "{}", }; function openClientFile(files: File[]) { const host = createServerHost(files); diff --git a/src/testRunner/unittests/tsserver/configuredProjects.ts b/src/testRunner/unittests/tsserver/configuredProjects.ts index a496d5612849c..0f524e010e49b 100644 --- a/src/testRunner/unittests/tsserver/configuredProjects.ts +++ b/src/testRunner/unittests/tsserver/configuredProjects.ts @@ -1,5 +1,7 @@ import * as ts from "../../_namespaces/ts"; -import { ensureErrorFreeBuild } from "../helpers/solutionBuilder"; +import { + ensureErrorFreeBuild, +} from "../helpers/solutionBuilder"; import { commonFile1, commonFile2, @@ -31,19 +33,19 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { "exclude": [ "e" ] - }` + }`, }; const file1: File = { path: "/a/b/c/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2: File = { path: "/a/b/d/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const file3: File = { path: "/a/b/e/f3.ts", - content: "let z = 1" + content: "let z = 1", }; const host = createServerHost([configFile, libFile, file1, file2, file3]); @@ -63,19 +65,19 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { { "compilerOptions": {}, "include": ["*.ts"] - }` + }`, }; const file1: File = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2: File = { path: "/a/b/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const file3: File = { path: "/a/b/c/f3.ts", - content: "let z = 1" + content: "let z = 1", }; const host = createServerHost([configFile, libFile, file1, file2, file3]); @@ -93,15 +95,15 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { path: `/user/username/projects/myproject/tsconfig.json`, content: `{ "files": ["commonFile1.ts"] - }` + }`, }; const commonFile1: File = { path: `/user/username/projects/myproject/commonFile1.ts`, - content: "let x = 1" + content: "let x = 1", }; const commonFile2: File = { path: `/user/username/projects/myproject/commonFile2.ts`, - content: "let y = 1" + content: "let y = 1", }; const host = createServerHost([libFile, commonFile1, commonFile2]); @@ -124,7 +126,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("add new files to a configured project without file list", () => { const configFile: File = { path: "/a/b/tsconfig.json", - content: `{}` + content: `{}`, }; const host = createServerHost([commonFile1, libFile, configFile]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -145,7 +147,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { "commonFile1.ts", "commonFile3.ts" ] - }` + }`, }; const host = createServerHost([commonFile1, commonFile2, configFile]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -157,7 +159,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("handle recreated files correctly", () => { const configFile: File = { path: "/a/b/tsconfig.json", - content: `{}` + content: `{}`, }; const host = createServerHost([commonFile1, commonFile2, configFile]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -179,11 +181,11 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { content: `{ "compilerOptions": {}, "exclude": ["/a/c"] - }` + }`, }; const excludedFile1: File = { path: "/a/c/excluedFile1.ts", - content: `let t = 1;` + content: `let t = 1;`, }; const host = createServerHost([commonFile1, commonFile2, excludedFile1, configFile]); @@ -197,19 +199,19 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("should properly handle module resolution changes in config file", () => { const file1: File = { path: "/a/b/file1.ts", - content: `import { T } from "module1";` + content: `import { T } from "module1";`, }; const nodeModuleFile: File = { path: "/a/b/node_modules/module1.ts", - content: `export interface T {}` + content: `export interface T {}`, }; const classicModuleFile: File = { path: "/a/module1.ts", - content: `export interface T {}` + content: `export interface T {}`, }; const randomFile: File = { path: "/a/file1.ts", - content: `export interface T {}` + content: `export interface T {}`, }; const configFile: File = { path: "/a/b/tsconfig.json", @@ -218,7 +220,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { "moduleResolution": "node" }, "files": ["${file1.path}"] - }` + }`, }; const files = [file1, nodeModuleFile, classicModuleFile, configFile, randomFile]; const host = createServerHost(files); @@ -227,13 +229,15 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { projectService.openClientFile(nodeModuleFile.path); projectService.openClientFile(classicModuleFile.path); - - host.writeFile(configFile.path, `{ + host.writeFile( + configFile.path, + `{ "compilerOptions": { "moduleResolution": "classic" }, "files": ["${file1.path}"] - }`); + }`, + ); host.runQueuedTimeoutCallbacks(); // will not remove project 1 @@ -247,11 +251,11 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("should keep the configured project when the opened file is referenced by the project but not its root", () => { const file1: File = { path: "/a/b/main.ts", - content: "import { objA } from './obj-a';" + content: "import { objA } from './obj-a';", }; const file2: File = { path: "/a/b/obj-a.ts", - content: `export const objA = Object.assign({foo: "bar"}, {bar: "baz"});` + content: `export const objA = Object.assign({foo: "bar"}, {bar: "baz"});`, }; const configFile: File = { path: "/a/b/tsconfig.json", @@ -260,7 +264,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { "target": "es6" }, "files": [ "main.ts" ] - }` + }`, }; const host = createServerHost([file1, file2, configFile]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -279,7 +283,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { "allowAnything": true }, "someOtherProperty": {} - }` + }`, }; const host = createServerHost([commonFile1, commonFile2, libFile, configFile]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -290,11 +294,11 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("should reuse same project if file is opened from the configured project that has no open files", () => { const file1 = { path: "/a/b/main.ts", - content: "let x =1;" + content: "let x =1;", }; const file2 = { path: "/a/b/main2.ts", - content: "let y =1;" + content: "let y =1;", }; const configFile: File = { path: "/a/b/tsconfig.json", @@ -303,7 +307,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { "target": "es6" }, "files": [ "main.ts", "main2.ts" ] - }` + }`, }; const host = createServerHost([file1, file2, configFile, libFile]); const projectService = createProjectService(host, { useSingleInferredProject: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -321,7 +325,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("should not close configured project after closing last open file, but should be closed on next file open if its not the file from same project", () => { const file1 = { path: "/a/b/main.ts", - content: "let x =1;" + content: "let x =1;", }; const configFile: File = { path: "/a/b/tsconfig.json", @@ -330,7 +334,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { "target": "es6" }, "files": [ "main.ts" ] - }` + }`, }; const host = createServerHost([file1, configFile, libFile]); const projectService = createProjectService(host, { useSingleInferredProject: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -348,19 +352,19 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("open file become a part of configured project if it is referenced from root file", () => { const file1 = { path: `/user/username/projects/myproject/a/b/f1.ts`, - content: "export let x = 5" + content: "export let x = 5", }; const file2 = { path: `/user/username/projects/myproject/a/c/f2.ts`, - content: `import {x} from "../b/f1"` + content: `import {x} from "../b/f1"`, }; const file3 = { path: `/user/username/projects/myproject/a/c/f3.ts`, - content: "export let y = 1" + content: "export let y = 1", }; const configFile = { path: `/user/username/projects/myproject/a/c/tsconfig.json`, - content: JSON.stringify({ compilerOptions: {}, files: ["f2.ts", "f3.ts"] }) + content: JSON.stringify({ compilerOptions: {}, files: ["f2.ts", "f3.ts"] }), }; const host = createServerHost([file1, file2, file3]); @@ -379,15 +383,15 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("can correctly update configured project when set of root files has changed (new file on disk)", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const configFile = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {} }) + content: JSON.stringify({ compilerOptions: {} }), }; const host = createServerHost([file1, configFile]); @@ -405,15 +409,15 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("can correctly update configured project when set of root files has changed (new file in list of files)", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const configFile = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts"] }) + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts"] }), }; const host = createServerHost([file1, file2, configFile]); @@ -430,15 +434,15 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("can update configured project when set of root files was not changed", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const configFile = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }) + content: JSON.stringify({ compilerOptions: {}, files: ["f1.ts", "f2.ts"] }), }; const host = createServerHost([file1, file2, configFile]); @@ -455,23 +459,23 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("Open ref of configured project when open file gets added to the project as part of configured file update", () => { const file1: File = { path: "/a/b/src/file1.ts", - content: "let x = 1;" + content: "let x = 1;", }; const file2: File = { path: "/a/b/src/file2.ts", - content: "let y = 1;" + content: "let y = 1;", }; const file3: File = { path: "/a/b/file3.ts", - content: "let z = 1;" + content: "let z = 1;", }; const file4: File = { path: "/a/file4.ts", - content: "let z = 1;" + content: "let z = 1;", }; const configFile = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ files: ["src/file1.ts", "file3.ts"] }) + content: JSON.stringify({ files: ["src/file1.ts", "file3.ts"] }), }; const files = [file1, file2, file3, file4]; @@ -506,7 +510,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { const file5: File = { path: "/file5.ts", - content: "let zz = 1;" + content: "let zz = 1;", }; host.writeFile(file5.path, file5.content); projectService.testhost.baselineHost("File5 written"); @@ -518,23 +522,23 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("Open ref of configured project when open file gets added to the project as part of configured file update buts its open file references are all closed when the update happens", () => { const file1: File = { path: "/a/b/src/file1.ts", - content: "let x = 1;" + content: "let x = 1;", }; const file2: File = { path: "/a/b/src/file2.ts", - content: "let y = 1;" + content: "let y = 1;", }; const file3: File = { path: "/a/b/file3.ts", - content: "let z = 1;" + content: "let z = 1;", }; const file4: File = { path: "/a/file4.ts", - content: "let z = 1;" + content: "let z = 1;", }; const configFile = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ files: ["src/file1.ts", "file3.ts"] }) + content: JSON.stringify({ files: ["src/file1.ts", "file3.ts"] }), }; const files = [file1, file2, file3]; @@ -569,24 +573,23 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("files are properly detached when language service is disabled", () => { const f1 = { path: "/a/app.js", - content: "var x = 1" + content: "var x = 1", }; const f2 = { path: "/a/largefile.js", - content: "" + content: "", }; const f3 = { path: "/a/lib.js", - content: "var x = 1" + content: "var x = 1", }; const config = { path: "/a/tsconfig.json", - content: JSON.stringify({ compilerOptions: { allowJs: true } }) + content: JSON.stringify({ compilerOptions: { allowJs: true } }), }; const host = createServerHost([f1, f2, f3, config]); const originalGetFileSize = host.getFileSize; - host.getFileSize = (filePath: string) => - filePath === f2.path ? ts.server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + host.getFileSize = (filePath: string) => filePath === f2.path ? ts.server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); projectService.openClientFile(f1.path); @@ -603,7 +606,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { const f4 = { path: "/aa.js", - content: "var x = 1" + content: "var x = 1", }; host.writeFile(f4.path, f4.content); projectService.openClientFile(f4.path); @@ -619,20 +622,19 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { it("syntactic features work even if language service is disabled", () => { const f1 = { path: "/a/app.js", - content: "let x = 1;" + content: "let x = 1;", }; const f2 = { path: "/a/largefile.js", - content: "" + content: "", }; const config = { path: "/a/jsconfig.json", - content: "{}" + content: "{}", }; const host = createServerHost([f1, f2, config]); const originalGetFileSize = host.getFileSize; - host.getFileSize = (filePath: string) => - filePath === f2.path ? ts.server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + host.getFileSize = (filePath: string) => filePath === f2.path ? ts.server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); openFilesForSession([f1], session); session.logger.log(`Language languageServiceEnabled:: ${session.getProjectService().configuredProjects.get(config.path)!.languageServiceEnabled}`); @@ -641,7 +643,7 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { command: ts.server.protocol.CommandTypes.FormatFull, arguments: { file: f1.path, - } + }, }); baselineTsserverLogs("configuredProjects", "syntactic features work even if language service is disabled", session); }); @@ -652,47 +654,47 @@ describe("unittests:: tsserver:: ConfiguredProjects", () => { content: JSON.stringify({ include: ["index.ts"], compilerOptions: { - lib: ["dom", "es2017"] - } - }) + lib: ["dom", "es2017"], + }, + }), }; const barIndex: File = { path: `/user/username/projects/myproject/bar/index.ts`, content: ` export function bar() { console.log("hello world"); -}` +}`, }; const fooConfig: File = { path: `/user/username/projects/myproject/foo/tsconfig.json`, content: JSON.stringify({ include: ["index.ts"], compilerOptions: { - lib: ["es2017"] - } - }) + lib: ["es2017"], + }, + }), }; const fooIndex: File = { path: `/user/username/projects/myproject/foo/index.ts`, content: ` import { bar } from "bar"; -bar();` +bar();`, }; const barSymLink: SymLink = { path: `/user/username/projects/myproject/foo/node_modules/bar`, - symLink: `/user/username/projects/myproject/bar` + symLink: `/user/username/projects/myproject/bar`, }; const lib2017: File = { path: `${ts.getDirectoryPath(libFile.path)}/lib.es2017.d.ts`, - content: libFile.content + content: libFile.content, }; const libDom: File = { path: `${ts.getDirectoryPath(libFile.path)}/lib.dom.d.ts`, content: ` declare var console: { log(...args: any[]): void; -};` +};`, }; const host = createServerHost([barConfig, barIndex, fooConfig, fooIndex, barSymLink, lib2017, libDom]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -704,15 +706,15 @@ declare var console: { it("when file name starts with ^", () => { const file: File = { path: `/user/username/projects/myproject/file.ts`, - content: "const x = 10;" + content: "const x = 10;", }; const app: File = { path: `/user/username/projects/myproject/^app.ts`, - content: "const y = 10;" + content: "const y = 10;", }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const host = createServerHost([file, app, tsconfig, libFile]); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -723,34 +725,37 @@ declare var console: { describe("when creating new file", () => { const foo: File = { path: `/user/username/projects/myproject/src/foo.ts`, - content: "export function foo() { }" + content: "export function foo() { }", }; const bar: File = { path: `/user/username/projects/myproject/src/bar.ts`, - content: "export function bar() { }" + content: "export function bar() { }", }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ - include: ["./src"] - }) + include: ["./src"], + }), }; const fooBar: File = { path: `/user/username/projects/myproject/src/sub/fooBar.ts`, - content: "export function fooBar() { }" + content: "export function fooBar() { }", }; function verifySessionWorker({ withExclude, openFileBeforeCreating }: VerifySession, errorOnNewFileBeforeOldFile: boolean) { const host = createServerHost([ - foo, bar, libFile, { path: `/user/username/projects/myproject/src/sub` }, + foo, + bar, + libFile, + { path: `/user/username/projects/myproject/src/sub` }, withExclude ? { path: config.path, content: JSON.stringify({ include: ["./src"], - exclude: ["./src/sub"] - }) + exclude: ["./src/sub"], + }), } : - config + config, ]); const session = createSession(host, { canUseEvents: true, @@ -761,8 +766,8 @@ declare var console: { arguments: { file: foo.path, fileContent: foo.content, - projectRootPath: "/user/username/projects/myproject" - } + projectRootPath: "/user/username/projects/myproject", + }, }); if (!openFileBeforeCreating) { host.writeFile(fooBar.path, fooBar.content); @@ -772,8 +777,8 @@ declare var console: { arguments: { file: fooBar.path, fileContent: fooBar.content, - projectRootPath: "/user/username/projects/myproject" - } + projectRootPath: "/user/username/projects/myproject", + }, }); if (openFileBeforeCreating) { host.writeFile(fooBar.path, fooBar.content); @@ -783,7 +788,7 @@ declare var console: { files: errorOnNewFileBeforeOldFile ? [fooBar, foo] : [foo, fooBar], - existingTimeouts: !withExclude + existingTimeouts: !withExclude, }); baselineTsserverLogs("configuredProjects", `creating new file and then open it ${openFileBeforeCreating ? "before" : "after"} watcher is invoked, ask errors on it ${errorOnNewFileBeforeOldFile ? "before" : "after"} old one${withExclude ? " without file being in config" : ""}`, session); } @@ -828,20 +833,20 @@ declare var console: { it("when default configured project does not contain the file", () => { const barConfig: File = { path: `/user/username/projects/myproject/bar/tsconfig.json`, - content: "{}" + content: "{}", }; const barIndex: File = { path: `/user/username/projects/myproject/bar/index.ts`, content: `import {foo} from "../foo/lib"; -foo();` +foo();`, }; const fooBarConfig: File = { path: `/user/username/projects/myproject/foobar/tsconfig.json`, - content: barConfig.path + content: barConfig.path, }; const fooBarIndex: File = { path: `/user/username/projects/myproject/foobar/index.ts`, - content: barIndex.content + content: barIndex.content, }; const fooConfig: File = { path: `/user/username/projects/myproject/foo/tsconfig.json`, @@ -849,13 +854,13 @@ foo();` include: ["index.ts"], compilerOptions: { declaration: true, - outDir: "lib" - } - }) + outDir: "lib", + }, + }), }; const fooIndex: File = { path: `/user/username/projects/myproject/foo/index.ts`, - content: `export function foo() {}` + content: `export function foo() {}`, }; const host = createServerHost([barConfig, barIndex, fooBarConfig, fooBarIndex, fooConfig, fooIndex, libFile]); ensureErrorFreeBuild(host, [fooConfig.path]); @@ -870,8 +875,8 @@ foo();` startLine: 1, startOffset: 1, endLine: 1, - endOffset: 1 - } + endOffset: 1, + }, }); session.logger.log(`Default project for file: ${fooDts}: ${service.tryGetDefaultProjectForFile(ts.server.toNormalizedPath(fooDts))?.projectName}`); baselineTsserverLogs("configuredProjects", "when default configured project does not contain the file", session); @@ -881,35 +886,35 @@ foo();` function getService(additionalFiles?: File[]) { const alphaExtendedConfig: File = { path: `/user/username/projects/myproject/extended/alpha.tsconfig.json`, - content: "{}" + content: "{}", }; const bravoExtendedConfig: File = { path: `/user/username/projects/myproject/extended/bravo.tsconfig.json`, content: JSON.stringify({ - extends: "./alpha.tsconfig.json" - }) + extends: "./alpha.tsconfig.json", + }), }; const aConfig: File = { path: `/user/username/projects/myproject/a/tsconfig.json`, content: JSON.stringify({ extends: "../extended/alpha.tsconfig.json", - files: ["a.ts"] - }) + files: ["a.ts"], + }), }; const aFile: File = { path: `/user/username/projects/myproject/a/a.ts`, - content: `let a = 1;` + content: `let a = 1;`, }; const bConfig: File = { path: `/user/username/projects/myproject/b/tsconfig.json`, content: JSON.stringify({ extends: "../extended/bravo.tsconfig.json", - files: ["b.ts"] - }) + files: ["b.ts"], + }), }; const bFile: File = { path: `/user/username/projects/myproject/b/b.ts`, - content: `let b = 1;` + content: `let b = 1;`, }; const host = createServerHost([alphaExtendedConfig, aConfig, aFile, bravoExtendedConfig, bConfig, bFile, ...(additionalFiles || ts.emptyArray)]); @@ -923,24 +928,33 @@ foo();` projectService.openClientFile(aFile.path); projectService.openClientFile(bFile.path); - host.writeFile(alphaExtendedConfig.path, JSON.stringify({ - compilerOptions: { - strict: true - } - })); + host.writeFile( + alphaExtendedConfig.path, + JSON.stringify({ + compilerOptions: { + strict: true, + }, + }), + ); host.runQueuedTimeoutCallbacks(); - host.writeFile(bravoExtendedConfig.path, JSON.stringify({ - extends: "./alpha.tsconfig.json", - compilerOptions: { - strict: false - } - })); + host.writeFile( + bravoExtendedConfig.path, + JSON.stringify({ + extends: "./alpha.tsconfig.json", + compilerOptions: { + strict: false, + }, + }), + ); host.runQueuedTimeoutCallbacks(); - host.writeFile(bConfig.path, JSON.stringify({ - extends: "../extended/alpha.tsconfig.json", - })); + host.writeFile( + bConfig.path, + JSON.stringify({ + extends: "../extended/alpha.tsconfig.json", + }), + ); host.runQueuedTimeoutCallbacks(); host.writeFile(alphaExtendedConfig.path, "{}"); @@ -951,11 +965,11 @@ foo();` it("should stop watching the extended configs of closed projects", () => { const dummy: File = { path: `/user/username/projects/myproject/dummy/dummy.ts`, - content: `let dummy = 1;` + content: `let dummy = 1;`, }; const dummyConfig: File = { path: `/user/username/projects/myproject/dummy/tsconfig.json`, - content: "{}" + content: "{}", }; const { projectService, aFile, bFile } = getService([dummy, dummyConfig]); @@ -967,7 +981,6 @@ foo();` projectService.closeClientFile(dummy.path); projectService.openClientFile(dummy.path); - projectService.closeClientFile(aFile.path); projectService.closeClientFile(dummy.path); projectService.openClientFile(dummy.path); @@ -983,11 +996,11 @@ describe("unittests:: tsserver:: ConfiguredProjects:: non-existing directories l content: `{ "compilerOptions": {}, "include": ["app/*", "test/**/*", "something"] - }` + }`, }; const file1 = { path: "/a/b/file1.ts", - content: "let t = 10;" + content: "let t = 10;", }; const host = createServerHost([file1, configFile]); @@ -1002,22 +1015,22 @@ describe("unittests:: tsserver:: ConfiguredProjects:: non-existing directories l it("should be able to handle @types if input file list is empty", () => { const f = { path: "/a/app.ts", - content: "let x = 1" + content: "let x = 1", }; const config = { path: "/a/tsconfig.json", content: JSON.stringify({ compiler: {}, - files: [] - }) + files: [], + }), }; const t1 = { path: "/a/node_modules/@types/typings/index.d.ts", - content: `export * from "./lib"` + content: `export * from "./lib"`, }; const t2 = { path: "/a/node_modules/@types/typings/lib.d.ts", - content: `export const x: number` + content: `export const x: number`, }; const host = createServerHost([f, config, t1, t2], { currentDirectory: ts.getDirectoryPath(f.path) }); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -1030,19 +1043,19 @@ describe("unittests:: tsserver:: ConfiguredProjects:: non-existing directories l it("should tolerate invalid include files that start in subDirectory", () => { const f = { path: `/user/username/projects/myproject/src/server/index.ts`, - content: "let x = 1" + content: "let x = 1", }; const config = { path: `/user/username/projects/myproject/src/server/tsconfig.json`, content: JSON.stringify({ compiler: { module: "commonjs", - outDir: "../../build" + outDir: "../../build", }, include: [ - "../src/**/*.ts" - ] - }) + "../src/**/*.ts", + ], + }), }; const host = createServerHost([f, config, libFile], { useCaseSensitiveFileNames: true }); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -1055,19 +1068,19 @@ describe("unittests:: tsserver:: ConfiguredProjects:: non-existing directories l it("Changed module resolution reflected when specifying files list", () => { const file1: File = { path: "/users/username/projects/project/file1.ts", - content: 'import classc from "file2"' + content: 'import classc from "file2"', }; const file2a: File = { path: "/users/username/projects/file2.ts", - content: "export classc { method2a() { return 10; } }" + content: "export classc { method2a() { return 10; } }", }; const file2: File = { path: "/users/username/projects/project/file2.ts", - content: "export classc { method2() { return 10; } }" + content: "export classc { method2() { return 10; } }", }; const configFile: File = { path: "/users/username/projects/project/tsconfig.json", - content: JSON.stringify({ files: [file1.path], compilerOptions: { module: "amd" } }) + content: JSON.stringify({ files: [file1.path], compilerOptions: { module: "amd" } }), }; const files = [file1, file2a, configFile, libFile]; const host = createServerHost(files); @@ -1087,24 +1100,24 @@ describe("unittests:: tsserver:: ConfiguredProjects:: non-existing directories l const root = "/user/username/rootfolder"; const file1: File = { path: "/a/b/src/file1.ts", - content: 'import { classc } from "module1"' + content: 'import { classc } from "module1"', }; const module1: File = { path: "/a/b/node_modules/module1/index.d.ts", content: `import { class2 } from "module2"; - export classc { method2a(): class2; }` + export classc { method2a(): class2; }`, }; const module2: File = { path: "/a/b/node_modules/module2/index.d.ts", - content: "export class2 { method2() { return 10; } }" + content: "export class2 { method2() { return 10; } }", }; const module3: File = { path: "/a/b/node_modules/module/node_modules/module3/index.d.ts", - content: "export class3 { method2() { return 10; } }" + content: "export class3 { method2() { return 10; } }", }; const configFile: File = { path: "/a/b/src/tsconfig.json", - content: JSON.stringify({ files: ["file1.ts"] }) + content: JSON.stringify({ files: ["file1.ts"] }), }; const nonLibFiles = [file1, module1, module2, module3, configFile]; nonLibFiles.forEach(f => f.path = root + f.path); @@ -1120,11 +1133,11 @@ describe("unittests:: tsserver:: ConfiguredProjects:: when reading tsconfig file it("should be tolerated without crashing the server", () => { const configFile = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "" + content: "", }; const file1 = { path: `/user/username/projects/myproject/file1.ts`, - content: "let t = 10;" + content: "let t = 10;", }; const host = createServerHost([file1, libFile, configFile]); diff --git a/src/testRunner/unittests/tsserver/declarationFileMaps.ts b/src/testRunner/unittests/tsserver/declarationFileMaps.ts index 1539380be3728..2f63d0c8b21ee 100644 --- a/src/testRunner/unittests/tsserver/declarationFileMaps.ts +++ b/src/testRunner/unittests/tsserver/declarationFileMaps.ts @@ -42,7 +42,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references sourceRoot: "", sources: ["../a.ts"], names: [], - mappings: "AAAA,wBAAgB,GAAG,SAAK;AACxB,MAAM,WAAW,MAAM;CAAG;AAC1B,eAAO,MAAM,SAAS,EAAE,MAAW,CAAC" + mappings: "AAAA,wBAAgB,GAAG,SAAK;AACxB,MAAM,WAAW,MAAM;CAAG;AAC1B,eAAO,MAAM,SAAS,EAAE,MAAW,CAAC", }; const aDtsMap: File = { path: "/a/bin/a.d.ts.map", @@ -80,7 +80,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const dummyFile: File = { path: "/dummy/dummy.ts", - content: "let a = 10;" + content: "let a = 10;", }; const userTs: File = { @@ -97,8 +97,8 @@ describe("unittests:: tsserver:: with declaration file maps:: project references path: "/user/tsconfig.json", content: JSON.stringify({ file: ["user.ts"], - references: [{ path: "../a" }, { path: "../b" }] - }) + references: [{ path: "../a" }, { path: "../b" }], + }), }; function makeSampleProjects(addUserTsConfig?: boolean, keepAllFiles?: boolean) { @@ -138,7 +138,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Definition, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "goToDefinition", session); @@ -148,7 +148,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "getDefinitionAndBoundSpan", session); @@ -158,7 +158,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(/*addUserTsConfig*/ true); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); // Navigate to the definition @@ -175,7 +175,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.TypeDefinition, - arguments: protocolFileLocationFromSubstring(userTs, "instanceA") + arguments: protocolFileLocationFromSubstring(userTs, "instanceA"), }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "goToType", session); @@ -185,7 +185,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Implementation, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "goToImplementation", session); @@ -195,7 +195,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Definition, - arguments: protocolFileLocationFromSubstring(userTs, "fnB()") + arguments: protocolFileLocationFromSubstring(userTs, "fnB()"), }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "goToDefinition target does not exist", session); @@ -205,7 +205,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Navto, - arguments: { file: userTs.path, searchValue: "fn" } + arguments: { file: userTs.path, searchValue: "fn" }, }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "navigateTo", session); @@ -215,7 +215,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(/*addUserTsConfig*/ true, /*keepAllFiles*/ true); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Navto, - arguments: { file: undefined, searchValue: "fn" } + arguments: { file: undefined, searchValue: "fn" }, }); baselineTsserverLogs("declarationFileMaps", "navigateToAll neither file not project is specified", session); }); @@ -224,7 +224,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(/*addUserTsConfig*/ true, /*keepAllFiles*/ true); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Navto, - arguments: { projectFileName: bTsconfig.path, file: undefined, searchValue: "fn" } + arguments: { projectFileName: bTsconfig.path, file: undefined, searchValue: "fn" }, }); baselineTsserverLogs("declarationFileMaps", "navigateToAll file is not specified but project is", session); }); @@ -233,7 +233,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); verifyATsConfigOriginalProject(session); @@ -245,19 +245,21 @@ describe("unittests:: tsserver:: with declaration file maps:: project references openFilesForSession([aTs], session); // If it's not opened, the reference isn't found. session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(aTs, "fnA") + arguments: protocolFileLocationFromSubstring(aTs, "fnA"), }); verifyATsConfigWhenOpened(session); baselineTsserverLogs("declarationFileMaps", "findAllReferences starting at definition", session); }); - interface ReferencesFullRequest extends ts.server.protocol.FileLocationRequest { readonly command: ts.server.protocol.CommandTypes.ReferencesFull; } + interface ReferencesFullRequest extends ts.server.protocol.FileLocationRequest { + readonly command: ts.server.protocol.CommandTypes.ReferencesFull; + } it("findAllReferencesFull", () => { const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.ReferencesFull, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); verifyATsConfigOriginalProject(session); baselineTsserverLogs("declarationFileMaps", "findAllReferencesFull", session); @@ -284,7 +286,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.ReferencesFull, - arguments: protocolFileLocationFromSubstring(bTs, "f()") + arguments: protocolFileLocationFromSubstring(bTs, "f()"), }); baselineTsserverLogs("declarationFileMaps", "findAllReferencesFull definition is in mapped file", session); }); @@ -293,7 +295,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(userTs, "fnB()") + arguments: protocolFileLocationFromSubstring(userTs, "fnB()"), }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "findAllReferences target does not exist", session); @@ -303,7 +305,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Rename, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); verifyATsConfigOriginalProject(session); baselineTsserverLogs("declarationFileMaps", "renameLocations", session); @@ -314,7 +316,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references openFilesForSession([aTs], session); // If it's not opened, the reference isn't found. session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Rename, - arguments: protocolFileLocationFromSubstring(aTs, "fnA") + arguments: protocolFileLocationFromSubstring(aTs, "fnA"), }); verifyATsConfigWhenOpened(session); baselineTsserverLogs("declarationFileMaps", "renameLocations starting at definition", session); @@ -324,7 +326,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.RenameLocationsFull, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); verifyATsConfigOriginalProject(session); baselineTsserverLogs("declarationFileMaps", "renameLocationsFull", session); @@ -334,7 +336,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references const session = makeSampleProjects(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Rename, - arguments: protocolFileLocationFromSubstring(userTs, "fnB()") + arguments: protocolFileLocationFromSubstring(userTs, "fnB()"), }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "renameLocations target does not exist", session); @@ -347,7 +349,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references arguments: { oldFilePath: aTs.path, newFilePath: "/a/aNew.ts", - } + }, }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "getEditsForFileRename", session); @@ -363,7 +365,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references declaration: true, declarationMap: true, outDir: "./build", - } + }, }), }; const bTs: File = { path: "/b/src/b.ts", content: "" }; @@ -387,7 +389,7 @@ describe("unittests:: tsserver:: with declaration file maps:: project references arguments: { oldFilePath: aTs.path, newFilePath: "/a/src/a1.ts", - } + }, }); baselineTsserverLogs("declarationFileMaps", "getEditsForFileRename when referencing project doesnt include file and its renamed", session); }); @@ -395,11 +397,11 @@ describe("unittests:: tsserver:: with declaration file maps:: project references it("does not jump to source if inlined sources", () => { const aDtsInlinedSources: ts.RawSourceMap = { ...aDtsMapContent, - sourcesContent: [aTs.content] + sourcesContent: [aTs.content], }; const aDtsMapInlinedSources: File = { path: aDtsMap.path, - content: JSON.stringify(aDtsInlinedSources) + content: JSON.stringify(aDtsInlinedSources), }; const host = createServerHost([aTs, aDtsMapInlinedSources, aDts, bTs, bDtsMap, bDts, userTs, dummyFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -410,13 +412,13 @@ describe("unittests:: tsserver:: with declaration file maps:: project references // Inlined so does not jump to aTs session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: protocolFileLocationFromSubstring(userTs, "fnA()") + arguments: protocolFileLocationFromSubstring(userTs, "fnA()"), }); // Not inlined, jumps to bTs session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: protocolFileLocationFromSubstring(userTs, "fnB()") + arguments: protocolFileLocationFromSubstring(userTs, "fnB()"), }); verifySingleInferredProject(session); baselineTsserverLogs("declarationFileMaps", "does not jump to source if inlined sources", session); diff --git a/src/testRunner/unittests/tsserver/documentRegistry.ts b/src/testRunner/unittests/tsserver/documentRegistry.ts index 3b3a5b63150dd..ffde566529c04 100644 --- a/src/testRunner/unittests/tsserver/documentRegistry.ts +++ b/src/testRunner/unittests/tsserver/documentRegistry.ts @@ -1,4 +1,6 @@ -import { reportDocumentRegistryStats } from "../../../harness/incrementalUtils"; +import { + reportDocumentRegistryStats, +} from "../../../harness/incrementalUtils"; import * as ts from "../../_namespaces/ts"; import { baselineTsserverLogs, @@ -19,15 +21,15 @@ describe("unittests:: tsserver:: documentRegistry:: document registry in project const importModuleContent = `import {a} from "./module1"`; const file: File = { path: `/user/username/projects/myproject/index.ts`, - content: importModuleContent + content: importModuleContent, }; const moduleFile: File = { path: `/user/username/projects/myproject/module1.d.ts`, - content: "export const a: number;" + content: "export const a: number;", }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ files: ["index.ts"] }) + content: JSON.stringify({ files: ["index.ts"] }), }; function getProject(service: TestProjectService) { @@ -127,19 +129,19 @@ describe("unittests:: tsserver:: documentRegistry:: works when reusing orphan sc textChanges: [{ newText, start: { line: 1, offset: 1 }, - end: { line: 2, offset: newText.length + 1 } // Remove the import so that structure is not reused - }] + end: { line: 2, offset: newText.length + 1 }, // Remove the import so that structure is not reused + }], }], openFiles: [ { file: "^/inmemory/model/4", fileContent: newText, projectRootPath: "/users/user/projects/san", // Add same document with different script kind - scriptKindName: "TS" + scriptKindName: "TS", }, - ] - } + ], + }, }); baselineTsserverLogs("documentRegistry", "works when reusing orphan script info with different scriptKind", session); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/duplicatePackages.ts b/src/testRunner/unittests/tsserver/duplicatePackages.ts index 3d4f31cba11e1..4a957d481ae01 100644 --- a/src/testRunner/unittests/tsserver/duplicatePackages.ts +++ b/src/testRunner/unittests/tsserver/duplicatePackages.ts @@ -43,7 +43,7 @@ describe("unittests:: tsserver:: duplicate packages", () => { endLine: 2, endOffset: 4, errorCodes: [ts.Diagnostics.Cannot_find_name_0.code], - } + }, }); } baselineTsserverLogs("duplicatePackages", "works with import fixes", session); diff --git a/src/testRunner/unittests/tsserver/dynamicFiles.ts b/src/testRunner/unittests/tsserver/dynamicFiles.ts index 4d1c79c582891..644deb0e908f1 100644 --- a/src/testRunner/unittests/tsserver/dynamicFiles.ts +++ b/src/testRunner/unittests/tsserver/dynamicFiles.ts @@ -21,7 +21,7 @@ function verifyPathRecognizedAsDynamic(subscenario: string, path: string) { path, content: `/// /// -var x = 10;` +var x = 10;`, }; const host = createServerHost([libFile]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -61,7 +61,7 @@ describe("unittests:: tsserver:: dynamicFiles:: Untitled files", () => { endLine: 3, endOffset: 5, errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], - } + }, }); baselineTsserverLogs("dynamicFiles", "untitled can convert positions to locations", session); }); @@ -69,7 +69,7 @@ describe("unittests:: tsserver:: dynamicFiles:: Untitled files", () => { it("opening untitled files", () => { const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const host = createServerHost([config, libFile], { useCaseSensitiveFileNames: true, currentDirectory: "/user/username/projects/myproject" }); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -78,7 +78,7 @@ describe("unittests:: tsserver:: dynamicFiles:: Untitled files", () => { const untitled: File = { path: `/user/username/projects/myproject/Untitled-1.ts`, - content: "const x = 10;" + content: "const x = 10;", }; host.writeFile(untitled.path, untitled.content); service.testhost.logTimeoutQueueLength(); @@ -94,11 +94,11 @@ describe("unittests:: tsserver:: dynamicFiles:: Untitled files", () => { it("opening and closing untitled files when projectRootPath is different from currentDirectory", () => { const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const file: File = { path: `/user/username/projects/myproject/file.ts`, - content: "const y = 10" + content: "const y = 10", }; const host = createServerHost([config, file, libFile], { useCaseSensitiveFileNames: true }); const service = createProjectService(host, { useInferredProjectPerProjectRoot: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -137,7 +137,7 @@ describe("unittests:: tsserver:: dynamicFiles:: ", () => { it("dynamic file without external project", () => { const file: File = { path: "^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js", - content: "var x = 10;" + content: "var x = 10;", }; const host = createServerHost([libFile], { useCaseSensitiveFileNames: true }); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -145,7 +145,7 @@ describe("unittests:: tsserver:: dynamicFiles:: ", () => { module: ts.ModuleKind.CommonJS, allowJs: true, allowSyntheticDefaultImports: true, - allowNonTsExtensions: true + allowNonTsExtensions: true, }, session); openFilesForSession([{ file: file.path, content: "var x = 10;" }], session); @@ -153,7 +153,7 @@ describe("unittests:: tsserver:: dynamicFiles:: ", () => { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Quickinfo, - arguments: protocolFileLocationFromSubstring(file, "x") + arguments: protocolFileLocationFromSubstring(file, "x"), }); baselineTsserverLogs("dynamicFiles", "dynamic file without external project", session); }); @@ -163,15 +163,15 @@ describe("unittests:: tsserver:: dynamicFiles:: ", () => { describe("dynamic file with projectRootPath", () => { const file: File = { path: "^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js", - content: "var x = 10;" + content: "var x = 10;", }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const configProjectFile: File = { path: `/user/username/projects/myproject/a.ts`, - content: "let y = 10;" + content: "let y = 10;", }; it("with useInferredProjectPerProjectRoot", () => { const host = createServerHost([libFile, configFile, configProjectFile], { useCaseSensitiveFileNames: true }); @@ -184,8 +184,8 @@ describe("unittests:: tsserver:: dynamicFiles:: ", () => { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetOutliningSpans, arguments: { - file: file.path - } + file: file.path, + }, }); // Without project root @@ -203,7 +203,7 @@ describe("unittests:: tsserver:: dynamicFiles:: ", () => { catch (e) { assert.strictEqual( e.message.replace(/\r?\n/, "\n"), - `Debug Failure. False expression.\nVerbose Debug Information: {"fileName":"^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js","currentDirectory":"/user/username/projects/myproject","hostCurrentDirectory":"/","openKeys":[]}\nDynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.` + `Debug Failure. False expression.\nVerbose Debug Information: {"fileName":"^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js","currentDirectory":"/user/username/projects/myproject","hostCurrentDirectory":"/","openKeys":[]}\nDynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.`, ); } const file2Path = file.path.replace("#1", "#2"); diff --git a/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts b/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts index c62579832b33e..7406af24c15ad 100644 --- a/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts +++ b/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts @@ -23,7 +23,7 @@ describe("unittests:: tsserver:: events:: LargeFileReferencedEvent with large fi const largeFile: File = { path: `/user/username/projects/myproject/${getLargeFile(useLargeTsFile)}`, content: "export var x = 10;", - fileSize: ts.server.maxFileSize + 1 + fileSize: ts.server.maxFileSize + 1, }; files.push(largeFile); const host = createServerHost(files); @@ -36,11 +36,11 @@ describe("unittests:: tsserver:: events:: LargeFileReferencedEvent with large fi it("when large file is included by tsconfig", () => { const file: File = { path: `/user/username/projects/myproject/src/file.ts`, - content: "export var y = 10;" + content: "export var y = 10;", }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: JSON.stringify({ files: ["src/file.ts", getLargeFile(useLargeTsFile)], compilerOptions: { target: 1, allowJs: true } }) + content: JSON.stringify({ files: ["src/file.ts", getLargeFile(useLargeTsFile)], compilerOptions: { target: 1, allowJs: true } }), }; const files = [file, libFile, tsconfig]; const session = createSessionWithEventHandler(files, useLargeTsFile); @@ -51,7 +51,7 @@ describe("unittests:: tsserver:: events:: LargeFileReferencedEvent with large fi it("when large file is included by module resolution", () => { const file: File = { path: `/user/username/projects/myproject/src/file.ts`, - content: `export var y = 10;import {x} from "./large"` + content: `export var y = 10;import {x} from "./large"`, }; const files = [file, libFile]; const session = createSessionWithEventHandler(files, useLargeTsFile); diff --git a/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts b/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts index 6ce697771b67a..4f854dca732d9 100644 --- a/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts +++ b/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts @@ -16,7 +16,7 @@ describe("unittests:: tsserver:: events:: ProjectLanguageServiceStateEvent", () it("language service disabled events are triggered", () => { const f1 = { path: "/a/app.js", - content: "let x = 1;" + content: "let x = 1;", }; const f2 = { path: "/a/largefile.js", @@ -24,16 +24,15 @@ describe("unittests:: tsserver:: events:: ProjectLanguageServiceStateEvent", () }; const config = { path: "/a/jsconfig.json", - content: "{}" + content: "{}", }; const configWithExclude = { path: config.path, - content: JSON.stringify({ exclude: ["largefile.js"] }) + content: JSON.stringify({ exclude: ["largefile.js"] }), }; const host = createServerHost([f1, f2, config]); const originalGetFileSize = host.getFileSize; - host.getFileSize = (filePath: string) => - filePath === f2.path ? ts.server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + host.getFileSize = (filePath: string) => filePath === f2.path ? ts.server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); openFilesForSession([f1], session); @@ -48,21 +47,21 @@ describe("unittests:: tsserver:: events:: ProjectLanguageServiceStateEvent", () it("Large file size is determined correctly", () => { const f1: File = { path: "/a/app.js", - content: "let x = 1;" + content: "let x = 1;", }; const f2: File = { path: "/a/largefile.js", content: "", - fileSize: ts.server.maxProgramSizeForNonTsFiles + 1 + fileSize: ts.server.maxProgramSizeForNonTsFiles + 1, }; const f3: File = { path: "/a/extremlylarge.d.ts", content: "", - fileSize: ts.server.maxProgramSizeForNonTsFiles + 100 + fileSize: ts.server.maxProgramSizeForNonTsFiles + 100, }; const config = { path: "/a/jsconfig.json", - content: "{}" + content: "{}", }; const host = createServerHost([f1, f2, f3, libFile, config]); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); diff --git a/src/testRunner/unittests/tsserver/events/projectLoading.ts b/src/testRunner/unittests/tsserver/events/projectLoading.ts index 90781f75c8bba..98295f81aaf4a 100644 --- a/src/testRunner/unittests/tsserver/events/projectLoading.ts +++ b/src/testRunner/unittests/tsserver/events/projectLoading.ts @@ -20,11 +20,11 @@ import { describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoadingFinish events", () => { const aTs: File = { path: `/user/username/projects/a/a.ts`, - content: "export class A { }" + content: "export class A { }", }; const configA: File = { path: `/user/username/projects/a/tsconfig.json`, - content: "{}" + content: "{}", }; const bTsPath = `/user/username/projects/b/b.ts`; const configBPath = `/user/username/projects/b/tsconfig.json`; @@ -35,11 +35,11 @@ describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoading it("when project is created by open file", () => { const bTs: File = { path: bTsPath, - content: "export class B {}" + content: "export class B {}", }; const configB: File = { path: configBPath, - content: "{}" + content: "{}", }; const host = createServerHost(files.concat(bTs, configB)); const session = createSession(host); @@ -61,13 +61,13 @@ describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoading it("when change is detected in an extended config file", () => { const bTs: File = { path: bTsPath, - content: "export class B {}" + content: "export class B {}", }; const configB: File = { path: configBPath, content: JSON.stringify({ extends: "../a/tsconfig.json", - }) + }), }; const host = createServerHost(files.concat(bTs, configB)); const session = createSession(host); @@ -93,26 +93,26 @@ describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoading content: `export declare class A { } //# sourceMappingURL=a.d.ts.map -` +`, }; const aDTsMap: File = { path: `/user/username/projects/a/a.d.ts.map`, - content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}` + content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}`, }; const bTs: File = { path: bTsPath, - content: `import {A} from "../a/a"; new A();` + content: `import {A} from "../a/a"; new A();`, }; const configB: File = { path: configBPath, content: JSON.stringify({ ...(disableSourceOfProjectReferenceRedirect && { compilerOptions: { - disableSourceOfProjectReferenceRedirect - } + disableSourceOfProjectReferenceRedirect, + }, }), - references: [{ path: "../a" }] - }) + references: [{ path: "../a" }], + }), }; const host = createServerHost(files.concat(aDTs, aDTsMap, bTs, configB)); @@ -123,8 +123,8 @@ describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoading command: ts.server.protocol.CommandTypes.References, arguments: { file: bTs.path, - ...protocolLocationFromSubstring(bTs.content, "A()") - } + ...protocolLocationFromSubstring(bTs.content, "A()"), + }, }); baselineTsserverLogs("events/projectLoading", `opening original location project${disableSourceOfProjectReferenceRedirect ? " disableSourceOfProjectReferenceRedirect" : ""} ${sessionType}`, session); } @@ -139,13 +139,13 @@ describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoading session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, arguments: { - preferences: { lazyConfiguredProjectsFromExternalProject } - } + preferences: { lazyConfiguredProjectsFromExternalProject }, + }, }); openExternalProjectForSession({ projectFileName, rootFiles: toExternalFiles([aTs.path, configA.path]), - options: {} + options: {}, }, session); return session; } @@ -166,8 +166,8 @@ describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoading session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, arguments: { - preferences: { lazyConfiguredProjectsFromExternalProject: false } - } + preferences: { lazyConfiguredProjectsFromExternalProject: false }, + }, }); baselineTsserverLogs("events/projectLoading", `lazyConfiguredProjectsFromExternalProject is disabled ${sessionType}`, session); }); @@ -176,8 +176,9 @@ describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoading } verifyProjectLoadingStartAndFinish("when using event handler", host => createSessionWithCustomEventHandler(host)); - verifyProjectLoadingStartAndFinish("when using default event handler", host => createSession( - host, - { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) } - )); + verifyProjectLoadingStartAndFinish("when using default event handler", host => + createSession( + host, + { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }, + )); }); diff --git a/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts b/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts index 19be7628c980b..8f113d43c0162 100644 --- a/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts +++ b/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts @@ -19,19 +19,19 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { it("when adding new file", () => { const commonFile1: File = { path: "/users/username/projects/project/file1.ts", - content: "export var x = 10;" + content: "export var x = 10;", }; const commonFile2: File = { path: "/users/username/projects/project/file2.ts", - content: "export var y = 10;" + content: "export var y = 10;", }; const commonFile3: File = { path: "/users/username/projects/project/file3.ts", - content: "export var z = 10;" + content: "export var z = 10;", }; const configFile: File = { path: "/users/username/projects/project/tsconfig.json", - content: `{}` + content: `{}`, }; const host = createServerHost([commonFile1, libFile, configFile]); const session = createSession(host); @@ -51,17 +51,17 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { const config: File = { path: "/users/username/projects/project/tsconfig.json", content: JSON.stringify({ - compilerOptions - }) + compilerOptions, + }), }; const f1: File = { path: "/users/username/projects/project/a.ts", - content: "export let x = 1" + content: "export let x = 1", }; const f2: File = { path: "/users/username/projects/project/b.ts", - content: "export let y = 1" + content: "export let y = 1", }; const files = [f1, config, libFile]; @@ -117,13 +117,13 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { const globalFile3: File = { path: "/users/username/projects/project/globalFile3.ts", - content: `interface GlobalFoo { age: number }` + content: `interface GlobalFoo { age: number }`, }; const additionalFiles = getAdditionalFileOrFolder ? getAdditionalFileOrFolder() : []; const configFile = { path: configFilePath, - content: JSON.stringify(configObj || { compilerOptions: {} }) + content: JSON.stringify(configObj || { compilerOptions: {} }), }; const files: File[] = [file1Consumer1, moduleFile1, file1Consumer2, moduleFile2, ...additionalFiles, globalFile3, libFile, configFile]; @@ -140,8 +140,14 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { if (!firstReloadFileList) host.runQueuedTimeoutCallbacks(); // Invalidated module resolutions to schedule project update return { - host, session, - moduleFile1, file1Consumer1, file1Consumer2, moduleFile2, globalFile3, configFile, + host, + session, + moduleFile1, + file1Consumer1, + file1Consumer2, + moduleFile2, + globalFile3, + configFile, updateContentOfOpenFile, }; @@ -154,8 +160,8 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { endLine: 1, endOffset: file.content.length, line: 1, - offset: 1 - } + offset: 1, + }, }); file.content = newContent; } @@ -216,7 +222,7 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { }); it("should be up-to-date with newly created files", () => { - const { host, moduleFile1, session, } = getInitialState(); + const { host, moduleFile1, session } = getInitialState(); host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); host.writeFile("/users/username/projects/project/file1Consumer3.ts", `import {Foo} from "./moduleFile1"; let y = Foo();`); @@ -248,7 +254,7 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { it("should always return the file itself if '--isolatedModules' is specified", () => { const { host, moduleFile1, session } = getInitialState({ - configObj: { compilerOptions: { isolatedModules: true } } + configObj: { compilerOptions: { isolatedModules: true } }, }); host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); @@ -259,7 +265,7 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { it("should always return the file itself if '--out' or '--outFile' is specified", () => { const outFilePath = "/users/username/projects/project/out.js"; const { host, moduleFile1, session } = getInitialState({ - configObj: { compilerOptions: { module: "system", outFile: outFilePath } } + configObj: { compilerOptions: { module: "system", outFile: outFilePath } }, }); host.writeFile(moduleFile1.path, `export var T: number;export function Foo() { };`); @@ -270,10 +276,10 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { it("should return cascaded affected file list", () => { const file1Consumer1Consumer1: File = { path: "/users/username/projects/project/file1Consumer1Consumer1.ts", - content: `import {y} from "./file1Consumer1";` + content: `import {y} from "./file1Consumer1";`, }; const { host, moduleFile1, file1Consumer1, updateContentOfOpenFile, session } = getInitialState({ - getAdditionalFileOrFolder: () => [file1Consumer1Consumer1] + getAdditionalFileOrFolder: () => [file1Consumer1Consumer1], }); updateContentOfOpenFile(file1Consumer1, file1Consumer1.content + "export var T: number;"); @@ -295,17 +301,17 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { path: "/users/username/projects/project/file1.ts", content: ` /// - export var t1 = 10;` + export var t1 = 10;`, }; const file2: File = { path: "/users/username/projects/project/file2.ts", content: ` /// - export var t2 = 10;` + export var t2 = 10;`, }; const { host, session } = getInitialState({ getAdditionalFileOrFolder: () => [file1, file2], - firstReloadFileList: [file1.path, libFile.path, file2.path, configFilePath] + firstReloadFileList: [file1.path, libFile.path, file2.path, configFilePath], }); host.writeFile(file2.path, file2.content + "export var t3 = 10;"); @@ -318,11 +324,11 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { path: "/users/username/projects/project/referenceFile1.ts", content: ` /// - export var x = Foo();` + export var x = Foo();`, }; const { host, session } = getInitialState({ getAdditionalFileOrFolder: () => [referenceFile1], - firstReloadFileList: [referenceFile1.path, libFile.path, moduleFile1Path, configFilePath] + firstReloadFileList: [referenceFile1.path, libFile.path, moduleFile1Path, configFilePath], }); host.deleteFile(moduleFile1Path); @@ -335,11 +341,11 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { path: "/users/username/projects/project/referenceFile1.ts", content: ` /// - export var x = Foo();` + export var x = Foo();`, }; const { host, moduleFile2, updateContentOfOpenFile, session } = getInitialState({ getAdditionalFileOrFolder: () => [referenceFile1], - firstReloadFileList: [referenceFile1.path, libFile.path, configFilePath] + firstReloadFileList: [referenceFile1.path, libFile.path, configFilePath], }); updateContentOfOpenFile(referenceFile1, referenceFile1.content + "export var yy = Foo();"); @@ -358,19 +364,19 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { const rootFolder = useSlashRootAsSomeNotRootFolderInUserDirectory ? "/user/username/rootfolder/otherfolder/" : "/"; const file1: File = { path: rootFolder + "a/b/project/file1.ts", - content: 'import a from "file2"' + content: 'import a from "file2"', }; const file2: File = { path: rootFolder + "a/b/node_modules/file2.d.ts", - content: "export class a { }" + content: "export class a { }", }; const file3: File = { path: rootFolder + "a/b/project/file3.ts", - content: "export class c { }" + content: "export class c { }", }; const configFile: File = { path: rootFolder + "a/b/project/tsconfig.json", - content: JSON.stringify({ compilerOptions: { typeRoots: [] } }) + content: JSON.stringify({ compilerOptions: { typeRoots: [] } }), }; const host = createServerHost([file1, file3, libFile, configFile]); @@ -399,18 +405,20 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { describe("when event handler is not set but session is created with canUseEvents = true", () => { describe("without noGetErrOnBackgroundUpdate, diagnostics for open files are queued", () => { - verifyProjectsUpdatedInBackgroundEvent("without noGetErrOnBackgroundUpdate", host => createSession(host, { - canUseEvents: true, - logger: createLoggerWithInMemoryLogs(host) - })); + verifyProjectsUpdatedInBackgroundEvent("without noGetErrOnBackgroundUpdate", host => + createSession(host, { + canUseEvents: true, + logger: createLoggerWithInMemoryLogs(host), + })); }); describe("with noGetErrOnBackgroundUpdate, diagnostics for open file are not queued", () => { - verifyProjectsUpdatedInBackgroundEvent("with noGetErrOnBackgroundUpdate", host => createSession(host, { - canUseEvents: true, - logger: createLoggerWithInMemoryLogs(host), - noGetErrOnBackgroundUpdate: true - })); + verifyProjectsUpdatedInBackgroundEvent("with noGetErrOnBackgroundUpdate", host => + createSession(host, { + canUseEvents: true, + logger: createLoggerWithInMemoryLogs(host), + noGetErrOnBackgroundUpdate: true, + })); }); }); }); diff --git a/src/testRunner/unittests/tsserver/exportMapCache.ts b/src/testRunner/unittests/tsserver/exportMapCache.ts index 601be84a76f4a..bcf6b3b38fd71 100644 --- a/src/testRunner/unittests/tsserver/exportMapCache.ts +++ b/src/testRunner/unittests/tsserver/exportMapCache.ts @@ -12,7 +12,7 @@ import { const packageJson: File = { path: "/package.json", - content: `{ "dependencies": { "mobx": "*" } }` + content: `{ "dependencies": { "mobx": "*" } }`, }; const aTs: File = { path: "/a.ts", @@ -28,15 +28,15 @@ const tsconfig: File = { }; const ambientDeclaration: File = { path: "/ambient.d.ts", - content: "declare module 'ambient' {}" + content: "declare module 'ambient' {}", }; const mobxPackageJson: File = { path: "/node_modules/mobx/package.json", - content: `{ "name": "mobx", "version": "1.0.0" }` + content: `{ "name": "mobx", "version": "1.0.0" }`, }; const mobxDts: File = { path: "/node_modules/mobx/index.d.ts", - content: "export declare function observable(): unknown;" + content: "export declare function observable(): unknown;", }; const exportEqualsMappedType: File = { path: "/lib/foo/constants.d.ts", @@ -120,9 +120,9 @@ describe("unittests:: tsserver:: exportMapCache", () => { newText: " ", start: { line: 1, offset: 1 }, end: { line: 1, offset: 1 }, - }] - }] - } + }], + }], + }, }); project.getLanguageService(/*ensureSynchronized*/ true); assert.notEqual(programBefore, project.getCurrentProgram()!); @@ -146,7 +146,7 @@ describe("unittests:: tsserver:: exportMapCache", () => { export abstract class Component { abstract render(): Element; - }` + }`, }; const classesTs: File = { path: "/classes.ts", @@ -154,7 +154,7 @@ describe("unittests:: tsserver:: exportMapCache", () => { export class MyComponent extends Component { render/**/ - }` + }`, }; const host = createServerHost([utilsTs, classesTs, tsconfig]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -168,7 +168,7 @@ describe("unittests:: tsserver:: exportMapCache", () => { includeCompletionsWithClassMemberSnippets: true, includeCompletionsWithInsertText: true, }, - } + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompletionInfo, @@ -179,7 +179,7 @@ describe("unittests:: tsserver:: exportMapCache", () => { prefix: "render", includeExternalModuleExports: true, includeInsertTextCompletions: true, - } + }, }); const project = projectService.configuredProjects.get(tsconfig.path)!; @@ -197,9 +197,9 @@ describe("unittests:: tsserver:: exportMapCache", () => { newText: "", start: { line: 4, offset: 22 }, end: { line: 4, offset: 23 }, - }] - }] - } + }], + }], + }, }); host.runQueuedTimeoutCallbacks(); @@ -219,7 +219,7 @@ describe("unittests:: tsserver:: exportMapCache", () => { prefix: "rende", includeExternalModuleExports: true, includeInsertTextCompletions: true, - } + }, }); baselineTsserverLogs("exportMapCache", "invalidates the cache when a file is opened with different contents", session); @@ -248,7 +248,7 @@ function setup() { ...requestLocation, includeExternalModuleExports: true, prefix: "foo", - } + }, }); } } diff --git a/src/testRunner/unittests/tsserver/extends.ts b/src/testRunner/unittests/tsserver/extends.ts index da16b435cd1d8..91676f0da2a26 100644 --- a/src/testRunner/unittests/tsserver/extends.ts +++ b/src/testRunner/unittests/tsserver/extends.ts @@ -1,4 +1,6 @@ -import { getSymlinkedExtendsSys } from "../helpers/extends"; +import { + getSymlinkedExtendsSys, +} from "../helpers/extends"; import { baselineTsserverLogs, createLoggerWithInMemoryLogs, @@ -13,4 +15,4 @@ describe("unittests:: tsserver:: extends::", () => { openFilesForSession(["/users/user/projects/myproject/src/index.ts"], session); baselineTsserverLogs("tsserver", "resolves the symlink path", session); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/externalProjects.ts b/src/testRunner/unittests/tsserver/externalProjects.ts index ff20e0c081fb1..5c6727ba5310d 100644 --- a/src/testRunner/unittests/tsserver/externalProjects.ts +++ b/src/testRunner/unittests/tsserver/externalProjects.ts @@ -25,13 +25,13 @@ describe("unittests:: tsserver:: externalProjects", () => { function verifyConfigFileCasing(lazyConfiguredProjectsFromExternalProject: boolean) { const f1 = { path: "/a/b/app.ts", - content: "let x = 1" + content: "let x = 1", }; const config = { path: "/a/b/tsconfig.json", content: JSON.stringify({ - include: [] - }) + include: [], + }), }; const host = createServerHost([f1, config], { useCaseSensitiveFileNames: false }); @@ -39,14 +39,14 @@ describe("unittests:: tsserver:: externalProjects", () => { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, arguments: { - preferences: { lazyConfiguredProjectsFromExternalProject } - } + preferences: { lazyConfiguredProjectsFromExternalProject }, + }, }); const upperCaseConfigFilePath = ts.combinePaths(ts.getDirectoryPath(config.path).toUpperCase(), ts.getBaseFileName(config.path)); openExternalProjectForSession({ projectFileName: "/a/b/project.csproj", rootFiles: toExternalFiles([f1.path, upperCaseConfigFilePath]), - options: {} + options: {}, }, session); openFilesForSession([f1], session); @@ -65,7 +65,7 @@ describe("unittests:: tsserver:: externalProjects", () => { it("load global plugins", () => { const f1 = { path: "/a/file1.ts", - content: "let x = [1, 2];" + content: "let x = [1, 2];", }; const p1 = { projectFileName: "/a/proj1.csproj", rootFiles: [toExternalFile(f1.path)], options: {} }; @@ -85,14 +85,14 @@ describe("unittests:: tsserver:: externalProjects", () => { code: 9999, length: 3, messageText: `Plugin diagnostic`, - start: 0 + start: 0, }); return prev; }; return proxy; - } + }, }), - error: undefined + error: undefined, }; }; const session = createSession(host, { globalPlugins: ["myplugin"], logger: createLoggerWithInMemoryLogs(host) }); @@ -102,8 +102,8 @@ describe("unittests:: tsserver:: externalProjects", () => { command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { file: f1.path, - projectFileName: p1.projectFileName - } + projectFileName: p1.projectFileName, + }, }); baselineTsserverLogs("externalProjects", "load global plugins", session); }); @@ -111,15 +111,15 @@ describe("unittests:: tsserver:: externalProjects", () => { it("remove not-listed external projects", () => { const f1 = { path: "/a/app.ts", - content: "let x = 1" + content: "let x = 1", }; const f2 = { path: "/b/app.ts", - content: "let x = 1" + content: "let x = 1", }; const f3 = { path: "/c/app.ts", - content: "let x = 1" + content: "let x = 1", }; const makeProject = (f: File) => ({ projectFileName: f.path + ".csproj", rootFiles: [toExternalFile(f.path)], options: {} }); const p1 = makeProject(f1); @@ -138,11 +138,11 @@ describe("unittests:: tsserver:: externalProjects", () => { it("should not close external project with no open files", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x =1;" + content: "let x =1;", }; const file2 = { path: "/a/b/f2.ts", - content: "let y =1;" + content: "let y =1;", }; const externalProjectName = "externalproject"; const host = createServerHost([file1, file2]); @@ -150,7 +150,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ rootFiles: toExternalFiles([file1.path, file2.path]), options: {}, - projectFileName: externalProjectName + projectFileName: externalProjectName, }); // open client file - should not lead to creation of inferred project projectService.openClientFile(file1.path, file1.content); @@ -168,7 +168,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ rootFiles: externalFiles, options: {}, - projectFileName: externalProjectName + projectFileName: externalProjectName, }); verifyDynamic(projectService, "/^scriptdocument1 file1.ts"); @@ -181,11 +181,11 @@ describe("unittests:: tsserver:: externalProjects", () => { it("when file name starts with ^", () => { const file: File = { path: `/user/username/projects/myproject/file.ts`, - content: "const x = 10;" + content: "const x = 10;", }; const app: File = { path: `/user/username/projects/myproject/^app.ts`, - content: "const y = 10;" + content: "const y = 10;", }; const host = createServerHost([file, app, libFile]); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -193,7 +193,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectFileName: `/user/username/projects/myproject/myproject.njsproj`, rootFiles: [ toExternalFile(file.path), - toExternalFile(app.path) + toExternalFile(app.path), ], options: {}, }]); @@ -203,33 +203,33 @@ describe("unittests:: tsserver:: externalProjects", () => { it("external project that included config files", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x =1;" + content: "let x =1;", }; const config1 = { path: "/a/b/tsconfig.json", content: JSON.stringify( { compilerOptions: {}, - files: ["f1.ts"] - } - ) + files: ["f1.ts"], + }, + ), }; const file2 = { path: "/a/c/f2.ts", - content: "let y =1;" + content: "let y =1;", }; const config2 = { path: "/a/c/tsconfig.json", content: JSON.stringify( { compilerOptions: {}, - files: ["f2.ts"] - } - ) + files: ["f2.ts"], + }, + ), }; const file3 = { path: "/a/d/f3.ts", - content: "let z =1;" + content: "let z =1;", }; const externalProjectName = "externalproject"; const host = createServerHost([file1, file2, file3, config1, config2]); @@ -237,7 +237,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ rootFiles: toExternalFiles([config1.path, config2.path, file3.path]), options: {}, - projectFileName: externalProjectName + projectFileName: externalProjectName, }); // open client file - should not lead to creation of inferred project @@ -264,11 +264,11 @@ describe("unittests:: tsserver:: externalProjects", () => { it("external project with included config file opened after configured project", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const configFile = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {} }) + content: JSON.stringify({ compilerOptions: {} }), }; const externalProjectName = "externalproject"; const host = createServerHost([file1, configFile]); @@ -279,10 +279,9 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ rootFiles: toExternalFiles([configFile.path]), options: {}, - projectFileName: externalProjectName + projectFileName: externalProjectName, }); - projectService.closeClientFile(file1.path); // configured project is alive since it is opened as part of external project @@ -293,15 +292,15 @@ describe("unittests:: tsserver:: externalProjects", () => { it("external project with included config file opened after configured project and then closed", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2 = { path: "/a/f2.ts", - content: "let x = 1" + content: "let x = 1", }; const configFile = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {} }) + content: JSON.stringify({ compilerOptions: {} }), }; const externalProjectName = "externalproject"; const host = createServerHost([file1, file2, libFile, configFile]); @@ -312,7 +311,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ rootFiles: toExternalFiles([configFile.path]), options: {}, - projectFileName: externalProjectName + projectFileName: externalProjectName, }); projectService.closeExternalProject(externalProjectName); @@ -327,11 +326,11 @@ describe("unittests:: tsserver:: externalProjects", () => { it("can correctly update external project when set of root files has changed", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1" + content: "let x = 1", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 1" + content: "let y = 1", }; const host = createServerHost([file1, file2]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -345,15 +344,15 @@ describe("unittests:: tsserver:: externalProjects", () => { it("can update external project when set of root files was not changed", () => { const file1 = { path: "/a/b/f1.ts", - content: `export * from "m"` + content: `export * from "m"`, }; const file2 = { path: "/a/b/f2.ts", - content: "export let y = 1" + content: "export let y = 1", }; const file3 = { path: "/a/m.ts", - content: "export let y = 1" + content: "export let y = 1", }; const host = createServerHost([file1, file2, file3]); @@ -368,16 +367,15 @@ describe("unittests:: tsserver:: externalProjects", () => { it("language service disabled state is updated in external projects", () => { const f1 = { path: "/a/app.js", - content: "var x = 1" + content: "var x = 1", }; const f2 = { path: "/a/largefile.js", - content: "" + content: "", }; const host = createServerHost([f1, f2]); const originalGetFileSize = host.getFileSize; - host.getFileSize = (filePath: string) => - filePath === f2.path ? ts.server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); + host.getFileSize = (filePath: string) => filePath === f2.path ? ts.server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); const projectFileName = "/a/proj.csproj"; @@ -385,21 +383,21 @@ describe("unittests:: tsserver:: externalProjects", () => { service.openExternalProject({ projectFileName, rootFiles: toExternalFiles([f1.path, f2.path]), - options: {} + options: {}, }); assert.isFalse(service.externalProjects[0].languageServiceEnabled, "language service should be disabled - 1"); service.openExternalProject({ projectFileName, rootFiles: toExternalFiles([f1.path]), - options: {} + options: {}, }); assert.isTrue(service.externalProjects[0].languageServiceEnabled, "language service should be enabled"); service.openExternalProject({ projectFileName, rootFiles: toExternalFiles([f1.path, f2.path]), - options: {} + options: {}, }); assert.isFalse(service.externalProjects[0].languageServiceEnabled, "language service should be disabled - 2"); baselineTsserverLogs("externalProjects", "language service disabled state is updated in external projects", service); @@ -409,11 +407,11 @@ describe("unittests:: tsserver:: externalProjects", () => { function verifyDeletingConfigFile(lazyConfiguredProjectsFromExternalProject: boolean) { const site = { path: "/user/someuser/project/js/site.js", - content: "" + content: "", }; const configFile = { path: "/user/someuser/project/tsconfig.json", - content: "{}" + content: "{}", }; const projectFileName = "/user/someuser/project/WebApplication6.csproj"; const host = createServerHost([libFile, site, configFile]); @@ -424,7 +422,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectFileName, rootFiles: [toExternalFile(site.path), toExternalFile(configFile.path)], options: { allowJs: false }, - typeAcquisition: { include: [] } + typeAcquisition: { include: [] }, }; projectService.openExternalProjects([externalProject]); @@ -452,15 +450,15 @@ describe("unittests:: tsserver:: externalProjects", () => { function verifyAddRemoveConfig(lazyConfiguredProjectsFromExternalProject: boolean) { const f1 = { path: "/a/b/app.ts", - content: "let x = 1;" + content: "let x = 1;", }; const f2 = { path: "/a/b/lib.ts", - content: "" + content: "", }; const tsconfig = { path: "/a/b/tsconfig.json", - content: "" + content: "", }; const host = createServerHost([f1, f2]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -471,7 +469,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ projectFileName: projectName, rootFiles: toExternalFiles([f1.path, f2.path]), - options: {} + options: {}, }); projectService.openClientFile(f1.path); @@ -480,7 +478,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ projectFileName: projectName, rootFiles: toExternalFiles([f1.path, tsconfig.path]), - options: {} + options: {}, }); if (lazyConfiguredProjectsFromExternalProject) { projectService.ensureInferredProjectsUpToDate_TestOnly(); @@ -491,7 +489,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ projectFileName: projectName, rootFiles: toExternalFiles([f1.path, f2.path]), - options: {} + options: {}, }); baselineTsserverLogs("externalProjects", `correctly handling add or remove tsconfig - 1${lazyConfiguredProjectsFromExternalProject ? " with lazyConfiguredProjectsFromExternalProject" : ""}`, projectService); } @@ -507,23 +505,23 @@ describe("unittests:: tsserver:: externalProjects", () => { function verifyAddRemoveConfig(lazyConfiguredProjectsFromExternalProject: boolean) { const f1 = { path: "/a/b/app.ts", - content: "let x = 1;" + content: "let x = 1;", }; const cLib = { path: "/a/b/c/lib.ts", - content: "" + content: "", }; const cTsconfig = { path: "/a/b/c/tsconfig.json", - content: "{}" + content: "{}", }; const dLib = { path: "/a/b/d/lib.ts", - content: "" + content: "", }; const dTsconfig = { path: "/a/b/d/tsconfig.json", - content: "{}" + content: "{}", }; const host = createServerHost([f1, cLib, cTsconfig, dLib, dTsconfig]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -534,14 +532,14 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ projectFileName: projectName, rootFiles: toExternalFiles([f1.path]), - options: {} + options: {}, }); // add two config file as root files projectService.openExternalProject({ projectFileName: projectName, rootFiles: toExternalFiles([f1.path, cTsconfig.path, dTsconfig.path]), - options: {} + options: {}, }); if (lazyConfiguredProjectsFromExternalProject) { projectService.ensureInferredProjectsUpToDate_TestOnly(); @@ -551,14 +549,14 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ projectFileName: projectName, rootFiles: toExternalFiles([f1.path, dTsconfig.path]), - options: {} + options: {}, }); // remove second config file projectService.openExternalProject({ projectFileName: projectName, rootFiles: toExternalFiles([f1.path]), - options: {} + options: {}, }); // open two config files @@ -566,7 +564,7 @@ describe("unittests:: tsserver:: externalProjects", () => { projectService.openExternalProject({ projectFileName: projectName, rootFiles: toExternalFiles([f1.path, cTsconfig.path, dTsconfig.path]), - options: {} + options: {}, }); if (lazyConfiguredProjectsFromExternalProject) { projectService.ensureInferredProjectsUpToDate_TestOnly(); @@ -588,15 +586,15 @@ describe("unittests:: tsserver:: externalProjects", () => { it("correctly handles changes in lib section of config file", () => { const libES5 = { path: "/compiler/lib.es5.d.ts", - content: "declare const eval: any" + content: "declare const eval: any", }; const libES2015Promise = { path: "/compiler/lib.es2015.promise.d.ts", - content: "declare class Promise {}" + content: "declare class Promise {}", }; const app = { path: "/src/app.ts", - content: "var x: Promise;" + content: "var x: Promise;", }; const config1 = { path: "/src/tsconfig.json", @@ -608,10 +606,11 @@ describe("unittests:: tsserver:: externalProjects", () => { noImplicitAny: true, sourceMap: false, lib: [ - "es5" - ] - } - }) + "es5", + ], + }, + }, + ), }; const config2 = { path: config1.path, @@ -624,10 +623,11 @@ describe("unittests:: tsserver:: externalProjects", () => { sourceMap: false, lib: [ "es5", - "es2015.promise" - ] - } - }) + "es2015.promise", + ], + }, + }, + ), }; const host = createServerHost([libES5, libES2015Promise, app, config1], { executingFilePath: "/compiler/tsc.js" }); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -642,7 +642,7 @@ describe("unittests:: tsserver:: externalProjects", () => { it("should handle non-existing directories in config file", () => { const f = { path: "/a/src/app.ts", - content: "let x = 1;" + content: "let x = 1;", }; const config = { path: "/a/tsconfig.json", @@ -650,9 +650,9 @@ describe("unittests:: tsserver:: externalProjects", () => { compilerOptions: {}, include: [ "src/**/*", - "notexistingfolder/*" - ] - }) + "notexistingfolder/*", + ], + }), }; const host = createServerHost([f, config]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -669,11 +669,11 @@ describe("unittests:: tsserver:: externalProjects", () => { it("handles loads existing configured projects of external projects when lazyConfiguredProjectsFromExternalProject is disabled", () => { const f1 = { path: "/a/b/app.ts", - content: "let x = 1" + content: "let x = 1", }; const config = { path: "/a/b/tsconfig.json", - content: JSON.stringify({}) + content: JSON.stringify({}), }; const projectFileName = "/a/b/project.csproj"; const host = createServerHost([f1, config]); @@ -682,7 +682,7 @@ describe("unittests:: tsserver:: externalProjects", () => { service.openExternalProject({ projectFileName, rootFiles: toExternalFiles([f1.path, config.path]), - options: {} + options: {}, } as ts.server.protocol.ExternalProject); const project = service.configuredProjects.get(config.path)!; assert.equal(project.pendingReload, ts.ConfigFileProgramReloadLevel.Full); // External project referenced configured project pending to be reloaded @@ -695,7 +695,7 @@ describe("unittests:: tsserver:: externalProjects", () => { service.openExternalProject({ projectFileName, rootFiles: toExternalFiles([f1.path, config.path]), - options: {} + options: {}, } as ts.server.protocol.ExternalProject); const project2 = service.configuredProjects.get(config.path)!; assert.equal(project2.pendingReload, ts.ConfigFileProgramReloadLevel.None); // External project referenced configured project loaded @@ -706,7 +706,7 @@ describe("unittests:: tsserver:: externalProjects", () => { const projectFileName = `/user/username/projects/myproject/WebApplication36.csproj`; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const files = [libFile, tsconfig]; const host = createServerHost(files); @@ -716,7 +716,7 @@ describe("unittests:: tsserver:: externalProjects", () => { service.openExternalProjects([{ projectFileName, rootFiles: [{ fileName: tsconfig.path }], - options: { allowJs: false } + options: { allowJs: false }, }]); // write js file, open external project and open it for edit @@ -725,14 +725,14 @@ describe("unittests:: tsserver:: externalProjects", () => { service.openExternalProjects([{ projectFileName, rootFiles: [{ fileName: tsconfig.path }, { fileName: jsFilePath }], - options: { allowJs: false } + options: { allowJs: false }, }]); service.applyChangesInOpenFiles(ts.singleIterator({ fileName: jsFilePath, scriptKind: ts.ScriptKind.JS, content: "" })); // write jsconfig file const jsConfig: File = { path: `/user/username/projects/myproject/jsconfig.json`, - content: "{}" + content: "{}", }; // Dont invoke file creation watchers as the repro suggests host.ensureFileOrFolder(jsConfig, /*ignoreWatchInvokedWithTriggerAsFileCreate*/ true); @@ -741,7 +741,7 @@ describe("unittests:: tsserver:: externalProjects", () => { service.openExternalProjects([{ projectFileName, rootFiles: [{ fileName: jsConfig.path }, { fileName: tsconfig.path }, { fileName: jsFilePath }], - options: { allowJs: false } + options: { allowJs: false }, }]); logInferredProjectsOrphanStatus(service); baselineTsserverLogs("externalProjects", "handles creation of external project with jsconfig before jsconfig creation watcher is invoked", service); diff --git a/src/testRunner/unittests/tsserver/findAllReferences.ts b/src/testRunner/unittests/tsserver/findAllReferences.ts index 85b1b4b05fcaa..e194b58fe7bb1 100644 --- a/src/testRunner/unittests/tsserver/findAllReferences.ts +++ b/src/testRunner/unittests/tsserver/findAllReferences.ts @@ -1,14 +1,22 @@ -import { protocol } from "../../_namespaces/ts.server"; -import { baselineTsserverLogs, createLoggerWithInMemoryLogs, createSession } from "../helpers/tsserver"; -import { createServerHost, File } from "../helpers/virtualFileSystemWithWatch"; +import { + protocol, +} from "../../_namespaces/ts.server"; +import { + baselineTsserverLogs, + createLoggerWithInMemoryLogs, + createSession, +} from "../helpers/tsserver"; +import { + createServerHost, + File, +} from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: services:: findAllReferences", () => { it("does not try to open a file in a project that was updated and no longer has the file", () => { const files: File[] = [ { path: "/packages/babel-loader/tsconfig.json", - content: -` + content: ` { "compilerOptions": { "target": "ES2018", @@ -22,19 +30,17 @@ describe("unittests:: services:: findAllReferences", () => { "include": ["src"], "references": [{"path": "../core"}] } -` +`, }, { path: "/packages/babel-loader/src/index.ts", - content: -` + content: ` import type { Foo } from "../../core/src/index.js"; -` +`, }, { path: "/packages/core/tsconfig.json", - content: -` + content: ` { "compilerOptions": { "target": "ES2018", @@ -47,30 +53,28 @@ import type { Foo } from "../../core/src/index.js"; }, "include": ["./src"] } -` +`, }, { path: "/packages/core/src/index.ts", - content: -` + content: ` import { Bar } from "./loading-indicator.js"; export type Foo = {}; const bar: Bar = { prop: 0 } -` +`, }, { path: "/packages/core/src/loading-indicator.ts", - content: -` + content: ` export interface Bar { prop: number; } const bar: Bar = { prop: 1 } -` +`, }, ]; const host = createServerHost(files); @@ -83,9 +87,9 @@ const bar: Bar = { { file: files[1].path, // babel-loader/src/index.ts fileContent: files[1].content, - } - ] - } + }, + ], + }, }); session.executeCommandSeq({ command: protocol.CommandTypes.UpdateOpen, @@ -94,9 +98,9 @@ const bar: Bar = { { file: files[3].path, // core/src/index.ts fileContent: files[3].content, - } - ] - } + }, + ], + }, }); // Now change `babel-loader` project to no longer import `core` project session.executeCommandSeq({ @@ -109,18 +113,18 @@ const bar: Bar = { { start: { line: 1, - offset: 26 + offset: 26, }, end: { line: 1, - offset: 26 + offset: 26, }, newText: "// comment", - } - ] - } - ] - } + }, + ], + }, + ], + }, }); const loadingIndicatorScriptInfo = session.getProjectService().getScriptInfo(files[3].path)!; // At this point, we haven't updated `babel-loader` project yet, @@ -132,9 +136,9 @@ const bar: Bar = { command: protocol.CommandTypes.References, arguments: { file: files[3].path, // core/src/index.ts - line: 5, // `prop` + line: 5, // `prop` offset: 5, - } + }, }); baselineTsserverLogs("findAllReferences", "does not try to open a file in a project that was updated and no longer has the file", session); }); diff --git a/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts b/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts index 6dbfe687f421e..2ef7a891b2afc 100644 --- a/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts +++ b/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts @@ -52,8 +52,8 @@ describe("unittests:: tsserver:: forceConsistentCasingInFileNames", () => { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompilerOptionsDiagnosticsFull, arguments: { - projectFileName: tsconfig.path - } + projectFileName: tsconfig.path, + }, }); baselineTsserverLogs("forceConsistentCasingInFileNames", "works when extends is specified with a case insensitive file system", session); }); @@ -61,17 +61,17 @@ describe("unittests:: tsserver:: forceConsistentCasingInFileNames", () => { it("works when renaming file with different casing", () => { const loggerFile: File = { path: `/user/username/projects/myproject/Logger.ts`, - content: `export class logger { }` + content: `export class logger { }`, }; const anotherFile: File = { path: `/user/username/projects/myproject/another.ts`, - content: `import { logger } from "./Logger"; new logger();` + content: `import { logger } from "./Logger"; new logger();`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ - compilerOptions: { forceConsistentCasingInFileNames: true } - }) + compilerOptions: { forceConsistentCasingInFileNames: true }, + }), }; const host = createServerHost([loggerFile, anotherFile, tsconfig, libFile, tsconfig]); @@ -95,11 +95,11 @@ describe("unittests:: tsserver:: forceConsistentCasingInFileNames", () => { newText: "./logger", ...protocolTextSpanFromSubstring( anotherFile.content, - "./Logger" - ) - }] - }] - } + "./Logger", + ), + }], + }], + }, }); // Check errors in both files @@ -110,17 +110,17 @@ describe("unittests:: tsserver:: forceConsistentCasingInFileNames", () => { it("when changing module name with different casing", () => { const loggerFile: File = { path: `/user/username/projects/myproject/Logger.ts`, - content: `export class logger { }` + content: `export class logger { }`, }; const anotherFile: File = { path: `/user/username/projects/myproject/another.ts`, - content: `import { logger } from "./Logger"; new logger();` + content: `import { logger } from "./Logger"; new logger();`, }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ - compilerOptions: { forceConsistentCasingInFileNames: true } - }) + compilerOptions: { forceConsistentCasingInFileNames: true }, + }), }; const host = createServerHost([loggerFile, anotherFile, tsconfig, libFile, tsconfig]); @@ -137,11 +137,11 @@ describe("unittests:: tsserver:: forceConsistentCasingInFileNames", () => { newText: "./logger", ...protocolTextSpanFromSubstring( anotherFile.content, - "./Logger" - ) - }] - }] - } + "./Logger", + ), + }], + }], + }, }); // Check errors in both files diff --git a/src/testRunner/unittests/tsserver/formatSettings.ts b/src/testRunner/unittests/tsserver/formatSettings.ts index 2978804b91d8a..a0d55ac41a5ed 100644 --- a/src/testRunner/unittests/tsserver/formatSettings.ts +++ b/src/testRunner/unittests/tsserver/formatSettings.ts @@ -1,12 +1,19 @@ import * as ts from "../../_namespaces/ts"; -import { baselineTsserverLogs, createLoggerWithInMemoryLogs, createSession, openFilesForSession } from "../helpers/tsserver"; -import { createServerHost } from "../helpers/virtualFileSystemWithWatch"; +import { + baselineTsserverLogs, + createLoggerWithInMemoryLogs, + createSession, + openFilesForSession, +} from "../helpers/tsserver"; +import { + createServerHost, +} from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: tsserver:: formatSettings", () => { it("can be set globally", () => { const f1 = { path: "/a/b/app.ts", - content: "let x;" + content: "let x;", }; const host = createServerHost([f1]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -18,7 +25,7 @@ describe("unittests:: tsserver:: formatSettings", () => { const newGlobalSettings1 = { ...defaultSettings, placeOpenBraceOnNewLineForControlBlocks: !defaultSettings.placeOpenBraceOnNewLineForControlBlocks }; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { formatOptions: newGlobalSettings1 } + arguments: { formatOptions: newGlobalSettings1 }, }); // get format options for file - should be equal to new global settings @@ -28,7 +35,7 @@ describe("unittests:: tsserver:: formatSettings", () => { const newPerFileSettings = { ...defaultSettings, insertSpaceAfterCommaDelimiter: !defaultSettings.insertSpaceAfterCommaDelimiter }; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { formatOptions: newPerFileSettings, file: f1.path } + arguments: { formatOptions: newPerFileSettings, file: f1.path }, }); // get format options for file - should be equal to new per-file settings @@ -38,7 +45,7 @@ describe("unittests:: tsserver:: formatSettings", () => { const newGlobalSettings2 = { ...defaultSettings, insertSpaceAfterSemicolonInForStatements: !defaultSettings.insertSpaceAfterSemicolonInForStatements }; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { formatOptions: newGlobalSettings2 } + arguments: { formatOptions: newGlobalSettings2 }, }); // get format options for file - should be equal to new per-file settings diff --git a/src/testRunner/unittests/tsserver/getApplicableRefactors.ts b/src/testRunner/unittests/tsserver/getApplicableRefactors.ts index 793ee5cfd0979..03ed1542cfb8f 100644 --- a/src/testRunner/unittests/tsserver/getApplicableRefactors.ts +++ b/src/testRunner/unittests/tsserver/getApplicableRefactors.ts @@ -18,7 +18,7 @@ describe("unittests:: tsserver:: getApplicableRefactors", () => { openFilesForSession([aTs], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetApplicableRefactors, - arguments: { file: aTs.path, line: 1, offset: 1 } + arguments: { file: aTs.path, line: 1, offset: 1 }, }); baselineTsserverLogs("getApplicableRefactors", "works when taking position", session); }); diff --git a/src/testRunner/unittests/tsserver/getEditsForFileRename.ts b/src/testRunner/unittests/tsserver/getEditsForFileRename.ts index e9e717cce003b..d7ebe9570845b 100644 --- a/src/testRunner/unittests/tsserver/getEditsForFileRename.ts +++ b/src/testRunner/unittests/tsserver/getEditsForFileRename.ts @@ -86,7 +86,7 @@ describe("unittests:: tsserver:: getEditsForFileRename", () => { arguments: { oldFilePath: aOldTs.path, newFilePath: "/a/new.ts", - } + }, }); baselineTsserverLogs("getEditsForFileRename", "works with multiple projects", session); }); @@ -105,7 +105,7 @@ describe("unittests:: tsserver:: getEditsForFileRename", () => { arguments: { oldFilePath: "/b.ts", newFilePath: cTs.path, - } + }, }); baselineTsserverLogs("getEditsForFileRename", "works with file moved to inferred project", session); }); diff --git a/src/testRunner/unittests/tsserver/getFileReferences.ts b/src/testRunner/unittests/tsserver/getFileReferences.ts index 147f9091c3f1d..057ab0dcb2240 100644 --- a/src/testRunner/unittests/tsserver/getFileReferences.ts +++ b/src/testRunner/unittests/tsserver/getFileReferences.ts @@ -26,11 +26,11 @@ describe("unittests:: tsserver:: getFileReferences", () => { }; const cTs: File = { path: "/project/c.ts", - content: importCurlyFromA + content: importCurlyFromA, }; const dTs: File = { path: "/project/d.ts", - content: [importAFromA, typeofImportA].join("\n") + content: [importAFromA, typeofImportA].join("\n"), }; const tsconfig: File = { path: "/project/tsconfig.json", @@ -59,8 +59,8 @@ describe("unittests:: tsserver:: getFileReferences", () => { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, arguments: { - preferences: { disableLineTextInReferences: true } - } + preferences: { disableLineTextInReferences: true }, + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.FileReferences, diff --git a/src/testRunner/unittests/tsserver/getMoveToRefactoringFileSuggestions.ts b/src/testRunner/unittests/tsserver/getMoveToRefactoringFileSuggestions.ts index e70ab769cb052..67aa8b3f9d353 100644 --- a/src/testRunner/unittests/tsserver/getMoveToRefactoringFileSuggestions.ts +++ b/src/testRunner/unittests/tsserver/getMoveToRefactoringFileSuggestions.ts @@ -3,11 +3,11 @@ import { baselineTsserverLogs, createLoggerWithInMemoryLogs, createSession, - openFilesForSession + openFilesForSession, } from "../helpers/tsserver"; import { createServerHost, - File + File, } from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: tsserver:: getMoveToRefactoringFileSuggestions", () => { @@ -17,22 +17,22 @@ describe("unittests:: tsserver:: getMoveToRefactoringFileSuggestions", () => { content: `interface ka { name: string; } - ` + `, }; const file2: File = { path: "/project/b/file2.ts", content: "" }; const file3: File = { path: "/project/d/e/file3.ts", content: "" }; const file4: File = { path: "/project/a/file4.ts", content: `import { value } from "../node_modules/@types/node/someFile.d.ts"; -import { value1 } from "../node_modules/.cache/someFile.d.ts";` +import { value1 } from "../node_modules/.cache/someFile.d.ts";`, }; const nodeModulesFile1: File = { path: "project/node_modules/@types/node/someFile.d.ts", - content: `export const value = 0;` + content: `export const value = 0;`, }; const nodeModulesFile2: File = { path: "project/node_modules/.cache/someFile.d.ts", - content: `export const value1 = 0;` + content: `export const value1 = 0;`, }; const tsconfig: File = { path: "/project/tsconfig.json", @@ -43,7 +43,7 @@ import { value1 } from "../node_modules/.cache/someFile.d.ts";` openFilesForSession([file1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetMoveToRefactoringFileSuggestions, - arguments: { file: file1.path, line: 1, offset: 11 } + arguments: { file: file1.path, line: 1, offset: 11 }, }); baselineTsserverLogs("getMoveToRefactoringFileSuggestions", "works for suggesting a list of files, excluding node_modules within a project", session); }); @@ -53,7 +53,7 @@ import { value1 } from "../node_modules/.cache/someFile.d.ts";` content: `interface ka { name: string; } - ` + `, }; const file2: File = { path: "/file2.tsx", content: "" }; const file3: File = { path: "/file3.mts", content: "" }; @@ -69,14 +69,14 @@ import { value1 } from "../node_modules/.cache/someFile.d.ts";` session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetMoveToRefactoringFileSuggestions, - arguments: { file: file1.path, line: 1, offset: 11 } + arguments: { file: file1.path, line: 1, offset: 11 }, }); baselineTsserverLogs("getMoveToRefactoringFileSuggestions", "suggests only .ts file for a .ts filepath", session); }); it("suggests only .js file for a .js filepath", () => { const file1: File = { path: "/file1.js", - content: `class C {}` + content: `class C {}`, }; const file2: File = { path: "/file2.js", content: "" }; const file3: File = { path: "/file3.mts", content: "" }; @@ -90,14 +90,14 @@ import { value1 } from "../node_modules/.cache/someFile.d.ts";` session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetMoveToRefactoringFileSuggestions, - arguments: { file: file1.path, line: 1, offset: 7 } + arguments: { file: file1.path, line: 1, offset: 7 }, }); baselineTsserverLogs("getMoveToRefactoringFileSuggestions", "suggests only .js file for a .js filepath", session); }); it("skips lib.d.ts files", () => { const file1: File = { path: "/file1.d.ts", - content: `class C {}` + content: `class C {}`, }; const file2: File = { path: "/a/lib.d.ts", content: "" }; const file3: File = { path: "/a/file3.d.ts", content: "" }; @@ -110,8 +110,8 @@ import { value1 } from "../node_modules/.cache/someFile.d.ts";` session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetMoveToRefactoringFileSuggestions, - arguments: { file: file1.path, line: 1, offset: 7 } + arguments: { file: file1.path, line: 1, offset: 7 }, }); baselineTsserverLogs("getMoveToRefactoringFileSuggestions", "skips lib.d.ts files", session); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/goToDefinition.ts b/src/testRunner/unittests/tsserver/goToDefinition.ts index 852fc7d5588b3..f078d677694e3 100644 --- a/src/testRunner/unittests/tsserver/goToDefinition.ts +++ b/src/testRunner/unittests/tsserver/goToDefinition.ts @@ -1,14 +1,22 @@ -import { protocol } from "../../_namespaces/ts.server"; -import { baselineTsserverLogs, createLoggerWithInMemoryLogs, createSession } from "../helpers/tsserver"; -import { createServerHost, File } from "../helpers/virtualFileSystemWithWatch"; +import { + protocol, +} from "../../_namespaces/ts.server"; +import { + baselineTsserverLogs, + createLoggerWithInMemoryLogs, + createSession, +} from "../helpers/tsserver"; +import { + createServerHost, + File, +} from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: services:: goToDefinition", () => { it("does not issue errors on jsdoc in TS", () => { const files: File[] = [ { path: "/packages/babel-loader/tsconfig.json", - content: - ` + content: ` { "compilerOptions": { "target": "ES2018", @@ -20,19 +28,18 @@ describe("unittests:: services:: goToDefinition", () => { }, "include": ["src"], } -` +`, }, { path: "/packages/babel-loader/src/index.ts", - content: - ` + content: ` declare class Stuff { /** For more thorough tests, use {@link checkFooIs} */ checkFooLengthIs(len: number): void; checkFooIs(value: object): void; } -` +`, }, ]; const host = createServerHost(files); @@ -45,9 +52,9 @@ declare class Stuff { { file: files[1].path, // babel-loader/src/index.ts fileContent: files[1].content, - } - ] - } + }, + ], + }, }); session.executeCommandSeq({ command: protocol.CommandTypes.Definition, @@ -62,17 +69,15 @@ declare class Stuff { command: protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { file: "/packages/babel-loader/src/index.ts", - } + }, }); baselineTsserverLogs("goToDefinition", "does not issue errors on jsdoc in TS", session); - }); it("does not issue errors on jsdoc in TS", () => { const files: File[] = [ { path: "/packages/babel-loader/tsconfig.json", - content: - ` + content: ` { "compilerOptions": { "target": "ES2018", @@ -84,12 +89,11 @@ declare class Stuff { }, "include": ["src"], } -` +`, }, { path: "/packages/babel-loader/src/index.ts", - content: - ` + content: ` declare class Stuff { /** * Register a function to be run on mod initialization... @@ -102,7 +106,7 @@ declare class Stuff { */ on_init(f: (() => void) | undefined): void } -` +`, }, ]; const host = createServerHost(files); @@ -115,9 +119,9 @@ declare class Stuff { { file: files[1].path, // babel-loader/src/index.ts fileContent: files[1].content, - } - ] - } + }, + ], + }, }); session.executeCommandSeq({ command: protocol.CommandTypes.Definition, @@ -132,9 +136,8 @@ declare class Stuff { command: protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { file: "/packages/babel-loader/src/index.ts", - } + }, }); baselineTsserverLogs("goToDefinition", "does not issue errors on jsdoc in TS2", session); - }); }); diff --git a/src/testRunner/unittests/tsserver/importHelpers.ts b/src/testRunner/unittests/tsserver/importHelpers.ts index cad9e1c491552..ad355231c2593 100644 --- a/src/testRunner/unittests/tsserver/importHelpers.ts +++ b/src/testRunner/unittests/tsserver/importHelpers.ts @@ -5,17 +5,19 @@ import { openExternalProjectForSession, toExternalFile, } from "../helpers/tsserver"; -import { createServerHost } from "../helpers/virtualFileSystemWithWatch"; +import { + createServerHost, +} from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: tsserver:: importHelpers", () => { it("should not crash in tsserver", () => { const f1 = { path: "/a/app.ts", - content: "export async function foo() { return 100; }" + content: "export async function foo() { return 100; }", }; const tslib = { path: "/a/node_modules/tslib/index.d.ts", - content: "" + content: "", }; const host = createServerHost([f1, tslib]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); diff --git a/src/testRunner/unittests/tsserver/inconsistentErrorInEditor.ts b/src/testRunner/unittests/tsserver/inconsistentErrorInEditor.ts index fdee92a017186..3a80c1437731d 100644 --- a/src/testRunner/unittests/tsserver/inconsistentErrorInEditor.ts +++ b/src/testRunner/unittests/tsserver/inconsistentErrorInEditor.ts @@ -21,10 +21,10 @@ describe("unittests:: tsserver:: inconsistentErrorInEditor", () => { { file: "^/untitled/ts-nul-authority/Untitled-1", fileContent: "export function foo() {\r\n /*$*/return bar;\r\n}\r\n\r\nexport function bar(x: T) {\r\n return x;\r\n}\r\n\r\nlet x = foo()(42);", - scriptKindName: "TS" - } - ] - } + scriptKindName: "TS", + }, + ], + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EncodedSemanticClassificationsFull, @@ -32,8 +32,8 @@ describe("unittests:: tsserver:: inconsistentErrorInEditor", () => { file: "^/untitled/ts-nul-authority/Untitled-1", start: 0, length: 128, - format: "2020" - } + format: "2020", + }, }); verifyGetErrRequest({ session, files: ["^/untitled/ts-nul-authority/Untitled-1"] }); baselineTsserverLogs("inconsistentErrorInEditor", "should not error", session); @@ -53,10 +53,10 @@ describe("unittests:: tsserver:: inconsistentErrorInEditor2", () => { { file: "^/untitled/ts-nul-authority/Untitled-1", fileContent: "function fn(Foo: number) {\r\n type Foo = typeof Foo;\r\n return 0 as any as {x: Foo};\r\n}", - scriptKindName: "TS" - } - ] - } + scriptKindName: "TS", + }, + ], + }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EncodedSemanticClassificationsFull, @@ -64,8 +64,8 @@ describe("unittests:: tsserver:: inconsistentErrorInEditor2", () => { file: "^/untitled/ts-nul-authority/Untitled-1", start: 0, length: 128, - format: "2020" - } + format: "2020", + }, }); verifyGetErrRequest({ session, files: ["^/untitled/ts-nul-authority/Untitled-1"] }); baselineTsserverLogs("inconsistentErrorInEditor2", "should not error", session); diff --git a/src/testRunner/unittests/tsserver/inferredProjects.ts b/src/testRunner/unittests/tsserver/inferredProjects.ts index abe55289e5222..70582bc098712 100644 --- a/src/testRunner/unittests/tsserver/inferredProjects.ts +++ b/src/testRunner/unittests/tsserver/inferredProjects.ts @@ -1,5 +1,7 @@ import * as ts from "../../_namespaces/ts"; -import { commonFile1 } from "../helpers/tscWatch"; +import { + commonFile1, +} from "../helpers/tscWatch"; import { baselineTsserverLogs, closeFilesForSession, @@ -23,12 +25,12 @@ describe("unittests:: tsserver:: inferredProjects", () => { content: ` import {f} from "./module" console.log(f) - ` + `, }; const moduleFile: File = { path: `/user/username/projects/myproject/module.d.ts`, - content: `export let x: number` + content: `export let x: number`, }; const host = createServerHost([appFile, moduleFile, libFile]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -39,7 +41,7 @@ describe("unittests:: tsserver:: inferredProjects", () => { it("should use only one inferred project if 'useOneInferredProject' is set", () => { const file1 = { path: `/user/username/projects/myproject/a/b/main.ts`, - content: "let x =1;" + content: "let x =1;", }; const configFile: File = { path: `/user/username/projects/myproject/a/b/tsconfig.json`, @@ -48,16 +50,16 @@ describe("unittests:: tsserver:: inferredProjects", () => { "target": "es6" }, "files": [ "main.ts" ] - }` + }`, }; const file2 = { path: `/user/username/projects/myproject/a/c/main.ts`, - content: "let x =1;" + content: "let x =1;", }; const file3 = { path: `/user/username/projects/myproject/a/d/main.ts`, - content: "let x =1;" + content: "let x =1;", }; const host = createServerHost([file1, file2, file3, libFile]); @@ -74,7 +76,7 @@ describe("unittests:: tsserver:: inferredProjects", () => { it("disable inferred project", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x =1;" + content: "let x =1;", }; const host = createServerHost([file1]); @@ -89,11 +91,11 @@ describe("unittests:: tsserver:: inferredProjects", () => { it("project settings for inferred projects", () => { const file1 = { path: "/a/b/app.ts", - content: `import {x} from "mod"` + content: `import {x} from "mod"`, }; const modFile = { path: "/a/mod.ts", - content: "export let x: number" + content: "export let x: number", }; const host = createServerHost([file1, modFile]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -109,7 +111,7 @@ describe("unittests:: tsserver:: inferredProjects", () => { it("should support files without extensions", () => { const f = { path: "/a/compile", - content: "let x = 1" + content: "let x = 1", }; const host = createServerHost([f]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -127,41 +129,41 @@ describe("unittests:: tsserver:: inferredProjects", () => { const session = createSession(host, { useSingleInferredProject: true, useInferredProjectPerProjectRoot: true, - logger: createLoggerWithInMemoryLogs(host) + logger: createLoggerWithInMemoryLogs(host), }); setCompilerOptionsForInferredProjectsRequestForSession({ allowJs: true, - target: ts.ScriptTarget.ESNext + target: ts.ScriptTarget.ESNext, }, session); setCompilerOptionsForInferredProjectsRequestForSession({ options: { allowJs: true, - target: ts.ScriptTarget.ES2015 + target: ts.ScriptTarget.ES2015, }, - projectRootPath: "/b" + projectRootPath: "/b", }, session); openFilesForSession([{ file: file1.path, content: file1.content, scriptKindName: "JS", - projectRootPath: file1.projectRootPath + projectRootPath: file1.projectRootPath, }], session); openFilesForSession([{ file: file2.path, content: file2.content, scriptKindName: "JS", - projectRootPath: file2.projectRootPath + projectRootPath: file2.projectRootPath, }], session); openFilesForSession([{ file: file3.path, content: file3.content, scriptKindName: "JS", - projectRootPath: file3.projectRootPath + projectRootPath: file3.projectRootPath, }], session); openFilesForSession([{ file: file4.path, content: file4.content, - scriptKindName: "JS" + scriptKindName: "JS", }], session); const projectService = session.getProjectService(); @@ -177,20 +179,20 @@ describe("unittests:: tsserver:: inferredProjects", () => { { path: "/a/file1.ts", content: "let x = 1;" }, { path: "/A/file2.ts", content: "let y = 2;" }, { path: "/b/file2.ts", content: "let x = 3;" }, - { path: "/c/file3.ts", content: "let z = 4;" } + { path: "/c/file3.ts", content: "let z = 4;" }, ]; const host = createServerHost(files, { useCaseSensitiveFileNames }); const session = createSession(host, { useSingleInferredProject: true, useInferredProjectPerProjectRoot: true, logger: createLoggerWithInMemoryLogs(host) }); setCompilerOptionsForInferredProjectsRequestForSession({ allowJs: true, - target: ts.ScriptTarget.ESNext + target: ts.ScriptTarget.ESNext, }, session); setCompilerOptionsForInferredProjectsRequestForSession({ options: { allowJs: true, - target: ts.ScriptTarget.ES2015 + target: ts.ScriptTarget.ES2015, }, - projectRootPath: "/a" + projectRootPath: "/a", }, session); openClientFiles(["/a", "/a", "/b", undefined]); @@ -202,9 +204,9 @@ describe("unittests:: tsserver:: inferredProjects", () => { setCompilerOptionsForInferredProjectsRequestForSession({ options: { allowJs: true, - target: ts.ScriptTarget.ES2017 + target: ts.ScriptTarget.ES2017, }, - projectRootPath: "/A" + projectRootPath: "/A", }, session); openClientFiles(["/a", "/a", "/b", undefined]); @@ -215,9 +217,7 @@ describe("unittests:: tsserver:: inferredProjects", () => { baselineTsserverLogs("inferredProjects", subScenario, session); function openClientFiles(projectRoots: [string | undefined, string | undefined, string | undefined, string | undefined]) { - files.forEach((file, index) => - openFilesForSession([{ file: file.path, content: file.content, scriptKindName: "JS", projectRootPath: projectRoots[index] }], session) - ); + files.forEach((file, index) => openFilesForSession([{ file: file.path, content: file.content, scriptKindName: "JS", projectRootPath: projectRoots[index] }], session)); } function closeClientFiles() { @@ -232,19 +232,19 @@ describe("unittests:: tsserver:: inferredProjects", () => { it("should still retain configured project created while opening the file", () => { const appFile: File = { path: `/user/username/projects/myproject/app.ts`, - content: `const app = 20;` + content: `const app = 20;`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const jsFile1: File = { path: `/user/username/projects/myproject/jsFile1.js`, - content: `const jsFile1 = 10;` + content: `const jsFile1 = 10;`, }; const jsFile2: File = { path: `/user/username/projects/myproject/jsFile2.js`, - content: `const jsFile2 = 10;` + content: `const jsFile2 = 10;`, }; const host = createServerHost([appFile, libFile, config, jsFile1, jsFile2]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -284,7 +284,7 @@ describe("unittests:: tsserver:: inferredProjects", () => { const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); setCompilerOptionsForInferredProjectsRequestForSession({ allowJs: true, - target: ts.ScriptTarget.ES2015 + target: ts.ScriptTarget.ES2015, }, session); session.testhost.logTimeoutQueueLength(); baselineTsserverLogs("inferredProjects", "Setting compiler options for inferred projects when there are no open files should not schedule any refresh", session); diff --git a/src/testRunner/unittests/tsserver/inlayHints.ts b/src/testRunner/unittests/tsserver/inlayHints.ts index 375393932892b..b2c7e0a3d1a5d 100644 --- a/src/testRunner/unittests/tsserver/inlayHints.ts +++ b/src/testRunner/unittests/tsserver/inlayHints.ts @@ -18,11 +18,11 @@ import { describe("unittests:: tsserver:: inlayHints", () => { const configFile: File = { path: "/a/b/tsconfig.json", - content: "{}" + content: "{}", }; const app: File = { path: "/a/b/app.ts", - content: "declare function foo(param: any): void;\nfoo(12);" + content: "declare function foo(param: any): void;\nfoo(12);", }; it("with updateOpen request does not corrupt documents", () => { @@ -30,29 +30,29 @@ describe("unittests:: tsserver:: inlayHints", () => { const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Open, - arguments: { file: app.path } + arguments: { file: app.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, arguments: { preferences: { - includeInlayParameterNameHints: "all" - } as ts.UserPreferences - } + includeInlayParameterNameHints: "all", + } as ts.UserPreferences, + }, }); verifyInlayHintResponse(session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.UpdateOpen, arguments: { - changedFiles: [{ fileName: app.path, textChanges: [{ start: { line: 1, offset: 39 }, end: { line: 1, offset: 39 }, newText: "//" }] }] - } + changedFiles: [{ fileName: app.path, textChanges: [{ start: { line: 1, offset: 39 }, end: { line: 1, offset: 39 }, newText: "//" }] }], + }, }); verifyInlayHintResponse(session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.UpdateOpen, arguments: { - changedFiles: [{ fileName: app.path, textChanges: [{ start: { line: 1, offset: 41 }, end: { line: 1, offset: 41 }, newText: "c" }] }] - } + changedFiles: [{ fileName: app.path, textChanges: [{ start: { line: 1, offset: 41 }, end: { line: 1, offset: 41 }, newText: "c" }] }], + }, }); verifyInlayHintResponse(session); baselineTsserverLogs("inlayHints", "with updateOpen request does not corrupt documents", session); @@ -64,7 +64,7 @@ describe("unittests:: tsserver:: inlayHints", () => { file: app.path, start: 0, length: app.content.length, - } + }, }); } }); diff --git a/src/testRunner/unittests/tsserver/jsdocTag.ts b/src/testRunner/unittests/tsserver/jsdocTag.ts index 1c1ffd51a1003..b3023da35d8b9 100644 --- a/src/testRunner/unittests/tsserver/jsdocTag.ts +++ b/src/testRunner/unittests/tsserver/jsdocTag.ts @@ -20,11 +20,11 @@ describe("unittests:: tsserver:: jsdocTag:: jsdoc @link ", () => { } "files": ["someFile1.js"] } -` +`, }; function assertQuickInfoJSDoc(subScenario: string, file: File, options: { - displayPartsForJSDoc: boolean, - command: ts.server.protocol.CommandTypes, + displayPartsForJSDoc: boolean; + command: ts.server.protocol.CommandTypes; }) { it(subScenario, () => { const { command, displayPartsForJSDoc } = options; @@ -32,7 +32,7 @@ describe("unittests:: tsserver:: jsdocTag:: jsdoc @link ", () => { const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { preferences: { displayPartsForJSDoc } } + arguments: { preferences: { displayPartsForJSDoc } }, }); openFilesForSession([file], session); const indexOfX = file.content.indexOf("x"); @@ -41,7 +41,7 @@ describe("unittests:: tsserver:: jsdocTag:: jsdoc @link ", () => { arguments: { file: file.path, position: indexOfX, - } as ts.server.protocol.FileLocationRequestArgs + } as ts.server.protocol.FileLocationRequestArgs, }); baselineTsserverLogs("jsdocTag", subScenario, session); }); @@ -51,14 +51,14 @@ describe("unittests:: tsserver:: jsdocTag:: jsdoc @link ", () => { path: "/a/someFile1.js", content: `class C { } /** @wat {@link C} */ -var x = 1` +var x = 1`, }; const linkInComment: File = { path: "/a/someFile1.js", content: `class C { } /** {@link C} */ var x = 1 -;` +;`, }; assertQuickInfoJSDoc("for quickinfo, should provide display parts plus a span for a working link in a tag", linkInTag, { @@ -102,8 +102,8 @@ var x = 1 }); function assertSignatureHelpJSDoc(subScenario: string, options: { - displayPartsForJSDoc: boolean, - command: ts.server.protocol.CommandTypes, + displayPartsForJSDoc: boolean; + command: ts.server.protocol.CommandTypes; }) { it(subScenario, () => { const linkInParamTag: File = { @@ -111,7 +111,7 @@ var x = 1 content: `class C { } /** @param y - {@link C} */ function x(y) { } -x(1)` +x(1)`, }; const { command, displayPartsForJSDoc } = options; @@ -119,7 +119,7 @@ x(1)` const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { preferences: { displayPartsForJSDoc } } + arguments: { preferences: { displayPartsForJSDoc } }, }); openFilesForSession([linkInParamTag], session); const indexOfX = linkInParamTag.content.lastIndexOf("1"); @@ -127,11 +127,11 @@ x(1)` command: command as ts.server.protocol.CommandTypes.SignatureHelp, arguments: { triggerReason: { - kind: "invoked" + kind: "invoked", }, file: linkInParamTag.path, position: indexOfX, - } as ts.server.protocol.SignatureHelpRequestArgs + } as ts.server.protocol.SignatureHelpRequestArgs, }); baselineTsserverLogs("jsdocTag", subScenario, session); }); @@ -156,8 +156,8 @@ x(1)` }); function assertCompletionsJSDoc(subScenario: string, options: { - displayPartsForJSDoc: boolean, - command: ts.server.protocol.CommandTypes, + displayPartsForJSDoc: boolean; + command: ts.server.protocol.CommandTypes; }) { it(subScenario, () => { const linkInParamJSDoc: File = { @@ -165,14 +165,14 @@ x(1)` content: `class C { } /** @param x - see {@link C} */ function foo (x) { } -foo` +foo`, }; const { command, displayPartsForJSDoc } = options; const host = createServerHost([linkInParamJSDoc, config]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { preferences: { displayPartsForJSDoc } } + arguments: { preferences: { displayPartsForJSDoc } }, }); openFilesForSession([linkInParamJSDoc], session); const indexOfFoo = linkInParamJSDoc.content.lastIndexOf("fo"); @@ -182,7 +182,7 @@ foo` entryNames: ["foo"], file: linkInParamJSDoc.path, position: indexOfFoo, - } as ts.server.protocol.CompletionDetailsRequestArgs + } as ts.server.protocol.CompletionDetailsRequestArgs, }); baselineTsserverLogs("jsdocTag", subScenario, session); }); diff --git a/src/testRunner/unittests/tsserver/languageService.ts b/src/testRunner/unittests/tsserver/languageService.ts index ae95669213adb..b7f3646716c7f 100644 --- a/src/testRunner/unittests/tsserver/languageService.ts +++ b/src/testRunner/unittests/tsserver/languageService.ts @@ -1,16 +1,23 @@ import * as Utils from "../../_namespaces/Utils"; -import { baselineTsserverLogs, createLoggerWithInMemoryLogs, createProjectService, logDiagnostics } from "../helpers/tsserver"; -import { createServerHost } from "../helpers/virtualFileSystemWithWatch"; +import { + baselineTsserverLogs, + createLoggerWithInMemoryLogs, + createProjectService, + logDiagnostics, +} from "../helpers/tsserver"; +import { + createServerHost, +} from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: tsserver:: languageService", () => { it("should work correctly on case-sensitive file systems", () => { const lib = { path: "/a/Lib/lib.d.ts", - content: "let x: number" + content: "let x: number", }; const f = { path: "/a/b/app.ts", - content: "let x = 1;" + content: "let x = 1;", }; const host = createServerHost([lib, f], { executingFilePath: "/a/Lib/tsc.js", useCaseSensitiveFileNames: true }); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -25,36 +32,36 @@ describe("unittests:: tsserver:: languageService", () => { path: "/project/shared.ts", content: Utils.dedent` import {foo_a} from "foo"; - ` + `, }, { path: `/project/a/tsconfig.json`, - content: `{ "compilerOptions": { "paths": { "foo": ["./foo.d.ts"] } }, "files": ["./index.ts", "./foo.d.ts"] }` + content: `{ "compilerOptions": { "paths": { "foo": ["./foo.d.ts"] } }, "files": ["./index.ts", "./foo.d.ts"] }`, }, { path: `/project/a/foo.d.ts`, content: Utils.dedent` export const foo_a = 1; - ` + `, }, { path: "/project/a/index.ts", - content: `import "../shared";` + content: `import "../shared";`, }, { path: `/project/b/tsconfig.json`, - content: `{ "compilerOptions": { "paths": { "foo": ["./foo.d.ts"] } }, "files": ["./index.ts", "./foo.d.ts"] }` + content: `{ "compilerOptions": { "paths": { "foo": ["./foo.d.ts"] } }, "files": ["./index.ts", "./foo.d.ts"] }`, }, { path: `/project/b/foo.d.ts`, content: Utils.dedent` export const foo_b = 1; - ` + `, }, { path: "/project/b/index.ts", - content: `import "../shared";` - } + content: `import "../shared";`, + }, ]; const host = createServerHost(files, { executingFilePath: "/project/tsc.js", useCaseSensitiveFileNames: true }); diff --git a/src/testRunner/unittests/tsserver/libraryResolution.ts b/src/testRunner/unittests/tsserver/libraryResolution.ts index 213e538ed70c7..99a1d09942044 100644 --- a/src/testRunner/unittests/tsserver/libraryResolution.ts +++ b/src/testRunner/unittests/tsserver/libraryResolution.ts @@ -1,9 +1,11 @@ -import { getServerHosForLibResolution } from "../helpers/libraryResolution"; +import { + getServerHosForLibResolution, +} from "../helpers/libraryResolution"; import { baselineTsserverLogs, createLoggerWithInMemoryLogs, createSession, - openFilesForSession + openFilesForSession, } from "../helpers/tsserver"; describe("unittests:: tsserver:: libraryResolution", () => { @@ -20,23 +22,29 @@ describe("unittests:: tsserver:: libraryResolution", () => { host.runQueuedTimeoutCallbacks(); host.deleteFile("/home/src/projects/node_modules/@typescript/lib-dom/index.d.ts"); host.runQueuedTimeoutCallbacks(); - host.writeFile("/home/src/projects/project1/tsconfig.json", JSON.stringify({ - compilerOptions: { - composite: true, - typeRoots: ["./typeroot1", "./typeroot2"], - lib: ["es5", "dom"], - traceResolution: true, - }, - })); - host.runQueuedTimeoutCallbacks(); - host.writeFile("/home/src/projects/project1/tsconfig.json", JSON.stringify({ - compilerOptions: { - composite: true, - typeRoots: ["./typeroot1"], - lib: ["es5", "dom"], - traceResolution: true, - }, - })); + host.writeFile( + "/home/src/projects/project1/tsconfig.json", + JSON.stringify({ + compilerOptions: { + composite: true, + typeRoots: ["./typeroot1", "./typeroot2"], + lib: ["es5", "dom"], + traceResolution: true, + }, + }), + ); + host.runQueuedTimeoutCallbacks(); + host.writeFile( + "/home/src/projects/project1/tsconfig.json", + JSON.stringify({ + compilerOptions: { + composite: true, + typeRoots: ["./typeroot1"], + lib: ["es5", "dom"], + traceResolution: true, + }, + }), + ); host.ensureFileOrFolder({ path: "/home/src/projects/node_modules/@typescript/lib-dom/index.d.ts", content: "interface DOMInterface { }" }); host.runQueuedTimeoutCallbacks(); host.ensureFileOrFolder({ path: "/home/src/projects/node_modules/@typescript/lib-webworker/index.d.ts", content: "interface WebWorkerInterface { }" }); @@ -59,23 +67,29 @@ describe("unittests:: tsserver:: libraryResolution", () => { host.ensureFileOrFolder({ path: "/home/src/projects/node_modules/@typescript/lib-dom/index.d.ts", content: "interface DOMInterface { }" }); host.runQueuedTimeoutCallbacks(); host.runQueuedTimeoutCallbacks(); - host.writeFile("/home/src/projects/project1/tsconfig.json", JSON.stringify({ - compilerOptions: { - composite: true, - typeRoots: ["./typeroot1", "./typeroot2"], - lib: ["es5", "dom"], - traceResolution: true, - }, - })); - host.runQueuedTimeoutCallbacks(); - host.writeFile("/home/src/projects/project1/tsconfig.json", JSON.stringify({ - compilerOptions: { - composite: true, - typeRoots: ["./typeroot1"], - lib: ["es5", "dom"], - traceResolution: true, - }, - })); + host.writeFile( + "/home/src/projects/project1/tsconfig.json", + JSON.stringify({ + compilerOptions: { + composite: true, + typeRoots: ["./typeroot1", "./typeroot2"], + lib: ["es5", "dom"], + traceResolution: true, + }, + }), + ); + host.runQueuedTimeoutCallbacks(); + host.writeFile( + "/home/src/projects/project1/tsconfig.json", + JSON.stringify({ + compilerOptions: { + composite: true, + typeRoots: ["./typeroot1"], + lib: ["es5", "dom"], + traceResolution: true, + }, + }), + ); host.deleteFile("/home/src/projects/node_modules/@typescript/lib-dom/index.d.ts"); host.runQueuedTimeoutCallbacks(); host.deleteFile("/home/src/projects/node_modules/@typescript/lib-webworker/index.d.ts"); @@ -85,4 +99,4 @@ describe("unittests:: tsserver:: libraryResolution", () => { host.runQueuedTimeoutCallbacks(); baselineTsserverLogs("libraryResolution", "with config with redirection", session); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts b/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts index 02b722bf0165d..2f4fe30e0d392 100644 --- a/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts +++ b/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts @@ -17,11 +17,11 @@ describe("unittests:: tsserver:: maxNodeModuleJsDepth for inferred projects", () it("should be set to 2 if the project has js root files", () => { const file1: File = { path: "/a/b/file1.js", - content: `var t = require("test"); t.` + content: `var t = require("test"); t.`, }; const moduleFile: File = { path: "/a/b/node_modules/test/index.js", - content: `var v = 10; module.exports = v;` + content: `var v = 10; module.exports = v;`, }; const host = createServerHost([file1, moduleFile]); @@ -39,11 +39,11 @@ describe("unittests:: tsserver:: maxNodeModuleJsDepth for inferred projects", () it("should return to normal state when all js root files are removed from project", () => { const file1 = { path: "/a/file1.ts", - content: "let x =1;" + content: "let x =1;", }; const file2 = { path: "/a/file2.js", - content: "let x =1;" + content: "let x =1;", }; const host = createServerHost([file1, file2, libFile]); diff --git a/src/testRunner/unittests/tsserver/metadataInResponse.ts b/src/testRunner/unittests/tsserver/metadataInResponse.ts index e69b1ab1f198c..9bc2dc2c0af79 100644 --- a/src/testRunner/unittests/tsserver/metadataInResponse.ts +++ b/src/testRunner/unittests/tsserver/metadataInResponse.ts @@ -17,8 +17,8 @@ describe("unittests:: tsserver:: with metadataInResponse::", () => { const tsconfig: File = { path: "/tsconfig.json", content: JSON.stringify({ - compilerOptions: { plugins: [{ name: "myplugin" }] } - }) + compilerOptions: { plugins: [{ name: "myplugin" }] }, + }), }; function createHostWithPlugin(files: readonly File[]) { const host = createServerHost(files); @@ -36,9 +36,9 @@ describe("unittests:: tsserver:: with metadataInResponse::", () => { return result; }; return proxy; - } + }, }), - error: undefined + error: undefined, }; }; return host; @@ -48,7 +48,7 @@ describe("unittests:: tsserver:: with metadataInResponse::", () => { const completionRequestArgs: ts.server.protocol.CompletionsRequestArgs = { file: aTs.path, line: 1, - offset: aTs.content.indexOf("this.") + 1 + "this.".length + offset: aTs.content.indexOf("this.") + 1 + "this.".length, }; it("can pass through metadata when the command returns array", () => { @@ -57,7 +57,7 @@ describe("unittests:: tsserver:: with metadataInResponse::", () => { openFilesForSession([aTs], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Completions, - arguments: completionRequestArgs + arguments: completionRequestArgs, }); baselineTsserverLogs("metadataInResponse", "can pass through metadata when the command returns array", session); }); @@ -68,7 +68,7 @@ describe("unittests:: tsserver:: with metadataInResponse::", () => { openFilesForSession([aTs], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompletionInfo, - arguments: completionRequestArgs + arguments: completionRequestArgs, }); baselineTsserverLogs("metadataInResponse", "can pass through metadata when the command returns object", session); }); @@ -80,7 +80,7 @@ describe("unittests:: tsserver:: with metadataInResponse::", () => { openFilesForSession([aTs], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Completions, - arguments: { file: aTs.path, line: 1, offset: aTs.content.indexOf("x") + 1 } + arguments: { file: aTs.path, line: 1, offset: aTs.content.indexOf("x") + 1 }, }); baselineTsserverLogs("metadataInResponse", "returns undefined correctly", session); }); diff --git a/src/testRunner/unittests/tsserver/moduleResolution.ts b/src/testRunner/unittests/tsserver/moduleResolution.ts index f0ff49c993cfb..8fd1665d5d0d4 100644 --- a/src/testRunner/unittests/tsserver/moduleResolution.ts +++ b/src/testRunner/unittests/tsserver/moduleResolution.ts @@ -1,5 +1,10 @@ import * as Utils from "../../_namespaces/Utils"; -import { getFsConentsForNode10ResultAtTypesPackageJson, getFsContentsForNode10Result, getFsContentsForNode10ResultDts, getFsContentsForNode10ResultPackageJson } from "../helpers/node10Result"; +import { + getFsConentsForNode10ResultAtTypesPackageJson, + getFsContentsForNode10Result, + getFsContentsForNode10ResultDts, + getFsContentsForNode10ResultPackageJson, +} from "../helpers/node10Result"; import { baselineTsserverLogs, createLoggerWithInMemoryLogs, @@ -24,32 +29,34 @@ describe("unittests:: tsserver:: moduleResolution", () => { module: "Node16", outDir: "../out", traceResolution: true, - } - }) + }, + }), }; const packageFile: File = { path: `/user/username/projects/myproject/package.json`, - content: packageFileContents + content: packageFileContents, }; const fileA: File = { path: `/user/username/projects/myproject/src/fileA.ts`, content: Utils.dedent` import { foo } from "./fileB.mjs"; foo(); - ` + `, }; const fileB: File = { path: `/user/username/projects/myproject/src/fileB.mts`, content: Utils.dedent` export function foo() { } - ` + `, }; const host = createServerHost([configFile, fileA, fileB, packageFile, { ...libFile, path: "/a/lib/lib.es2016.full.d.ts" }]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); openFilesForSession([fileA], session); return { - host, session, packageFile, + host, + session, + packageFile, verifyErr: () => verifyGetErrRequest({ files: [fileA], session }), }; } @@ -57,9 +64,14 @@ describe("unittests:: tsserver:: moduleResolution", () => { const { host, session, packageFile, verifyErr } = setup(JSON.stringify({ name: "app", version: "1.0.0" })); session.logger.info("Modify package json file to add type module"); - host.writeFile(packageFile.path, JSON.stringify({ - name: "app", version: "1.0.0", type: "module", - })); + host.writeFile( + packageFile.path, + JSON.stringify({ + name: "app", + version: "1.0.0", + type: "module", + }), + ); host.runQueuedTimeoutCallbacks(); // Failed lookup updates host.runQueuedTimeoutCallbacks(); // Actual update verifyErr(); @@ -77,9 +89,14 @@ describe("unittests:: tsserver:: moduleResolution", () => { verifyErr(); session.logger.info("Modify package json file to add type module"); - host.writeFile(packageFile.path, JSON.stringify({ - name: "app", version: "1.0.0", type: "module", - })); + host.writeFile( + packageFile.path, + JSON.stringify({ + name: "app", + version: "1.0.0", + type: "module", + }), + ); host.runQueuedTimeoutCallbacks(); // Failed lookup updates host.runQueuedTimeoutCallbacks(); // Actual update verifyErr(); @@ -95,7 +112,9 @@ describe("unittests:: tsserver:: moduleResolution", () => { it("package json file is edited when package json with type module exists", () => { const { host, session, packageFile, verifyErr } = setup(JSON.stringify({ - name: "app", version: "1.0.0", type: "module", + name: "app", + version: "1.0.0", + type: "module", })); session.logger.info("Modify package json file to remove type module"); @@ -176,4 +195,4 @@ describe("unittests:: tsserver:: moduleResolution", () => { }); } }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts b/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts index 5e06f62d75a52..acc39d3981dd2 100644 --- a/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts +++ b/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts @@ -13,7 +13,7 @@ import { const packageJson: File = { path: "/package.json", - content: `{ "dependencies": { "mobx": "*" } }` + content: `{ "dependencies": { "mobx": "*" } }`, }; const aTs: File = { path: "/src/a.ts", @@ -37,15 +37,15 @@ const tsconfig: File = { }; const ambientDeclaration: File = { path: "/src/ambient.d.ts", - content: "declare module 'ambient' {}" + content: "declare module 'ambient' {}", }; const mobxPackageJson: File = { path: "/node_modules/mobx/package.json", - content: `{ "name": "mobx", "version": "1.0.0" }` + content: `{ "name": "mobx", "version": "1.0.0" }`, }; const mobxDts: File = { path: "/node_modules/mobx/index.d.ts", - content: "export declare function observable(): unknown;" + content: "export declare function observable(): unknown;", }; describe("unittests:: tsserver:: moduleSpecifierCache", () => { @@ -112,7 +112,7 @@ describe("unittests:: tsserver:: moduleSpecifierCache", () => { getWithPreferences({}); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { preferences } + arguments: { preferences }, }); // Nothing changes yet getWithPreferences({}); @@ -125,7 +125,7 @@ describe("unittests:: tsserver:: moduleSpecifierCache", () => { // Test other affecting preference session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { preferences: { importModuleSpecifierEnding: "js" } } + arguments: { preferences: { importModuleSpecifierEnding: "js" } }, }); triggerCompletions({ file: bTs.path, line: 1, offset: 3 }); getWithPreferences(preferences); @@ -152,7 +152,7 @@ function setup() { includeCompletionsWithInsertText: true, includeCompletionsWithSnippetText: true, }, - } + }, }); triggerCompletions({ file: bTs.path, line: 1, offset: 3 }); diff --git a/src/testRunner/unittests/tsserver/navTo.ts b/src/testRunner/unittests/tsserver/navTo.ts index db9303a635ee2..883d5bdbda56b 100644 --- a/src/testRunner/unittests/tsserver/navTo.ts +++ b/src/testRunner/unittests/tsserver/navTo.ts @@ -15,11 +15,11 @@ describe("unittests:: tsserver:: navigate-to for javascript project", () => { it("should not include type symbols", () => { const file1: File = { path: "/a/b/file1.js", - content: "function foo() {}" + content: "function foo() {}", }; const configFile: File = { path: "/a/b/jsconfig.json", - content: "{}" + content: "{}", }; const host = createServerHost([file1, configFile, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -28,12 +28,12 @@ describe("unittests:: tsserver:: navigate-to for javascript project", () => { // Try to find some interface type defined in lib.d.ts session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Navto, - arguments: { searchValue: "Document", file: file1.path, projectFileName: configFile.path } + arguments: { searchValue: "Document", file: file1.path, projectFileName: configFile.path }, }).response as ts.server.protocol.NavtoItem[]; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Navto, - arguments: { searchValue: "foo", file: file1.path, projectFileName: configFile.path } + arguments: { searchValue: "foo", file: file1.path, projectFileName: configFile.path }, }).response as ts.server.protocol.NavtoItem[]; baselineTsserverLogs("navTo", "should not include type symbols", session); }); @@ -45,11 +45,11 @@ describe("unittests:: tsserver:: navigate-to for javascript project", () => { "compilerOptions": { "composite": true } -}` +}`, }; const file1: File = { path: "/a/index.ts", - content: "export const abcdef = 1;" + content: "export const abcdef = 1;", }; const configFile2: File = { path: "/b/tsconfig.json", @@ -60,12 +60,12 @@ describe("unittests:: tsserver:: navigate-to for javascript project", () => { "references": [ { "path": "../a" } ] -}` +}`, }; const file2: File = { path: "/b/index.ts", content: `import a = require("../a"); -export const ghijkl = a.abcdef;` +export const ghijkl = a.abcdef;`, }; const host = createServerHost([configFile1, file1, configFile2, file2]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -73,7 +73,7 @@ export const ghijkl = a.abcdef;` session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Navto, - arguments: { searchValue: "abcdef", file: file1.path } + arguments: { searchValue: "abcdef", file: file1.path }, }); baselineTsserverLogs("navTo", "should de-duplicate symbols", session); @@ -85,7 +85,7 @@ export const ghijkl = a.abcdef;` content: JSON.stringify({ references: [{ path: "./a" }, { path: "./b" }], files: [], - }) + }), }; const configFile1: File = { path: "/a/tsconfig.json", @@ -93,11 +93,11 @@ export const ghijkl = a.abcdef;` "compilerOptions": { "composite": true } -}` +}`, }; const file1: File = { path: "/a/index.ts", - content: "export const abcdef = 1;" + content: "export const abcdef = 1;", }; const configFile2: File = { path: "/b/tsconfig.json", @@ -108,12 +108,12 @@ export const ghijkl = a.abcdef;` "references": [ { "path": "../a" } ] -}` +}`, }; const file2: File = { path: "/b/index.ts", content: `import a = require("../a"); -export const ghijkl = a.abcdef;` +export const ghijkl = a.abcdef;`, }; const host = createServerHost([configFile1, file1, configFile2, file2, solutionConfig]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -121,7 +121,7 @@ export const ghijkl = a.abcdef;` session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Navto, - arguments: { searchValue: "abcdef" } + arguments: { searchValue: "abcdef" }, }); baselineTsserverLogs("navTo", "should de-duplicate symbols when searching all projects", session); }); @@ -129,11 +129,11 @@ export const ghijkl = a.abcdef;` it("should work with Deprecated", () => { const file1: File = { path: "/a/b/file1.js", - content: "/** @deprecated */\nfunction foo () {}" + content: "/** @deprecated */\nfunction foo () {}", }; const configFile: File = { path: "/a/b/jsconfig.json", - content: "{}" + content: "{}", }; const host = createServerHost([file1, configFile, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -142,7 +142,7 @@ export const ghijkl = a.abcdef;` // Try to find some interface type defined in lib.d.ts session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Navto, - arguments: { searchValue: "foo", file: file1.path, projectFileName: configFile.path } + arguments: { searchValue: "foo", file: file1.path, projectFileName: configFile.path }, }); baselineTsserverLogs("navTo", "should work with Deprecated", session); }); diff --git a/src/testRunner/unittests/tsserver/occurences.ts b/src/testRunner/unittests/tsserver/occurences.ts index e9eb1552bf3e3..c89b4754db866 100644 --- a/src/testRunner/unittests/tsserver/occurences.ts +++ b/src/testRunner/unittests/tsserver/occurences.ts @@ -14,7 +14,7 @@ describe("unittests:: tsserver:: occurrence highlight on string", () => { it("should be marked if only on string values", () => { const file1: File = { path: "/a/b/file1.ts", - content: `let t1 = "div";\nlet t2 = "div";\nlet t3 = { "div": 123 };\nlet t4 = t3["div"];` + content: `let t1 = "div";\nlet t2 = "div";\nlet t3 = { "div": 123 };\nlet t4 = t3["div"];`, }; const host = createServerHost([file1]); @@ -22,17 +22,17 @@ describe("unittests:: tsserver:: occurrence highlight on string", () => { openFilesForSession([file1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DocumentHighlights, - arguments: { file: file1.path, line: 1, offset: 11, filesToSearch: [file1.path] } + arguments: { file: file1.path, line: 1, offset: 11, filesToSearch: [file1.path] }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DocumentHighlights, - arguments: { file: file1.path, line: 3, offset: 13, filesToSearch: [file1.path] } + arguments: { file: file1.path, line: 3, offset: 13, filesToSearch: [file1.path] }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DocumentHighlights, - arguments: { file: file1.path, line: 4, offset: 14, filesToSearch: [file1.path] } + arguments: { file: file1.path, line: 4, offset: 14, filesToSearch: [file1.path] }, }); baselineTsserverLogs("occurences", "should be marked if only on string values", session); }); diff --git a/src/testRunner/unittests/tsserver/openFile.ts b/src/testRunner/unittests/tsserver/openFile.ts index 3d3c9c1929a85..110357c2b0327 100644 --- a/src/testRunner/unittests/tsserver/openFile.ts +++ b/src/testRunner/unittests/tsserver/openFile.ts @@ -21,7 +21,7 @@ describe("unittests:: tsserver:: Open-file", () => { it("can be reloaded with empty content", () => { const f = { path: "/a/b/app.ts", - content: "let x = 1" + content: "let x = 1", }; const projectFileName = "externalProject"; const host = createServerHost([f]); @@ -46,22 +46,22 @@ describe("unittests:: tsserver:: Open-file", () => { it(subScenario, () => { const file1: File = { path: "/a/b/src/app.ts", - content: "let x = 10;" + content: "let x = 10;", }; const file2: File = { path: "/a/B/lib/module2.ts", - content: "let z = 10;" + content: "let z = 10;", }; const configFile: File = { path: "/a/b/tsconfig.json", - content: "" + content: "", }; const configFile2: File = { path: "/a/tsconfig.json", - content: "" + content: "", }; const host = createServerHost([file1, file2, configFile, configFile2], { - useCaseSensitiveFileNames + useCaseSensitiveFileNames, }); const service = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -90,11 +90,11 @@ describe("unittests:: tsserver:: Open-file", () => { const projectFolder = "/user/someuser/projects/myproject"; const aFile: File = { path: `${projectFolder}/src/a.ts`, - content: "export const x = 0;" + content: "export const x = 0;", }; const configFile: File = { path: `${projectFolder}/tsconfig.json`, - content: "{}" + content: "{}", }; const files = [aFile, configFile, libFile]; const host = createServerHost(files); @@ -103,7 +103,7 @@ describe("unittests:: tsserver:: Open-file", () => { const bFile: File = { path: `${projectFolder}/src/b.ts`, - content: `export {}; declare module "./a" { export const y: number; }` + content: `export {}; declare module "./a" { export const y: number; }`, }; host.writeFile(bFile.path, bFile.content); service.openClientFile(bFile.path, /*fileContent*/ undefined, ts.ScriptKind.TS, projectFolder); @@ -114,11 +114,11 @@ describe("unittests:: tsserver:: Open-file", () => { const projectFolder = "/user/someuser/projects/myproject"; const aFile: File = { path: `${projectFolder}/src/a.ts`, - content: "export const x = 0;" + content: "export const x = 0;", }; const configFile: File = { path: `${projectFolder}/tsconfig.json`, - content: "{}" + content: "{}", }; const files = [aFile, configFile, libFile]; const host = createServerHost(files); @@ -148,7 +148,7 @@ function bar() { return z; } foo(); -bar();` +bar();`, }; const host = createServerHost([file, libFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -165,10 +165,10 @@ bar();` fileName: file.path, textChanges: [{ newText: " ", - ...locationOfTsIgnore - }] - }] - } + ...locationOfTsIgnore, + }], + }], + }, }); verifyGetErrRequest({ session, files: [file] }); // Revert the change and no errors should be reported @@ -179,10 +179,10 @@ bar();` fileName: file.path, textChanges: [{ newText: tsIgnoreComment, - ...locationOfTsIgnore - }] - }] - } + ...locationOfTsIgnore, + }], + }], + }, }); verifyGetErrRequest({ session, files: [file] }); baselineTsserverLogs("openfile", "when file makes edits to add/remove comment directives, they are handled correcrly", session); @@ -208,10 +208,10 @@ bar();` fileName, changes: [{ span: { start: 0, length: 0 }, - newText: "export const y = 10;" - }] - }] - } + newText: "export const y = 10;", + }], + }], + }, }); } diff --git a/src/testRunner/unittests/tsserver/packageJsonInfo.ts b/src/testRunner/unittests/tsserver/packageJsonInfo.ts index 1f7e4a740c5f1..573e014a6f765 100644 --- a/src/testRunner/unittests/tsserver/packageJsonInfo.ts +++ b/src/testRunner/unittests/tsserver/packageJsonInfo.ts @@ -12,25 +12,25 @@ import { const tsConfig: File = { path: "/tsconfig.json", - content: "{}" + content: "{}", }; const packageJsonContent = { dependencies: { - redux: "*" + redux: "*", }, peerDependencies: { - react: "*" + react: "*", }, optionalDependencies: { - typescript: "*" + typescript: "*", }, devDependencies: { - webpack: "*" - } + webpack: "*", + }, }; const packageJson: File = { path: "/package.json", - content: JSON.stringify(packageJsonContent, undefined, 2) + content: JSON.stringify(packageJsonContent, undefined, 2), }; describe("unittests:: tsserver:: packageJsonInfo::", () => { @@ -50,10 +50,13 @@ describe("unittests:: tsserver:: packageJsonInfo::", () => { assert.ok(packageJsonInfo.optionalDependencies); // Edit package.json - host.writeFile(packageJson.path, JSON.stringify({ - ...packageJsonContent, - dependencies: undefined - })); + host.writeFile( + packageJson.path, + JSON.stringify({ + ...packageJsonContent, + dependencies: undefined, + }), + ); session.testhost.baselineHost("Edit package.json"); packageJsonInfo = projectService.packageJsonCache.getInDirectory("/" as ts.Path)!; assert.isUndefined(packageJsonInfo.dependencies); @@ -63,7 +66,7 @@ describe("unittests:: tsserver:: packageJsonInfo::", () => { it("finds package.json on demand, watches for deletion, and removes them from cache", () => { // Initialize project with package.json - const { session , projectService, host } = setup(); + const { session, projectService, host } = setup(); projectService.getPackageJsonsVisibleToFile("/src/whatever/blah.ts" as ts.Path); assert.ok(projectService.packageJsonCache.getInDirectory("/" as ts.Path)); diff --git a/src/testRunner/unittests/tsserver/partialSemanticServer.ts b/src/testRunner/unittests/tsserver/partialSemanticServer.ts index ed8d7a988dad4..cbe2c337ab335 100644 --- a/src/testRunner/unittests/tsserver/partialSemanticServer.ts +++ b/src/testRunner/unittests/tsserver/partialSemanticServer.ts @@ -20,25 +20,25 @@ describe("unittests:: tsserver:: Semantic operations on partialSemanticServer", path: `/user/username/projects/myproject/a.ts`, content: `import { y, cc } from "./b"; import { something } from "something"; -class c { prop = "hello"; foo() { return this.prop; } }` +class c { prop = "hello"; foo() { return this.prop; } }`, }; const file2: File = { path: `/user/username/projects/myproject/b.ts`, content: `export { cc } from "./c"; import { something } from "something"; - export const y = 10;` + export const y = 10;`, }; const file3: File = { path: `/user/username/projects/myproject/c.ts`, - content: `export const cc = 10;` + content: `export const cc = 10;`, }; const something: File = { path: `/user/username/projects/myproject/node_modules/something/index.d.ts`, - content: "export const something = 10;" + content: "export const something = 10;", }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const host = createServerHost([file1, file2, file3, something, libFile, configFile]); const session = createSession(host, { @@ -62,7 +62,7 @@ import { something } from "something"; function verifyCompletions() { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Completions, - arguments: protocolFileLocationFromSubstring(file1, "prop", { index: 1 }) + arguments: protocolFileLocationFromSubstring(file1, "prop", { index: 1 }), }); } }); @@ -74,7 +74,7 @@ import { something } from "something"; try { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); } catch (e) { @@ -94,11 +94,11 @@ import { something } from "something"; it("allows syntactic diagnostic commands", () => { const file1: File = { path: `/user/username/projects/myproject/a.ts`, - content: `if (a < (b + c) { }` + content: `if (a < (b + c) { }`, }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: `{}` + content: `{}`, }; const expectedErrorMessage = "')' expected."; @@ -106,7 +106,7 @@ import { something } from "something"; const session = createSession(host, { serverMode: ts.LanguageServiceMode.PartialSemantic, useSingleInferredProject: true, - logger: createLoggerWithInMemoryLogs(host) + logger: createLoggerWithInMemoryLogs(host), }); const service = session.getProjectService(); @@ -115,7 +115,7 @@ import { something } from "something"; type: "request", seq: 1, command: ts.server.protocol.CommandTypes.SyntacticDiagnosticsSync, - arguments: { file: file1.path } + arguments: { file: file1.path }, }; const response = session.executeCommandSeq(request).response as ts.server.protocol.SyntacticDiagnosticsSyncResponse["body"]; assert.isDefined(response); @@ -135,7 +135,7 @@ import { something } from "something"; const { host, session, file1 } = setup(); const atTypes: File = { path: `/node_modules/@types/somemodule/index.d.ts`, - content: "export const something = 10;" + content: "export const something = 10;", }; host.ensureFileOrFolder(atTypes); openFilesForSession([file1], session); @@ -147,25 +147,25 @@ import { something } from "something"; path: `/user/username/projects/myproject/a.ts`, content: `/// /// -function fooA() { }` +function fooA() { }`, }; const file2: File = { path: `/user/username/projects/myproject/b.ts`, content: `/// /// -function fooB() { }` +function fooB() { }`, }; const file3: File = { path: `/user/username/projects/myproject/c.ts`, - content: `function fooC() { }` + content: `function fooC() { }`, }; const something: File = { path: `/user/username/projects/myproject/node_modules/something/index.d.ts`, - content: "function something() {}" + content: "function something() {}", }; const configFile: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; const host = createServerHost([file1, file2, file3, something, libFile, configFile]); const session = createSession(host, { @@ -205,11 +205,11 @@ function fooB() { }` }; const packageJson: File = { path: "/package.json", - content: `{ "dependencies": { "@angular/forms": "*", "@angular/core": "*" } }` + content: `{ "dependencies": { "@angular/forms": "*", "@angular/core": "*" } }`, }; const indexTs: File = { path: "/index.ts", - content: "" + content: "", }; const host = createServerHost([angularFormsDts, angularFormsPackageJson, tsconfig, packageJson, indexTs, libFile]); const session = createSession(host, { serverMode: ts.LanguageServiceMode.PartialSemantic, useSingleInferredProject: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -227,7 +227,7 @@ function fooB() { }` openFilesForSession([file1], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: protocolFileLocationFromSubstring(file1, `"./b"`) + arguments: protocolFileLocationFromSubstring(file1, `"./b"`), }); baselineTsserverLogs("partialSemanticServer", "should support go-to-definition on module specifiers", session); }); diff --git a/src/testRunner/unittests/tsserver/plugins.ts b/src/testRunner/unittests/tsserver/plugins.ts index df0befc74e0d1..503c0702d1633 100644 --- a/src/testRunner/unittests/tsserver/plugins.ts +++ b/src/testRunner/unittests/tsserver/plugins.ts @@ -28,13 +28,13 @@ describe("unittests:: tsserver:: plugins:: loading", () => { info.session?.addProtocolHandler(testProtocolCommand, request => { session.logger.log(`addProtocolHandler: ${JSON.stringify(request, undefined, " ")}`); return { - response: testProtocolCommandResponse + response: testProtocolCommandResponse, }; }); return Harness.LanguageService.makeDefaultProxy(info); - } + }, }), - error: undefined + error: undefined, }; }; const session = createSession(host, { ...opts, logger: createLoggerWithInMemoryLogs(host) }); @@ -51,10 +51,10 @@ describe("unittests:: tsserver:: plugins:: loading", () => { compilerOptions: { plugins: [ ...[...expectedToLoad, ...notToLoad].map(name => ({ name })), - { transform: "some-transform" } - ] - } - }) + { transform: "some-transform" }, + ], + }, + }), }; const { session } = createHostWithPlugin([aTs, tsconfig, libFile]); openFilesForSession([aTs], session); @@ -67,7 +67,7 @@ describe("unittests:: tsserver:: plugins:: loading", () => { const aTs: File = { path: "/a.ts", content: `class c { prop = "hello"; foo() { return this.prop; } }` }; const tsconfig: File = { path: "/tsconfig.json", - content: "{}" + content: "{}", }; const { session } = createHostWithPlugin([aTs, tsconfig, libFile], { globalPlugins: [...expectedToLoad, ...notToLoad] }); openFilesForSession([aTs], session); @@ -82,10 +82,10 @@ describe("unittests:: tsserver:: plugins:: loading", () => { content: JSON.stringify({ compilerOptions: { plugins: [ - { name: pluginName } - ] - } - }) + { name: pluginName }, + ], + }, + }), }; const { session } = createHostWithPlugin([aTs, tsconfig, libFile]); @@ -94,7 +94,7 @@ describe("unittests:: tsserver:: plugins:: loading", () => { session.executeCommandSeq({ command: testProtocolCommand, - arguments: testProtocolCommandRequest + arguments: testProtocolCommandRequest, }); baselineTsserverLogs("plugins", "With session and custom protocol message", session); @@ -106,9 +106,9 @@ describe("unittests:: tsserver:: plugins:: loading", () => { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - plugins: [{ name: "some-plugin" }] - } - }) + plugins: [{ name: "some-plugin" }], + }, + }), }; const externalFiles: ts.MapLike = { @@ -124,21 +124,24 @@ describe("unittests:: tsserver:: plugins:: loading", () => { session.logger.log(`PluginFactory Invoke`); return { create: Harness.LanguageService.makeDefaultProxy, - getExternalFiles: () => externalFiles[moduleName] + getExternalFiles: () => externalFiles[moduleName], }; }, - error: undefined + error: undefined, }; }; const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); openFilesForSession([aTs], session); session.logger.log(`ExternalFiles:: ${JSON.stringify(session.getProjectService().configuredProjects.get(tsconfig.path)!.getExternalFiles())}`); - host.writeFile(tsconfig.path, JSON.stringify({ - compilerOptions: { - plugins: [{ name: "some-other-plugin" }] - } - })); + host.writeFile( + tsconfig.path, + JSON.stringify({ + compilerOptions: { + plugins: [{ name: "some-other-plugin" }], + }, + }), + ); host.runQueuedTimeoutCallbacks(); session.logger.log(`ExternalFiles:: ${JSON.stringify(session.getProjectService().configuredProjects.get(tsconfig.path)!.getExternalFiles())}`); @@ -150,21 +153,21 @@ describe("unittests:: tsserver:: plugins:: overriding getSupportedCodeFixes", () it("getSupportedCodeFixes can be proxied", () => { const aTs: File = { path: "/a.ts", - content: `class c { prop = "hello"; foo() { const x = 0; } }` + content: `class c { prop = "hello"; foo() { const x = 0; } }`, }; const bTs: File = { path: "/b.ts", - content: aTs.content + content: aTs.content, }; const cTs: File = { path: "/c.ts", - content: aTs.content + content: aTs.content, }; const config: File = { path: "/tsconfig.json", content: JSON.stringify({ - compilerOptions: { plugins: [{ name: "myplugin" }] } - }) + compilerOptions: { plugins: [{ name: "myplugin" }] }, + }), }; const host = createServerHost([aTs, bTs, cTs, config, libFile]); host.require = () => { @@ -172,7 +175,7 @@ describe("unittests:: tsserver:: plugins:: overriding getSupportedCodeFixes", () module: () => ({ create(info: ts.server.PluginCreateInfo) { const proxy = Harness.LanguageService.makeDefaultProxy(info); - proxy.getSupportedCodeFixes = (fileName) => { + proxy.getSupportedCodeFixes = fileName => { switch (fileName) { case "/a.ts": return ["a"]; @@ -184,9 +187,9 @@ describe("unittests:: tsserver:: plugins:: overriding getSupportedCodeFixes", () } }; return proxy; - } + }, }), - error: undefined + error: undefined, }; }; const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -197,21 +200,21 @@ describe("unittests:: tsserver:: plugins:: overriding getSupportedCodeFixes", () }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetSupportedCodeFixes, - arguments: { file: aTs.path } + arguments: { file: aTs.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetSupportedCodeFixes, - arguments: { file: bTs.path } + arguments: { file: bTs.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetSupportedCodeFixes, - arguments: { file: cTs.path } + arguments: { file: cTs.path }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.GetSupportedCodeFixes, - arguments: { projectFileName: config.path } + arguments: { projectFileName: config.path }, }); baselineTsserverLogs("plugins", "getSupportedCodeFixes can be proxied", session); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/pluginsAsync.ts b/src/testRunner/unittests/tsserver/pluginsAsync.ts index 1dda2ff6d5dce..a14caeb845734 100644 --- a/src/testRunner/unittests/tsserver/pluginsAsync.ts +++ b/src/testRunner/unittests/tsserver/pluginsAsync.ts @@ -1,5 +1,7 @@ import * as ts from "../../_namespaces/ts"; -import { defer } from "../../_namespaces/Utils"; +import { + defer, +} from "../../_namespaces/Utils"; import { baselineTsserverLogs, closeFilesForSession, @@ -7,7 +9,10 @@ import { createSession, openFilesForSession, } from "../helpers/tsserver"; -import { createServerHost, libFile } from "../helpers/virtualFileSystemWithWatch"; +import { + createServerHost, + libFile, +} from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: tsserver:: pluginsAsync:: async loaded plugins", () => { function setup(globalPlugins: string[]) { @@ -28,7 +33,7 @@ describe("unittests:: tsserver:: pluginsAsync:: async loaded plugins", () => { pluginInvoked = true; return { create: info => info.languageService }; }) as ts.server.PluginModuleFactory, - error: undefined + error: undefined, }; }; @@ -67,7 +72,7 @@ describe("unittests:: tsserver:: pluginsAsync:: async loaded plugins", () => { session.logger.log(`invoke plugin ${moduleName}`); return { create: info => info.languageService }; }) as ts.server.PluginModuleFactory, - error: undefined + error: undefined, }; }; @@ -93,14 +98,13 @@ describe("unittests:: tsserver:: pluginsAsync:: async loaded plugins", () => { await Promise.resolve(); // simulate at least a single turn delay return { module: (() => ({ create: info => info.languageService })) as ts.server.PluginModuleFactory, - error: undefined + error: undefined, }; }; openFilesForSession([{ file: "^memfs:/foo.ts", content: "" }], session); const projectService = session.getProjectService(); - await projectService.waitForPendingPlugins(); baselineTsserverLogs("pluginsAsync", "sends projectsUpdatedInBackground event", session); @@ -118,7 +122,7 @@ describe("unittests:: tsserver:: pluginsAsync:: async loaded plugins", () => { create: info => info.languageService, getExternalFiles: () => ["external.txt"], })) as ts.server.PluginModuleFactory, - error: undefined + error: undefined, }; }; @@ -152,14 +156,13 @@ describe("unittests:: tsserver:: pluginsAsync:: async loaded plugins", () => { await projectClosed.promise; return { module: (() => ({ create: info => info.languageService })) as ts.server.PluginModuleFactory, - error: undefined + error: undefined, }; }; openFilesForSession([{ file: "^memfs:/foo.ts", content: "" }], session); const projectService = session.getProjectService(); - // wait for the plugin to start loading await pluginALoaded.promise; @@ -174,4 +177,4 @@ describe("unittests:: tsserver:: pluginsAsync:: async loaded plugins", () => { // the project was closed before plugins were ready. no project update should have been requested baselineTsserverLogs("pluginsAsync", "project is closed before plugins are loaded", session); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/projectErrors.ts b/src/testRunner/unittests/tsserver/projectErrors.ts index 20f38c4ab8fc4..80a82f97fa5a9 100644 --- a/src/testRunner/unittests/tsserver/projectErrors.ts +++ b/src/testRunner/unittests/tsserver/projectErrors.ts @@ -25,25 +25,25 @@ describe("unittests:: tsserver:: projectErrors::", () => { it("external project - diagnostics for missing files", () => { const file1 = { path: "/a/b/app.ts", - content: "" + content: "", }; const file2 = { path: "/a/b/applib.ts", - content: "" + content: "", }; const host = createServerHost([file1, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); const projectFileName = "/a/b/test.csproj"; const compilerOptionsRequest: TestSessionRequest = { command: ts.server.protocol.CommandTypes.CompilerOptionsDiagnosticsFull, - arguments: { projectFileName } + arguments: { projectFileName }, }; { openExternalProjectForSession({ projectFileName, options: {}, - rootFiles: toExternalFiles([file1.path, file2.path]) + rootFiles: toExternalFiles([file1.path, file2.path]), }, session); session.executeCommandSeq(compilerOptionsRequest); @@ -66,22 +66,22 @@ describe("unittests:: tsserver:: projectErrors::", () => { it("configured projects - diagnostics for missing files", () => { const file1 = { path: "/a/b/app.ts", - content: "" + content: "", }; const file2 = { path: "/a/b/applib.ts", - content: "" + content: "", }; const config = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ files: [file1, file2].map(f => ts.getBaseFileName(f.path)) }) + content: JSON.stringify({ files: [file1, file2].map(f => ts.getBaseFileName(f.path)) }), }; const host = createServerHost([file1, config, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); openFilesForSession([file1], session); const compilerOptionsRequest: TestSessionRequest = { command: ts.server.protocol.CommandTypes.CompilerOptionsDiagnosticsFull, - arguments: { projectFileName: config.path } + arguments: { projectFileName: config.path }, }; session.executeCommandSeq(compilerOptionsRequest); @@ -94,19 +94,19 @@ describe("unittests:: tsserver:: projectErrors::", () => { it("configured projects - diagnostics for corrupted config 1", () => { const file1 = { path: "/a/b/app.ts", - content: "" + content: "", }; const file2 = { path: "/a/b/lib.ts", - content: "" + content: "", }; const correctConfig = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ files: [file1, file2].map(f => ts.getBaseFileName(f.path)) }) + content: JSON.stringify({ files: [file1, file2].map(f => ts.getBaseFileName(f.path)) }), }; const corruptedConfig = { path: correctConfig.path, - content: correctConfig.content.substr(1) + content: correctConfig.content.substr(1), }; const host = createServerHost([file1, file2, corruptedConfig]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -115,14 +115,14 @@ describe("unittests:: tsserver:: projectErrors::", () => { { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SynchronizeProjectList, - arguments: { knownProjects: [] } + arguments: { knownProjects: [] }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { file: corruptedConfig.path, - projectFileName: corruptedConfig.path - } + projectFileName: corruptedConfig.path, + }, }); } // fix config and trigger watcher @@ -130,14 +130,14 @@ describe("unittests:: tsserver:: projectErrors::", () => { { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SynchronizeProjectList, - arguments: { knownProjects: [] } + arguments: { knownProjects: [] }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { file: correctConfig.path, - projectFileName: correctConfig.path - } + projectFileName: correctConfig.path, + }, }); } baselineTsserverLogs("projectErrors", "configured projects - diagnostics for corrupted config 1", session); @@ -146,19 +146,19 @@ describe("unittests:: tsserver:: projectErrors::", () => { it("configured projects - diagnostics for corrupted config 2", () => { const file1 = { path: "/a/b/app.ts", - content: "" + content: "", }; const file2 = { path: "/a/b/lib.ts", - content: "" + content: "", }; const correctConfig = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ files: [file1, file2].map(f => ts.getBaseFileName(f.path)) }) + content: JSON.stringify({ files: [file1, file2].map(f => ts.getBaseFileName(f.path)) }), }; const corruptedConfig = { path: correctConfig.path, - content: correctConfig.content.substr(1) + content: correctConfig.content.substr(1), }; const host = createServerHost([file1, file2, correctConfig]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -167,14 +167,14 @@ describe("unittests:: tsserver:: projectErrors::", () => { { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SynchronizeProjectList, - arguments: { knownProjects: [] } + arguments: { knownProjects: [] }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { file: correctConfig.path, - projectFileName: correctConfig.path - } + projectFileName: correctConfig.path, + }, }); } // break config and trigger watcher @@ -182,14 +182,14 @@ describe("unittests:: tsserver:: projectErrors::", () => { { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SynchronizeProjectList, - arguments: { knownProjects: [] } + arguments: { knownProjects: [] }, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { file: corruptedConfig.path, - projectFileName: corruptedConfig.path - } + projectFileName: corruptedConfig.path, + }, }); } baselineTsserverLogs("projectErrors", "configured projects - diagnostics for corrupted config 2", session); @@ -200,11 +200,11 @@ describe("unittests:: tsserver:: projectErrors:: are reported as appropriate", ( it("document is not contained in project", () => { const file1 = { path: "/a/b/app.ts", - content: "" + content: "", }; const corruptedConfig = { path: "/a/b/tsconfig.json", - content: "{" + content: "{", }; const host = createServerHost([file1, corruptedConfig]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -217,11 +217,11 @@ describe("unittests:: tsserver:: projectErrors:: are reported as appropriate", ( const folderPath = "/user/someuser/projects/someFolder"; const fileInRoot: File = { path: `/src/somefile.d.ts`, - content: "class c { }" + content: "class c { }", }; const fileInProjectRoot: File = { path: `${folderPath}/src/somefile.d.ts`, - content: "class c { }" + content: "class c { }", }; const host = createServerHost([libFile, fileInRoot, fileInProjectRoot]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host), useInferredProjectPerProjectRoot: true }); @@ -237,8 +237,8 @@ describe("unittests:: tsserver:: projectErrors:: are reported as appropriate", ( file: untitledFile, fileContent, scriptKindName: "TS", - projectRootPath: useProjectRoot ? folderPath : undefined - } + projectRootPath: useProjectRoot ? folderPath : undefined, + }, }); appendAllScriptInfos(session); @@ -260,22 +260,22 @@ describe("unittests:: tsserver:: projectErrors:: are reported as appropriate", ( const projectDir = "/a/b/projects/myproject"; const app: File = { path: `${projectDir}/bar/app.ts`, - content: "class Bar implements foo.Foo { getFoo() { return ''; } get2() { return 1; } }" + content: "class Bar implements foo.Foo { getFoo() { return ''; } get2() { return 1; } }", }; const foo: File = { path: `${projectDir}/foo/foo.ts`, - content: "declare namespace foo { interface Foo { get2(): number; getFoo(): string; } }" + content: "declare namespace foo { interface Foo { get2(): number; getFoo(): string; } }", }; const configFile: File = { path: `${projectDir}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { module: "none", targer: "es5" }, exclude: ["node_modules"] }) + content: JSON.stringify({ compilerOptions: { module: "none", targer: "es5" }, exclude: ["node_modules"] }), }; const host = createServerHost([app, foo, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Open, - arguments: { file: app.path, } + arguments: { file: app.path }, }); verifyGetErrRequest({ session, files: [app] }); @@ -289,7 +289,7 @@ describe("unittests:: tsserver:: projectErrors:: are reported as appropriate", ( it("Getting errors before opening file", () => { const file: File = { path: "/a/b/project/file.ts", - content: "let x: number = false;" + content: "let x: number = false;", }; const host = createServerHost([file, libFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -297,8 +297,8 @@ describe("unittests:: tsserver:: projectErrors:: are reported as appropriate", ( command: ts.server.protocol.CommandTypes.Geterr, arguments: { delay: 0, - files: [file.path] - } + files: [file.path], + }, }); host.runQueuedTimeoutCallbacks(); @@ -308,15 +308,15 @@ describe("unittests:: tsserver:: projectErrors:: are reported as appropriate", ( it("Reports errors correctly when file referenced by inferred project root, is opened right after closing the root file", () => { const app: File = { path: `/user/username/projects/myproject/src/client/app.js`, - content: "" + content: "", }; const serverUtilities: File = { path: `/user/username/projects/myproject/src/server/utilities.js`, - content: `function getHostName() { return "hello"; } export { getHostName };` + content: `function getHostName() { return "hello"; } export { getHostName };`, }; const backendTest: File = { path: `/user/username/projects/myproject/test/backend/index.js`, - content: `import { getHostName } from '../../src/server/utilities';export default getHostName;` + content: `import { getHostName } from '../../src/server/utilities';export default getHostName;`, }; const files = [libFile, app, serverUtilities, backendTest]; const host = createServerHost(files); @@ -337,24 +337,24 @@ describe("unittests:: tsserver:: projectErrors:: are reported as appropriate", ( content: `import * as myModule from "@custom/plugin"; function foo() { // hello -}` +}`, }; const config: File = { path: `${projectRootPath}/tsconfig.json`, - content: JSON.stringify({ include: ["src"] }) + content: JSON.stringify({ include: ["src"] }), }; const plugin: File = { path: `${projectRootPath}/node_modules/@custom/plugin/index.d.ts`, content: `import './proposed'; declare module '@custom/plugin' { export const version: string; -}` +}`, }; const pluginProposed: File = { path: `${projectRootPath}/node_modules/@custom/plugin/proposed.d.ts`, content: `declare module '@custom/plugin' { export const bar = 10; -}` +}`, }; const files = [libFile, aFile, config, plugin, pluginProposed]; const host = createServerHost(files); @@ -371,8 +371,8 @@ declare module '@custom/plugin' { offset: 8, endLine: 3, endOffset: 8, - insertString: "o" - } + insertString: "o", + }, }); verifyGetErrRequest({ session, files: [aFile] }); baselineTsserverLogs("projectErrors", `correct errors when resolution resolves to file that has same ambient module and is also module`, session); @@ -382,11 +382,11 @@ declare module '@custom/plugin' { const file: File = { path: `/user/username/projects/myproject/ui.ts`, content: `const x = async (_action: string) => { -};` +};`, }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; verifyGetErrScenario({ scenario: "projectErrors", @@ -404,7 +404,7 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e it("are generated when the config file has errors", () => { const file: File = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const configFile: File = { path: "/a/b/tsconfig.json", @@ -413,7 +413,7 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e "foo": "bar", "allowJS": true } - }` + }`, }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -424,13 +424,13 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e it("are generated when the config file doesn't have errors", () => { const file: File = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "compilerOptions": {} - }` + }`, }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -441,13 +441,13 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e it("are generated when the config file changes", () => { const file: File = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const configFile = { path: "/a/b/tsconfig.json", content: `{ "compilerOptions": {} - }` + }`, }; const host = createServerHost([file, libFile, configFile]); @@ -473,15 +473,15 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e it("are not generated when the config file does not include file opened and config file has errors", () => { const file: File = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const file2: File = { path: "/a/b/test.ts", - content: "let x = 10" + content: "let x = 10", }; const file3: File = { path: "/a/b/test2.ts", - content: "let xy = 10" + content: "let xy = 10", }; const configFile: File = { path: "/a/b/tsconfig.json", @@ -491,7 +491,7 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e "allowJS": true }, "files": ["app.ts"] - }` + }`, }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -505,7 +505,7 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e it("are not generated when the config file has errors but suppressDiagnosticEvents is true", () => { const file: File = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const configFile: File = { path: "/a/b/tsconfig.json", @@ -514,7 +514,7 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e "foo": "bar", "allowJS": true } - }` + }`, }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { canUseEvents: true, suppressDiagnosticEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -525,21 +525,21 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e it("are not generated when the config file does not include file opened and doesnt contain any errors", () => { const file: File = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const file2: File = { path: "/a/b/test.ts", - content: "let x = 10" + content: "let x = 10", }; const file3: File = { path: "/a/b/test2.ts", - content: "let xy = 10" + content: "let xy = 10", }; const configFile: File = { path: "/a/b/tsconfig.json", content: `{ "files": ["app.ts"] - }` + }`, }; const host = createServerHost([file, file2, file3, libFile, configFile]); @@ -554,7 +554,7 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e it("contains the project reference errors", () => { const file: File = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const noSuchTsconfig = "no-such-tsconfig.json"; const configFile: File = { @@ -562,7 +562,7 @@ describe("unittests:: tsserver:: Project Errors for Configure file diagnostics e content: `{ "files": ["app.ts"], "references": [{"path":"./${noSuchTsconfig}"}] - }` + }`, }; const host = createServerHost([file, libFile, configFile]); @@ -576,7 +576,7 @@ describe("unittests:: tsserver:: projectErrors:: dont include overwrite emit err it("for inferred project", () => { const f1 = { path: "/a/b/f1.js", - content: "function test1() { }" + content: "function test1() { }", }; const host = createServerHost([f1, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -586,13 +586,13 @@ describe("unittests:: tsserver:: projectErrors:: dont include overwrite emit err const projectFileName = projectService.inferredProjects[0].getProjectName(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompilerOptionsDiagnosticsFull, - arguments: { projectFileName } + arguments: { projectFileName }, }); setCompilerOptionsForInferredProjectsRequestForSession({ module: ts.ModuleKind.CommonJS }, session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompilerOptionsDiagnosticsFull, - arguments: { projectFileName } + arguments: { projectFileName }, }); baselineTsserverLogs("projectErrors", "for inferred project", session); }); @@ -600,7 +600,7 @@ describe("unittests:: tsserver:: projectErrors:: dont include overwrite emit err it("for external project", () => { const f1 = { path: "/a/b/f1.js", - content: "function test1() { }" + content: "function test1() { }", }; const host = createServerHost([f1, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -609,22 +609,22 @@ describe("unittests:: tsserver:: projectErrors:: dont include overwrite emit err openExternalProjectForSession({ projectFileName, rootFiles: externalFiles, - options: {} + options: {}, }, session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompilerOptionsDiagnosticsFull, - arguments: { projectFileName } + arguments: { projectFileName }, }); openExternalProjectForSession({ projectFileName, rootFiles: externalFiles, - options: { module: ts.ModuleKind.CommonJS } + options: { module: ts.ModuleKind.CommonJS }, }, session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompilerOptionsDiagnosticsFull, - arguments: { projectFileName } + arguments: { projectFileName }, }); baselineTsserverLogs("projectErrors", "for external project", session); }); @@ -634,7 +634,7 @@ describe("unittests:: tsserver:: projectErrors:: reports Options Diagnostic loca it("when options change", () => { const file = { path: "/a/b/app.ts", - content: "let x = 10" + content: "let x = 10", }; const configFileContentBeforeComment = `{`; const configFileContentComment = ` @@ -650,7 +650,7 @@ describe("unittests:: tsserver:: projectErrors:: reports Options Diagnostic loca const configFile = { path: "/a/b/tsconfig.json", - content: configFileContentWithComment + content: configFileContentWithComment, }; const host = createServerHost([file, libFile, configFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -658,14 +658,14 @@ describe("unittests:: tsserver:: projectErrors:: reports Options Diagnostic loca session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: { file: configFile.path, projectFileName: configFile.path, includeLinePosition: true } + arguments: { file: configFile.path, projectFileName: configFile.path, includeLinePosition: true }, }); host.writeFile(configFile.path, configFileContentWithoutCommentLine); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: { file: configFile.path, projectFileName: configFile.path, includeLinePosition: true } + arguments: { file: configFile.path, projectFileName: configFile.path, includeLinePosition: true }, }); baselineTsserverLogs("projectErrors", "when options change", session); }); @@ -686,7 +686,7 @@ describe("unittests:: tsserver:: projectErrors:: with config file change", () => session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: { file: aTs.path } + arguments: { file: aTs.path }, }); baselineTsserverLogs("projectErrors", `diagnostics after noUnusedLabels changes`, session); }); @@ -698,21 +698,21 @@ describe("unittests:: tsserver:: projectErrors:: with resolveJsonModule", () => path: `/user/username/projects/myproject/src/test.ts`, content: `import * as blabla from "./blabla.json"; declare var console: any; -console.log(blabla);` +console.log(blabla);`, }; const blabla: File = { path: `/user/username/projects/myproject/src/blabla.json`, - content: "{}" + content: "{}", }; const tsconfig: File = { path: `/user/username/projects/myproject/tsconfig.json`, content: JSON.stringify({ compilerOptions: { resolveJsonModule: true, - composite: true + composite: true, }, - include - }) + include, + }), }; const host = createServerHost([test, blabla, libFile, tsconfig]); @@ -723,7 +723,7 @@ console.log(blabla);` it("should not report incorrect error when json is root file found by tsconfig", () => { const { session, test } = createSessionForTest({ - include: ["./src/*.ts", "./src/*.json"] + include: ["./src/*.ts", "./src/*.json"], }); verifyGetErrRequest({ session, files: [test] }); baselineTsserverLogs("projectErrors", `should not report incorrect error when json is root file found by tsconfig`, session); @@ -731,7 +731,7 @@ console.log(blabla);` it("should report error when json is not root file found by tsconfig", () => { const { session, test } = createSessionForTest({ - include: ["./src/*.ts"] + include: ["./src/*.ts"], }); verifyGetErrRequest({ session, files: [test] }); baselineTsserverLogs("projectErrors", `should report error when json is not root file found by tsconfig`, session); @@ -742,16 +742,16 @@ describe("unittests:: tsserver:: projectErrors:: with npm install when", () => { function verifyNpmInstall(timeoutDuringPartialInstallation: boolean) { const main: File = { path: `/user/username/projects/myproject/src/main.ts`, - content: "import * as _a from '@angular/core';" + content: "import * as _a from '@angular/core';", }; const config: File = { path: `/user/username/projects/myproject/tsconfig.json`, - content: "{}" + content: "{}", }; // Move things from staging to node_modules without triggering watch const moduleFile: File = { path: `/user/username/projects/myproject/node_modules/@angular/core/index.d.ts`, - content: `export const y = 10;` + content: `export const y = 10;`, }; const projectFiles = [main, libFile, config]; const host = createServerHost(projectFiles); diff --git a/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts b/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts index e9f24f00bf8b0..121a59a925243 100644 --- a/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts +++ b/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts @@ -1,5 +1,7 @@ import * as ts from "../../_namespaces/ts"; -import { ensureErrorFreeBuild } from "../helpers/solutionBuilder"; +import { + ensureErrorFreeBuild, +} from "../helpers/solutionBuilder"; import { baselineTsserverLogs, createLoggerWithInMemoryLogs, @@ -20,14 +22,14 @@ describe("unittests:: tsserver:: with project references and compile on save", ( path: `${dependecyLocation}/fns.ts`, content: `export function fn1() { } export function fn2() { } -` +`, }; const dependencyConfig: File = { path: `${dependecyLocation}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, declarationDir: "../decls" }, - compileOnSave: true - }) + compileOnSave: true, + }), }; const usageTs: File = { path: `${usageLocation}/usage.ts`, @@ -37,14 +39,14 @@ export function fn2() { } } from '../decls/fns' fn1(); fn2(); -` +`, }; const usageConfig: File = { path: `${usageLocation}/tsconfig.json`, content: JSON.stringify({ compileOnSave: true, - references: [{ path: "../dependency" }] - }) + references: [{ path: "../dependency" }], + }), }; const localChange = "function fn3() { }"; @@ -60,19 +62,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage", session); }); @@ -84,19 +86,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage with project", session); }); @@ -107,26 +109,26 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage and local change to dependency", session); }); @@ -137,26 +139,26 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage with project and local change to dependency", session); }); @@ -167,7 +169,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -178,26 +180,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage and local change to usage", session); }); @@ -208,7 +210,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -219,26 +221,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage with project and local change to usage", session); }); @@ -249,26 +251,26 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage and change to depenedency", session); }); @@ -279,26 +281,26 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage with project and change to depenedency", session); }); @@ -309,7 +311,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -320,26 +322,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage and change to usage", session); }); @@ -350,7 +352,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -361,26 +363,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on usage with project and change to usage", session); }); @@ -395,19 +397,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency", session); }); @@ -419,19 +421,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency with project", session); }); @@ -442,26 +444,26 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency and local change to dependency", session); }); @@ -472,26 +474,26 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${localChange}`); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency with project and local change to dependency", session); }); @@ -502,7 +504,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -513,26 +515,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency and local change to usage", session); }); @@ -543,7 +545,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -554,26 +556,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency with project and local change to usage", session); }); @@ -584,26 +586,26 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency and change to dependency", session); }); @@ -614,26 +616,26 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); host.writeFile(dependencyTs.path, `${dependencyTs.content}${change}`); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency with project and change to dependency", session); }); @@ -644,7 +646,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -655,26 +657,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency and change to usage", session); }); @@ -685,7 +687,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -696,26 +698,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "when dependency project is not open and save on dependency with project and change to usage", session); }); @@ -732,19 +734,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage", session); }); @@ -756,19 +758,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage with project", session); }); @@ -779,7 +781,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -790,26 +792,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage and local change to dependency", session); }); @@ -820,7 +822,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -831,26 +833,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage and local change to dependency with file", session); }); @@ -861,7 +863,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -872,26 +874,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage and local change to usage", session); }); @@ -902,7 +904,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -913,26 +915,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage and local change to usage with project", session); }); @@ -943,7 +945,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -954,26 +956,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage and change to dependency", session); }); @@ -984,7 +986,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -995,26 +997,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage with project and change to dependency", session); }); @@ -1025,7 +1027,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -1036,26 +1038,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path } + arguments: { file: usageTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage and change to usage", session); }); @@ -1066,7 +1068,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -1077,25 +1079,25 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: usageTs.path, projectFileName: usageConfig.path } + arguments: { file: usageTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on usage with project and change to usage", session); }); @@ -1110,19 +1112,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with usage project", session); }); @@ -1133,7 +1135,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -1144,26 +1146,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with usage project and local change to dependency", session); }); @@ -1174,7 +1176,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -1185,26 +1187,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with usage project and local change to usage", session); }); @@ -1215,7 +1217,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -1226,26 +1228,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with usage project and change to dependency", session); }); @@ -1256,7 +1258,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -1267,26 +1269,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: usageConfig.path } + arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with usage project and change to usage", session); }); @@ -1301,19 +1303,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency", session); }); @@ -1325,19 +1327,19 @@ fn2(); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with project", session); }); @@ -1348,7 +1350,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -1359,26 +1361,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency and local change to dependency", session); }); @@ -1389,7 +1391,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -1400,26 +1402,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with project and local change to dependency", session); }); @@ -1430,7 +1432,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -1441,26 +1443,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency and local change to usage", session); }); @@ -1471,7 +1473,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -1482,26 +1484,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: localChange - } + insertString: localChange, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with project and local change to usage", session); }); @@ -1512,7 +1514,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -1523,26 +1525,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency and change to dependency", session); }); @@ -1553,7 +1555,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(dependencyTs.content); const location = toLocation(dependencyTs.content.length); @@ -1564,26 +1566,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with project and change to dependency", session); }); @@ -1594,7 +1596,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -1605,26 +1607,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency and change to usage", session); }); @@ -1635,7 +1637,7 @@ fn2(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path } + arguments: { file: dependencyTs.path }, }); const toLocation = protocolToLocation(usageTs.content); const location = toLocation(usageTs.content.length); @@ -1646,26 +1648,26 @@ fn2(); ...location, endLine: location.line, endOffset: location.offset, - insertString: change - } + insertString: change, + }, }); // Verify CompileOnSaveAffectedFileList session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveAffectedFileList, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify CompileOnSaveEmit session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); // Verify EmitOutput session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.EmitOutput, - arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path } + arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "save on dependency with project and change to usage", session); }); @@ -1681,9 +1683,9 @@ describe("unittests:: tsserver:: with project references and compile on save wit compileOnSave: true, compilerOptions: { module: "none", - composite: true - } - }) + composite: true, + }, + }), }; const buttonClass = `/user/username/projects/myproject/buttonClass`; const buttonConfig: File = { @@ -1691,10 +1693,10 @@ describe("unittests:: tsserver:: with project references and compile on save wit content: JSON.stringify({ extends: "../tsbase.json", compilerOptions: { - outFile: "Source.js" + outFile: "Source.js", }, - files: ["Source.ts"] - }) + files: ["Source.ts"], + }), }; const buttonSource: File = { path: `${buttonClass}/Source.ts`, @@ -1703,7 +1705,7 @@ describe("unittests:: tsserver:: with project references and compile on save wit public static myStaticFunction() { } } -}` +}`, }; const siblingClass = `/user/username/projects/myproject/SiblingClass`; @@ -1712,13 +1714,13 @@ describe("unittests:: tsserver:: with project references and compile on save wit content: JSON.stringify({ extends: "../tsbase.json", references: [{ - path: "../buttonClass/" + path: "../buttonClass/", }], compilerOptions: { - outFile: "Source.js" + outFile: "Source.js", }, - files: ["Source.ts"] - }) + files: ["Source.ts"], + }), }; const siblingSource: File = { path: `${siblingClass}/Source.ts`, @@ -1727,7 +1729,7 @@ describe("unittests:: tsserver:: with project references and compile on save wit public mySiblingFunction() { } } -}` +}`, }; const host = createServerHost([libFile, tsbaseJson, buttonConfig, buttonSource, siblingConfig, siblingSource], { useCaseSensitiveFileNames: true }); @@ -1741,9 +1743,9 @@ describe("unittests:: tsserver:: with project references and compile on save wit command: ts.server.protocol.CommandTypes.CompileOnSaveEmitFile, arguments: { file: siblingSource.path, - projectFileName: siblingConfig.path - } + projectFileName: siblingConfig.path, + }, }); baselineTsserverLogs("projectReferenceCompileOnSave", "compile on save emits same output as project build with external project", session); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/projectReferenceErrors.ts b/src/testRunner/unittests/tsserver/projectReferenceErrors.ts index 9b92d6c7cf0f7..088eaeae560cd 100644 --- a/src/testRunner/unittests/tsserver/projectReferenceErrors.ts +++ b/src/testRunner/unittests/tsserver/projectReferenceErrors.ts @@ -2,7 +2,9 @@ import { GetErrForProjectDiagnostics, verifyGetErrScenario, } from "../helpers/tsserver"; -import { File } from "../helpers/virtualFileSystemWithWatch"; +import { + File, +} from "../helpers/virtualFileSystemWithWatch"; describe("unittests:: tsserver:: with project references and error reporting", () => { const dependecyLocation = `/user/username/projects/myproject/dependency`; @@ -28,8 +30,8 @@ describe("unittests:: tsserver:: with project references and error reporting", ( usageProjectDiagnostics(), { project: dependencyTs, - files: [dependencyTs, usageTs] - } + files: [dependencyTs, usageTs], + }, ], syncDiagnostics: () => [ // Without project @@ -51,7 +53,7 @@ describe("unittests:: tsserver:: with project references and error reporting", ( getErrRequest: () => [usageTs, dependencyTs], getErrForProjectRequest: () => [ usageProjectDiagnostics(), - dependencyProjectDiagnostics() + dependencyProjectDiagnostics(), ], syncDiagnostics: () => [ // Without project @@ -74,11 +76,11 @@ export function fn2() { } // Introduce error for fnErr import in main // export function fnErr() { } // Error in dependency ts file -export let x: string = 10;` +export let x: string = 10;`, }; const dependencyConfig: File = { path: `${dependecyLocation}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { composite: true, declarationDir: "../decls" } }) + content: JSON.stringify({ compilerOptions: { composite: true, declarationDir: "../decls" } }), }; const usageTs: File = { path: `${usageLocation}/usage.ts`, @@ -90,14 +92,14 @@ export let x: string = 10;` fn1(); fn2(); fnErr(); -` +`, }; const usageConfig: File = { path: `${usageLocation}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true }, - references: [{ path: "../dependency" }] - }) + references: [{ path: "../dependency" }], + }), }; verifyUsageAndDependency("with module scenario", dependencyTs, dependencyConfig, usageTs, usageConfig); }); @@ -110,25 +112,25 @@ function fn2() { } // Introduce error for fnErr import in main // function fnErr() { } // Error in dependency ts file -let x: string = 10;` +let x: string = 10;`, }; const dependencyConfig: File = { path: `${dependecyLocation}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { composite: true, outFile: "../dependency.js" } }) + content: JSON.stringify({ compilerOptions: { composite: true, outFile: "../dependency.js" } }), }; const usageTs: File = { path: `${usageLocation}/usage.ts`, content: `fn1(); fn2(); fnErr(); -` +`, }; const usageConfig: File = { path: `${usageLocation}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, outFile: "../usage.js" }, - references: [{ path: "../dependency" }] - }) + references: [{ path: "../dependency" }], + }), }; verifyUsageAndDependency("with non module", dependencyTs, dependencyConfig, usageTs, usageConfig); }); diff --git a/src/testRunner/unittests/tsserver/projectReferences.ts b/src/testRunner/unittests/tsserver/projectReferences.ts index e9d07963f0cab..00b764b72f10a 100644 --- a/src/testRunner/unittests/tsserver/projectReferences.ts +++ b/src/testRunner/unittests/tsserver/projectReferences.ts @@ -1,5 +1,7 @@ import * as ts from "../../_namespaces/ts"; -import { solutionBuildWithBaseline } from "../helpers/solutionBuilder"; +import { + solutionBuildWithBaseline, +} from "../helpers/solutionBuilder"; import { baselineTsserverLogs, createHostWithSolutionBuild, @@ -45,26 +47,26 @@ describe("unittests:: tsserver:: with project references and tsbuild", () => { service.openExternalProjects([{ projectFileName: getTsBuildProjectFilePath(project, project), rootFiles: files.map(f => ({ fileName: f.path })), - options: {} + options: {}, }]); files.forEach(f => { const args: ts.server.protocol.FileRequestArgs = { file: f.path, - projectFileName: ts.endsWith(f.path, "tsconfig.json") ? f.path : undefined + projectFileName: ts.endsWith(f.path, "tsconfig.json") ? f.path : undefined, }; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SyntacticDiagnosticsSync, - arguments: args + arguments: args, }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: args + arguments: args, }); }); const containerProject = service.configuredProjects.get(containerConfig.path)!; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompilerOptionsDiagnosticsFull, - arguments: { projectFileName: containerProject.projectName } + arguments: { projectFileName: containerProject.projectName }, }); baselineTsserverLogs("projectReferences", `does not error on container only project`, session); }); @@ -76,7 +78,7 @@ describe("unittests:: tsserver:: with project references and tsbuild", () => { const myConstStart = protocolLocationFromSubstring(containerCompositeExec[1].content, "myConst"); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Rename, - arguments: { file: containerCompositeExec[1].path, ...myConstStart } + arguments: { file: containerCompositeExec[1].path, ...myConstStart }, }); baselineTsserverLogs("projectReferences", `can successfully find references with out option`, session); @@ -85,7 +87,7 @@ describe("unittests:: tsserver:: with project references and tsbuild", () => { it("ancestor and project ref management", () => { const tempFile: File = { path: `/user/username/projects/temp/temp.ts`, - content: "let x = 10" + content: "let x = 10", }; const host = createHostWithSolutionBuild(files.concat([tempFile]), [containerConfig.path]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -101,8 +103,8 @@ describe("unittests:: tsserver:: with project references and tsbuild", () => { command: ts.server.protocol.CommandTypes.Rename, arguments: { file: containerCompositeExec[1].path, - ...locationOfMyConst - } + ...locationOfMyConst, + }, }); // Open temp file and verify all projects alive @@ -128,15 +130,15 @@ describe("unittests:: tsserver:: with project references and tsbuild", () => { declarationMap: true, outDir: "../../out", baseUrl: "..", - disableSourceOfProjectReferenceRedirect + disableSourceOfProjectReferenceRedirect, }, - include: ["./**/*"] - }) + include: ["./**/*"], + }), }; const keyboardTs: File = { path: `${projectLocation}/src/common/input/keyboard.ts`, content: `function bar() { return "just a random function so .d.ts location doesnt match"; } -export function evaluateKeyboardEvent() { }` +export function evaluateKeyboardEvent() { }`, }; const keyboardTestTs: File = { path: `${projectLocation}/src/common/input/keyboard.test.ts`, @@ -144,7 +146,7 @@ export function evaluateKeyboardEvent() { }` function testEvaluateKeyboardEvent() { return evaluateKeyboardEvent(); } -` +`, }; const srcConfig: File = { path: `${projectLocation}/src/tsconfig.json`, @@ -158,13 +160,13 @@ function testEvaluateKeyboardEvent() { "common/*": ["./common/*"], }, tsBuildInfoFile: "../out/src.tsconfig.tsbuildinfo", - disableSourceOfProjectReferenceRedirect + disableSourceOfProjectReferenceRedirect, }, include: ["./**/*"], references: [ - { path: "./common" } - ] - }) + { path: "./common" }, + ], + }), }; const terminalTs: File = { path: `${projectLocation}/src/terminal.ts`, @@ -172,11 +174,11 @@ function testEvaluateKeyboardEvent() { function foo() { return evaluateKeyboardEvent(); } -` +`, }; const host = createHostWithSolutionBuild( [commonConfig, keyboardTs, keyboardTestTs, srcConfig, terminalTs, libFile], - [srcConfig.path] + [srcConfig.path], ); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); openFilesForSession([keyboardTs, terminalTs], session); @@ -184,7 +186,7 @@ function foo() { const searchStr = "evaluateKeyboardEvent"; session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(keyboardTs, searchStr) + arguments: protocolFileLocationFromSubstring(keyboardTs, searchStr), }); baselineTsserverLogs("projectReferences", `root file is file from referenced project${disableSourceOfProjectReferenceRedirect ? " and using declaration maps" : ""}`, session); } @@ -206,29 +208,29 @@ function foo() { outDir: "../dist/", rootDir: "../", baseUrl: "../", - paths: { "@ref/*": ["./dist/*"] } - } - }) + paths: { "@ref/*": ["./dist/*"] }, + }, + }), }; const aTs: File = { path: `/user/username/projects/myproject/compositea/a.ts`, - content: `import { b } from "@ref/compositeb/b";` + content: `import { b } from "@ref/compositeb/b";`, }; const a2Ts: File = { path: `/user/username/projects/myproject/compositea/a2.ts`, - content: `export const x = 10;` + content: `export const x = 10;`, }; const configB: File = { path: `/user/username/projects/myproject/compositeb/tsconfig.json`, - content: configA.content + content: configA.content, }; const bTs: File = { path: `/user/username/projects/myproject/compositeb/b.ts`, - content: "export function b() {}" + content: "export function b() {}", }; const bDts: File = { path: `/user/username/projects/myproject/dist/compositeb/b.d.ts`, - content: "export declare function b(): void;" + content: "export declare function b(): void;", }; const configC: File = { path: `/user/username/projects/myproject/compositec/tsconfig.json`, @@ -238,14 +240,14 @@ function foo() { outDir: "../dist/", rootDir: "../", baseUrl: "../", - paths: { "@ref/*": ["./*"] } + paths: { "@ref/*": ["./*"] }, }, - references: [{ path: "../compositeb" }] - }) + references: [{ path: "../compositeb" }], + }), }; const cTs: File = { path: `/user/username/projects/myproject/compositec/c.ts`, - content: aTs.content + content: aTs.content, }; const files = [libFile, aTs, a2Ts, configA, bDts, bTs, configB, cTs, configC]; const host = createServerHost(files); @@ -318,10 +320,10 @@ function foo() { textChanges: [{ newText: "\n", start: { line: 5, offset: 1 }, - end: { line: 5, offset: 1 } - }] - }] - } + end: { line: 5, offset: 1 }, + }], + }], + }, }); verifyGetErrRequest({ session, files: [aTest] }); baselineTsserverLogs("projectReferences", `monorepo like with symlinks ${scenario} and solution is ${alreadyBuilt ? "built" : "not built"}${extraOptions.preserveSymlinks ? " with preserveSymlinks" : ""}`, session); @@ -335,18 +337,18 @@ function foo() { outDir: "lib", rootDir: "src", composite: true, - ...extraOptions + ...extraOptions, }, include: ["src"], - ...(references ? { references: references.map(path => ({ path })) } : {}) - }) + ...(references ? { references: references.map(path => ({ path })) } : {}), + }), }; } function file(packageName: string, fileName: string, content: string): File { return { path: `/user/username/projects/myproject/packages/${packageName}/src/${fileName}`, - content + content, }; } @@ -356,38 +358,46 @@ function foo() { path: `/user/username/projects/myproject/packages/B/package.json`, content: JSON.stringify({ main: "lib/index.js", - types: "lib/index.d.ts" - }) + types: "lib/index.d.ts", + }), }, - aTest: file("A", "index.ts", `import { foo } from '${scope}b'; + aTest: file( + "A", + "index.ts", + `import { foo } from '${scope}b'; import { bar } from '${scope}b/lib/bar'; foo(); bar(); -`), +`, + ), bFoo: file("B", "index.ts", `export function foo() { }`), bBar: file("B", "bar.ts", `export function bar() { }`), bSymlink: { path: `/user/username/projects/myproject/node_modules/${scope}b`, - symLink: `/user/username/projects/myproject/packages/B` - } + symLink: `/user/username/projects/myproject/packages/B`, + }, })); verifySymlinkScenario(`when referencing file from subFolder${scope ? " with scoped package" : ""}`, () => ({ bPackageJson: { path: `/user/username/projects/myproject/packages/B/package.json`, - content: "{}" + content: "{}", }, - aTest: file("A", "test.ts", `import { foo } from '${scope}b/lib/foo'; + aTest: file( + "A", + "test.ts", + `import { foo } from '${scope}b/lib/foo'; import { bar } from '${scope}b/lib/bar/foo'; foo(); bar(); -`), +`, + ), bFoo: file("B", "foo.ts", `export function foo() { }`), bBar: file("B", "bar/foo.ts", `export function bar() { }`), bSymlink: { path: `/user/username/projects/myproject/node_modules/${scope}b`, - symLink: `/user/username/projects/myproject/packages/B` - } + symLink: `/user/username/projects/myproject/packages/B`, + }, })); } @@ -408,10 +418,10 @@ bar(); allowJs: true, emitDeclarationOnly: true, outDir: "lib", - rootDir: "src" + rootDir: "src", }, - include: ["src"] - }) + include: ["src"], + }), }; const compositePackageJson: File = { path: `/user/username/projects/myproject/packages/emit-composite/package.json`, @@ -419,15 +429,15 @@ bar(); name: "emit-composite", version: "1.0.0", main: "src/index.js", - typings: "lib/index.d.ts" - }) + typings: "lib/index.d.ts", + }), }; const compositeIndex: File = { path: `/user/username/projects/myproject/packages/emit-composite/src/index.js`, content: `const testModule = require('./testModule'); module.exports = { ...testModule -}` +}`, }; const compositeTestModule: File = { path: `/user/username/projects/myproject/packages/emit-composite/src/testModule.js`, @@ -438,24 +448,24 @@ module.exports = { } module.exports = { testCompositeFunction -}` +}`, }; const consumerConfig: File = { path: `/user/username/projects/myproject/packages/consumer/tsconfig.json`, content: JSON.stringify({ include: ["src"], - references: [{ path: "../emit-composite" }] - }) + references: [{ path: "../emit-composite" }], + }), }; const consumerIndex: File = { path: `/user/username/projects/myproject/packages/consumer/src/index.ts`, content: `import { testCompositeFunction } from 'emit-composite'; testCompositeFunction('why hello there'); -testCompositeFunction('why hello there', 42);` +testCompositeFunction('why hello there', 42);`, }; const symlink: SymLink = { path: `/user/username/projects/myproject/node_modules/emit-composite`, - symLink: `/user/username/projects/myproject/packages/emit-composite` + symLink: `/user/username/projects/myproject/packages/emit-composite`, }; const host = createServerHost([libFile, compositeConfig, compositePackageJson, compositeIndex, compositeTestModule, consumerConfig, consumerIndex, symlink], { useCaseSensitiveFileNames: true }); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); @@ -474,18 +484,18 @@ testCompositeFunction('why hello there', 42);` references: [ { path: "./compiler" }, { path: "./services" }, - ] - }) + ], + }), }; const compilerConfig: File = { path: `${solutionLocation}/compiler/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, - module: "none" + module: "none", }, - files: ["./types.ts", "./program.ts"] - }) + files: ["./types.ts", "./program.ts"], + }), }; const typesFile: File = { path: `${solutionLocation}/compiler/types.ts`, @@ -494,7 +504,7 @@ testCompositeFunction('why hello there', 42);` export interface Program { getSourceFiles(): string[]; } - }` + }`, }; const programFile: File = { path: `${solutionLocation}/compiler/program.ts`, @@ -504,26 +514,26 @@ testCompositeFunction('why hello there', 42);` getSourceFiles: () => [getSourceFile()] }; function getSourceFile() { return "something"; } - }` + }`, }; const servicesConfig: File = { path: `${solutionLocation}/services/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - composite: true + composite: true, }, files: ["./services.ts"], references: [ - { path: "../compiler" } - ] - }) + { path: "../compiler" }, + ], + }), }; const servicesFile: File = { path: `${solutionLocation}/services/services.ts`, content: ` namespace ts { const result = program.getSourceFiles(); - }` + }`, }; const files = [libFile, solution, compilerConfig, typesFile, programFile, servicesConfig, servicesFile, libFile]; @@ -535,14 +545,14 @@ testCompositeFunction('why hello there', 42);` // Shouldnt load more projects session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(programFile, "getSourceFile", { index: 1 }) + arguments: protocolFileLocationFromSubstring(programFile, "getSourceFile", { index: 1 }), }); // Find all references for getSourceFiles // Should load more projects session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(programFile, "getSourceFiles") + arguments: protocolFileLocationFromSubstring(programFile, "getSourceFiles"), }); baselineTsserverLogs("projectReferences", `finding local reference doesnt load ancestor/sibling projects`, session); }); @@ -559,38 +569,38 @@ testCompositeFunction('why hello there', 42);` { path: "./b" }, { path: "./c" }, { path: "./d" }, - ] - }) + ], + }), }; const aConfig: File = { path: `${solutionLocation}/a/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, - module: "none" + module: "none", }, - files: ["./index.ts"] - }) + files: ["./index.ts"], + }), }; const aFile: File = { path: `${solutionLocation}/a/index.ts`, content: ` export interface I { M(): void; - }` + }`, }; const bConfig: File = { path: `${solutionLocation}/b/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - composite: true + composite: true, }, files: ["./index.ts"], references: [ - { path: "../a" } - ] - }) + { path: "../a" }, + ], + }), }; const bFile: File = { path: `${solutionLocation}/b/index.ts`, @@ -599,20 +609,20 @@ testCompositeFunction('why hello there', 42);` export class B implements I { M() {} - }` + }`, }; const cConfig: File = { path: `${solutionLocation}/c/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - composite: true + composite: true, }, files: ["./index.ts"], references: [ - { path: "../b" } - ] - }) + { path: "../b" }, + ], + }), }; const cFile: File = { path: `${solutionLocation}/c/index.ts`, @@ -621,20 +631,20 @@ testCompositeFunction('why hello there', 42);` import { B } from "../b"; export const C: I = new B(); - ` + `, }; const dConfig: File = { path: `${solutionLocation}/d/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - composite: true + composite: true, }, files: ["./index.ts"], references: [ - { path: "../c" } - ] - }) + { path: "../c" }, + ], + }), }; const dFile: File = { path: `${solutionLocation}/d/index.ts`, @@ -643,7 +653,7 @@ testCompositeFunction('why hello there', 42);` import { C } from "../c"; export const D: I = C; - ` + `, }; const files = [libFile, solutionConfig, aConfig, aFile, bConfig, bFile, cConfig, cFile, dConfig, dFile, libFile]; @@ -654,14 +664,14 @@ testCompositeFunction('why hello there', 42);` // The first search will trigger project loads session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(bFile, "I", { index: 1 }) + arguments: protocolFileLocationFromSubstring(bFile, "I", { index: 1 }), }); // The second search starts with the projects already loaded // Formerly, this would search some projects multiple times session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(bFile, "I", { index: 1 }) + arguments: protocolFileLocationFromSubstring(bFile, "I", { index: 1 }), }); baselineTsserverLogs("projectReferences", `finding references in overlapping projects`, session); @@ -678,8 +688,8 @@ testCompositeFunction('why hello there', 42);` references: [ { path: "./api" }, { path: "./app" }, - ] - }) + ], + }), }; const apiConfig: File = { path: `${solutionLocation}/api/tsconfig.json`, @@ -690,21 +700,21 @@ testCompositeFunction('why hello there', 42);` rootDir: "src", }, include: ["src"], - references: [{ path: "../shared" }] - }) + references: [{ path: "../shared" }], + }), }; const apiFile: File = { path: `${solutionLocation}/api/src/server.ts`, content: `import * as shared from "../../shared/dist"; -${usage}` +${usage}`, }; const appConfig: File = { path: `${solutionLocation}/app/tsconfig.json`, - content: apiConfig.content + content: apiConfig.content, }; const appFile: File = { path: `${solutionLocation}/app/src/app.ts`, - content: apiFile.content + content: apiFile.content, }; const sharedConfig: File = { path: `${solutionLocation}/shared/tsconfig.json`, @@ -714,12 +724,12 @@ ${usage}` outDir: "dist", rootDir: "src", }, - include: ["src"] - }) + include: ["src"], + }), }; const sharedFile: File = { path: `${solutionLocation}/shared/src/index.ts`, - content: definition + content: definition, }; const host = createServerHost([libFile, solution, libFile, apiConfig, apiFile, appConfig, appFile, sharedConfig, sharedFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -728,7 +738,7 @@ ${usage}` // Find all references session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(apiFile, referenceTerm) + arguments: protocolFileLocationFromSubstring(apiFile, referenceTerm), }); baselineTsserverLogs("projectReferences", `special handling of localness ${scenario}`, session); @@ -739,21 +749,21 @@ ${usage}` "when using arrow function assignment", `export const dog = () => { };`, `shared.dog();`, - "dog" + "dog", ); verify( "when using arrow function as object literal property types", `export const foo = { bar: () => { } };`, `shared.foo.bar();`, - "bar" + "bar", ); verify( "when using object literal property", `export const foo = { baz: "BAZ" };`, `shared.foo.baz;`, - "baz" + "baz", ); verify( @@ -761,17 +771,16 @@ ${usage}` `export const foo = class { fly() {} };`, `const instance = new shared.foo(); instance.fly();`, - "fly" + "fly", ); - verify( // when using arrow function as object literal property is loaded through indirect assignment with original declaration local to project is treated as local "when using arrow function as object literal property", `const local = { bar: () => { } }; export const foo = local;`, `shared.foo.bar();`, - "bar" + "bar", ); }); @@ -785,8 +794,8 @@ export const foo = local;`, references: [ { path: "./compiler" }, { path: "./services" }, - ] - }) + ], + }), }; const compilerConfig: File = { path: `${solutionLocation}/compiler/tsconfig.json`, @@ -794,10 +803,10 @@ export const foo = local;`, compilerOptions: { composite: true, module: "none", - disableSolutionSearching: true + disableSolutionSearching: true, }, - files: ["./types.ts", "./program.ts"] - }) + files: ["./types.ts", "./program.ts"], + }), }; const typesFile: File = { path: `${solutionLocation}/compiler/types.ts`, @@ -806,7 +815,7 @@ export const foo = local;`, export interface Program { getSourceFiles(): string[]; } - }` + }`, }; const programFile: File = { path: `${solutionLocation}/compiler/program.ts`, @@ -816,26 +825,26 @@ export const foo = local;`, getSourceFiles: () => [getSourceFile()] }; function getSourceFile() { return "something"; } - }` + }`, }; const servicesConfig: File = { path: `${solutionLocation}/services/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - composite: true + composite: true, }, files: ["./services.ts"], references: [ - { path: "../compiler" } - ] - }) + { path: "../compiler" }, + ], + }), }; const servicesFile: File = { path: `${solutionLocation}/services/services.ts`, content: ` namespace ts { const result = program.getSourceFiles(); - }` + }`, }; const files = [libFile, solution, compilerConfig, typesFile, programFile, servicesConfig, servicesFile, libFile]; @@ -847,7 +856,7 @@ export const foo = local;`, // No new solutions/projects loaded session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(programFile, "getSourceFiles") + arguments: protocolFileLocationFromSubstring(programFile, "getSourceFiles"), }); baselineTsserverLogs("projectReferences", `with disableSolutionSearching solution and siblings are not loaded`, session); }); @@ -863,44 +872,44 @@ export const foo = local;`, const main: File = { path: `/user/username/projects/myproject/src/main.ts`, content: `import { foo } from 'helpers/functions'; -export { foo };` +export { foo };`, }; const helper: File = { path: `/user/username/projects/myproject/src/helpers/functions.ts`, - content: `export const foo = 1;` + content: `export const foo = 1;`, }; const mainDts: File = { path: `/user/username/projects/myproject/target/src/main.d.ts`, content: `import { foo } from 'helpers/functions'; export { foo }; -//# sourceMappingURL=main.d.ts.map` +//# sourceMappingURL=main.d.ts.map`, }; const mainDtsMap: File = { path: `/user/username/projects/myproject/target/src/main.d.ts.map`, - content: `{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/main.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAExC,OAAO,EAAC,GAAG,EAAC,CAAC"}` + content: `{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/main.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAExC,OAAO,EAAC,GAAG,EAAC,CAAC"}`, }; const helperDts: File = { path: `/user/username/projects/myproject/target/src/helpers/functions.d.ts`, content: `export declare const foo = 1; -//# sourceMappingURL=functions.d.ts.map` +//# sourceMappingURL=functions.d.ts.map`, }; const helperDtsMap: File = { path: `/user/username/projects/myproject/target/src/helpers/functions.d.ts.map`, - content: `{"version":3,"file":"functions.d.ts","sourceRoot":"","sources":["../../../src/helpers/functions.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,GAAG,IAAI,CAAC"}` + content: `{"version":3,"file":"functions.d.ts","sourceRoot":"","sources":["../../../src/helpers/functions.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,GAAG,IAAI,CAAC"}`, }; const tsconfigIndirect3: File = { path: `/user/username/projects/myproject/indirect3/tsconfig.json`, content: JSON.stringify({ compilerOptions: { - baseUrl: "../target/src/" + baseUrl: "../target/src/", }, - }) + }), }; const fileResolvingToMainDts: File = { path: `/user/username/projects/myproject/indirect3/main.ts`, content: `import { foo } from 'main'; foo; -export function bar() {}` +export function bar() {}`, }; const tsconfigSrcPath = `/user/username/projects/myproject/tsconfig-src.json`; const tsconfigPath = `/user/username/projects/myproject/tsconfig.json`; @@ -912,29 +921,38 @@ export function bar() {}` compilerOptions: { composite: true, outDir: "./target/", - baseUrl: "./src/" + baseUrl: "./src/", }, - include: ["./src/**/*"] - }) + include: ["./src/**/*"], + }), }; const tsconfig: File = { path: tsconfigPath, content: JSON.stringify({ - ... (solutionOptions ? { compilerOptions: solutionOptions } : {}), + ...(solutionOptions ? { compilerOptions: solutionOptions } : {}), references: configRefs.map(path => ({ path })), - files: solutionFiles || [] - }) + files: solutionFiles || [], + }), }; const dummyFile: File = { path: dummyFilePath, - content: "let a = 10;" + content: "let a = 10;", }; const host = createServerHost([ - tsconfigSrc, tsconfig, main, helper, - libFile, dummyFile, - mainDts, mainDtsMap, helperDts, helperDtsMap, - tsconfigIndirect3, fileResolvingToMainDts, - ...additionalFiles]); + tsconfigSrc, + tsconfig, + main, + helper, + libFile, + dummyFile, + mainDts, + mainDtsMap, + helperDts, + helperDtsMap, + tsconfigIndirect3, + fileResolvingToMainDts, + ...additionalFiles, + ]); const session = createSession(host, { canUseEvents: true, logger: createLoggerWithInMemoryLogs(host) }); const service = session.getProjectService(); service.openClientFile(main.path); @@ -970,7 +988,7 @@ export function bar() {}` // Find all refs session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(main, "foo", { index: 1 }) + arguments: protocolFileLocationFromSubstring(main, "foo", { index: 1 }), }).response as ts.server.protocol.ReferencesResponseBody; service.closeClientFile(main.path); @@ -982,7 +1000,7 @@ export function bar() {}` // Find all refs from dts include session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(fileResolvingToMainDts, "foo") + arguments: protocolFileLocationFromSubstring(fileResolvingToMainDts, "foo"), }).response as ts.server.protocol.ReferencesResponseBody; baselineTsserverLogs("projectReferences", input.scenario, session); } @@ -995,15 +1013,15 @@ export function bar() {}` composite: true, outDir: "./target/", baseUrl: "./src/", - ...optionsToExtend + ...optionsToExtend, }, files: [`./indirect${postfix}/main.ts`], - references: [{ path: "./tsconfig-src.json" }] - }) + references: [{ path: "./tsconfig-src.json" }], + }), }; const indirect: File = { path: `/user/username/projects/myproject/indirect${postfix}/main.ts`, - content: fileResolvingToMainDts.content + content: fileResolvingToMainDts.content, }; return { tsconfigIndirect, indirect }; } @@ -1081,14 +1099,14 @@ export function bar() {}` it("when the project found is not solution but references open file through project reference", () => { const ownMain: File = { path: `/user/username/projects/myproject/own/main.ts`, - content: fileResolvingToMainDts.content + content: fileResolvingToMainDts.content, }; verifySolutionScenario({ scenario: "solution with its own files and project found is not solution but references open file through project reference", solutionFiles: [`./own/main.ts`], solutionOptions: { outDir: "./target/", - baseUrl: "./src/" + baseUrl: "./src/", }, configRefs: ["./tsconfig-src.json"], additionalFiles: [ownMain], @@ -1099,7 +1117,7 @@ export function bar() {}` const ownMain: File = { path: `/user/username/projects/myproject/own/main.ts`, content: `import { bar } from 'main'; -bar;` +bar;`, }; const { tsconfigIndirect, indirect } = getIndirectProject("1"); const { tsconfigIndirect: tsconfigIndirect2, indirect: indirect2 } = getIndirectProject("2"); @@ -1108,7 +1126,7 @@ bar;` solutionFiles: [`./own/main.ts`], solutionOptions: { outDir: "./target/", - baseUrl: "./indirect1/" + baseUrl: "./indirect1/", }, configRefs: ["./tsconfig-indirect1.json", "./tsconfig-indirect2.json"], additionalFiles: [tsconfigIndirect, indirect, tsconfigIndirect2, indirect2, ownMain], @@ -1118,7 +1136,7 @@ bar;` it("disables looking into the child project if disableReferencedProjectLoad is set", () => { const ownMain: File = { path: `/user/username/projects/myproject/own/main.ts`, - content: fileResolvingToMainDts.content + content: fileResolvingToMainDts.content, }; verifyDisableReferencedProjectLoad({ scenario: "solution with its own files and disables looking into the child project if disableReferencedProjectLoad is set", @@ -1126,7 +1144,7 @@ bar;` solutionOptions: { outDir: "./target/", baseUrl: "./src/", - disableReferencedProjectLoad: true + disableReferencedProjectLoad: true, }, configRefs: ["./tsconfig-src.json"], additionalFiles: [ownMain], @@ -1137,7 +1155,7 @@ bar;` const ownMain: File = { path: `/user/username/projects/myproject/own/main.ts`, content: `import { bar } from 'main'; -bar;` +bar;`, }; const { tsconfigIndirect, indirect } = getIndirectProject("1", { disableReferencedProjectLoad: true }); verifyDisableReferencedProjectLoad({ @@ -1156,7 +1174,7 @@ bar;` const ownMain: File = { path: `/user/username/projects/myproject/own/main.ts`, content: `import { bar } from 'main'; -bar;` +bar;`, }; const { tsconfigIndirect, indirect } = getIndirectProject("1", { disableReferencedProjectLoad: true }); const { tsconfigIndirect: tsconfigIndirect2, indirect: indirect2 } = getIndirectProject("2"); @@ -1181,18 +1199,18 @@ bar;` content: JSON.stringify({ compilerOptions: { module: "none", - composite: true + composite: true, }, - exclude: ["temp"] - }) + exclude: ["temp"], + }), }; const class1: File = { path: `/user/username/projects/myproject/projects/project1/class1.ts`, - content: `class class1 {}` + content: `class class1 {}`, }; const class1Dts: File = { path: `/user/username/projects/myproject/projects/project1/class1.d.ts`, - content: `declare class class1 {}` + content: `declare class class1 {}`, }; const config2: File = { path: `/user/username/projects/myproject/projects/project2/tsconfig.json`, @@ -1200,16 +1218,16 @@ bar;` compilerOptions: { module: "none", composite: true, - ...(extendOptionsProject2 || {}) + ...(extendOptionsProject2 || {}), }, references: [ - { path: "../project1" } - ] - }) + { path: "../project1" }, + ], + }), }; const class2: File = { path: `/user/username/projects/myproject/projects/project2/class2.ts`, - content: `class class2 {}` + content: `class class2 {}`, }; const host = createServerHost([config1, class1, class1Dts, config2, class2, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -1310,22 +1328,22 @@ bar;` files: [], references: [ { path: "shared/src/library" }, - { path: "app/src/program" } - ] - }) + { path: "app/src/program" }, + ], + }), }; const sharedConfig: File = { path: `/user/username/projects/myproject/shared/src/library/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, - outDir: "../../bld/library" - } - }) + outDir: "../../bld/library", + }, + }), }; const sharedIndex: File = { path: `/user/username/projects/myproject/shared/src/library/index.ts`, - content: `export function foo() {}` + content: `export function foo() {}`, }; const sharedPackage: File = { path: `/user/username/projects/myproject/shared/package.json`, @@ -1333,8 +1351,8 @@ bar;` name: "shared", version: "1.0.0", main: "bld/library/index.js", - types: "bld/library/index.d.ts" - }) + types: "bld/library/index.d.ts", + }), }; const appConfig: File = { path: `/user/username/projects/myproject/app/src/program/tsconfig.json`, @@ -1342,24 +1360,24 @@ bar;` compilerOptions: { composite: true, outDir: "../../bld/program", - disableSourceOfProjectReferenceRedirect + disableSourceOfProjectReferenceRedirect, }, references: [ - { path: "../../../shared/src/library" } - ] - }) + { path: "../../../shared/src/library" }, + ], + }), }; const appBar: File = { path: `/user/username/projects/myproject/app/src/program/bar.ts`, - content: `import {foo} from "shared";` + content: `import {foo} from "shared";`, }; const appIndex: File = { path: `/user/username/projects/myproject/app/src/program/index.ts`, - content: `foo` + content: `foo`, }; const sharedSymlink: SymLink = { path: `/user/username/projects/myproject/node_modules/shared`, - symLink: `/user/username/projects/myproject/shared` + symLink: `/user/username/projects/myproject/shared`, }; const files = [solnConfig, sharedConfig, sharedIndex, sharedPackage, appConfig, appBar, appIndex, sharedSymlink, libFile]; const host = createServerHost(files); @@ -1378,9 +1396,9 @@ bar;` endLine: 1, endOffset: 4, errorCodes: [ts.Diagnostics.Cannot_find_name_0.code], - } + }, }); - baselineTsserverLogs("projectReferences", `auto import with referenced project${built ? " when built" : ""}${disableSourceOfProjectReferenceRedirect ? " with disableSourceOfProjectReferenceRedirect": ""}`, session); + baselineTsserverLogs("projectReferences", `auto import with referenced project${built ? " when built" : ""}${disableSourceOfProjectReferenceRedirect ? " with disableSourceOfProjectReferenceRedirect" : ""}`, session); } it("when project is built", () => { @@ -1398,14 +1416,14 @@ bar;` function getPackageAndFile(packageName: string, references?: string[], optionsToExtend?: ts.CompilerOptions): [file: File, config: File] { const file: File = { path: `/user/username/projects/myproject/${packageName}/src/file1.ts`, - content: `export const ${packageName}Const = 10;` + content: `export const ${packageName}Const = 10;`, }; const config: File = { path: `/user/username/projects/myproject/${packageName}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, ...optionsToExtend || {} }, - references: references?.map(path => ({ path: `../${path}` })) - }) + references: references?.map(path => ({ path: `../${path}` })), + }), }; return [file, config]; } @@ -1423,12 +1441,31 @@ bar;` const [noCoreRef2File, noCoreRef2Config] = getPackageAndFile("noCoreRef2"); const host = createServerHost([ - libFile, mainFile, mainConfig, coreFile, coreConfig, noCoreRef1File, noCoreRef1Config, - indirectFile, indirectConfig, coreRef1File, coreRef1Config, - indirectDisabledChildLoad1File, indirectDisabledChildLoad1Config, coreRef2File, coreRef2Config, - indirectDisabledChildLoad2File, indirectDisabledChildLoad2Config, coreRef3File, coreRef3Config, - refToCoreRef3File, refToCoreRef3Config, - indirectNoCoreRefFile, indirectNoCoreRefConfig, noCoreRef2File, noCoreRef2Config + libFile, + mainFile, + mainConfig, + coreFile, + coreConfig, + noCoreRef1File, + noCoreRef1Config, + indirectFile, + indirectConfig, + coreRef1File, + coreRef1Config, + indirectDisabledChildLoad1File, + indirectDisabledChildLoad1Config, + coreRef2File, + coreRef2Config, + indirectDisabledChildLoad2File, + indirectDisabledChildLoad2Config, + coreRef3File, + coreRef3Config, + refToCoreRef3File, + refToCoreRef3Config, + indirectNoCoreRefFile, + indirectNoCoreRefConfig, + noCoreRef2File, + noCoreRef2Config, ], { useCaseSensitiveFileNames: true }); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); openFilesForSession([mainFile, coreFile], session); @@ -1436,7 +1473,7 @@ bar;` // Find all refs in coreFile session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(coreFile, `coreConst`) + arguments: protocolFileLocationFromSubstring(coreFile, `coreConst`), }); baselineTsserverLogs("projectReferences", `when files from two projects are open and one project references`, session); }); @@ -1446,7 +1483,7 @@ bar;` path: `/user/username/projects/myproject/a/index.ts`, content: `import { B } from "../b/lib"; -const b: B = new B();` +const b: B = new B();`, }; const configB: File = { @@ -1457,21 +1494,21 @@ const b: B = new B();` "outDir": "lib", "composite": true } -}` +}`, }; const indexB: File = { path: `/user/username/projects/myproject/b/index.ts`, content: `export class B { M() {} -}` +}`, }; const helperB: File = { path: `/user/username/projects/myproject/b/helper.ts`, content: `import { B } from "."; -const b: B = new B();` +const b: B = new B();`, }; const dtsB: File = { @@ -1479,30 +1516,29 @@ const b: B = new B();` content: `export declare class B { M(): void; } -//# sourceMappingURL=index.d.ts.map` +//# sourceMappingURL=index.d.ts.map`, }; const dtsMapB: File = { path: `/user/username/projects/myproject/b/lib/index.d.ts.map`, - content: `{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;IACV,CAAC;CACJ"}` + content: `{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;IACV,CAAC;CACJ"}`, }; function baselineDisableReferencedProjectLoad( projectAlreadyLoaded: boolean, disableReferencedProjectLoad: boolean, disableSourceOfProjectReferenceRedirect: boolean, - dtsMapPresent: boolean) { - + dtsMapPresent: boolean, + ) { // Mangled to stay under windows path length limit - const subScenario = - `when proj ${projectAlreadyLoaded ? "is" : "is not"} loaded` + + const subScenario = `when proj ${projectAlreadyLoaded ? "is" : "is not"} loaded` + ` and refd proj loading is ${disableReferencedProjectLoad ? "disabled" : "enabled"}` + ` and proj ref redirects are ${disableSourceOfProjectReferenceRedirect ? "disabled" : "enabled"}` + ` and a decl map is ${dtsMapPresent ? "present" : "missing"}`; const compilerOptions: ts.CompilerOptions = { disableReferencedProjectLoad, disableSourceOfProjectReferenceRedirect, - composite: true + composite: true, }; it(subScenario, () => { @@ -1511,7 +1547,7 @@ const b: B = new B();` content: `{ "compilerOptions": ${JSON.stringify(compilerOptions)}, "references": [{ "path": "../b" }] - }` + }`, }; const host = createServerHost([configA, indexA, configB, indexB, helperB, dtsB, ...(dtsMapPresent ? [dtsMapB] : [])]); @@ -1520,39 +1556,40 @@ const b: B = new B();` session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.References, - arguments: protocolFileLocationFromSubstring(indexA, `B`, { index: 1 }) + arguments: protocolFileLocationFromSubstring(indexA, `B`, { index: 1 }), }); baselineTsserverLogs("projectReferences", `find refs to decl in other proj ${subScenario}`, session); }); } /* eslint-disable local/argument-trivia */ - - // Pre-loaded = A file from project B is already open when FAR is invoked - // dRPL = Project A has disableReferencedProjectLoad - // dSOPRR = Project A has disableSourceOfProjectReferenceRedirect - // Map = The declaration map file b/lib/index.d.ts.map exists - // B refs = files under directory b in which references are found (all scenarios find all references in a/index.ts) - - // Pre-loaded | dRPL | dSOPRR | Map | B state | Notes | B refs | Notes - // -----------+--------+--------+----------+------------+--------------+---------------------+--------------------------------------------------- - baselineDisableReferencedProjectLoad(true, true, true, true); // Pre-loaded | | index.ts, helper.ts | Via map and pre-loaded project - baselineDisableReferencedProjectLoad(true, true, true, false); // Pre-loaded | | lib/index.d.ts | Even though project is loaded - baselineDisableReferencedProjectLoad(true, true, false, true); // Pre-loaded | | index.ts, helper.ts | - baselineDisableReferencedProjectLoad(true, true, false, false); // Pre-loaded | | index.ts, helper.ts | - baselineDisableReferencedProjectLoad(true, false, true, true); // Pre-loaded | | index.ts, helper.ts | Via map and pre-loaded project - baselineDisableReferencedProjectLoad(true, false, true, false); // Pre-loaded | | lib/index.d.ts | Even though project is loaded - baselineDisableReferencedProjectLoad(true, false, false, true); // Pre-loaded | | index.ts, helper.ts | - baselineDisableReferencedProjectLoad(true, false, false, false); // Pre-loaded | | index.ts, helper.ts | - baselineDisableReferencedProjectLoad(false, true, true, true); // Not loaded | | lib/index.d.ts | Even though map is present - baselineDisableReferencedProjectLoad(false, true, true, false); // Not loaded | | lib/index.d.ts | - baselineDisableReferencedProjectLoad(false, true, false, true); // Not loaded | | index.ts | But not helper.ts, which is not referenced from a - baselineDisableReferencedProjectLoad(false, true, false, false); // Not loaded | | index.ts | But not helper.ts, which is not referenced from a - baselineDisableReferencedProjectLoad(false, false, true, true); // Loaded | Via map | index.ts, helper.ts | Via map and newly loaded project - baselineDisableReferencedProjectLoad(false, false, true, false); // Not loaded | | lib/index.d.ts | - baselineDisableReferencedProjectLoad(false, false, false, true); // Loaded | Via redirect | index.ts, helper.ts | - baselineDisableReferencedProjectLoad(false, false, false, false); // Loaded | Via redirect | index.ts, helper.ts | - + // dprint-ignore + { + // Pre-loaded = A file from project B is already open when FAR is invoked + // dRPL = Project A has disableReferencedProjectLoad + // dSOPRR = Project A has disableSourceOfProjectReferenceRedirect + // Map = The declaration map file b/lib/index.d.ts.map exists + // B refs = files under directory b in which references are found (all scenarios find all references in a/index.ts) + + // Pre-loaded | dRPL | dSOPRR | Map | B state | Notes | B refs | Notes + // -----------+--------+--------+----------+------------+--------------+---------------------+--------------------------------------------------- + baselineDisableReferencedProjectLoad(true, true, true, true); // Pre-loaded | | index.ts, helper.ts | Via map and pre-loaded project + baselineDisableReferencedProjectLoad(true, true, true, false); // Pre-loaded | | lib/index.d.ts | Even though project is loaded + baselineDisableReferencedProjectLoad(true, true, false, true); // Pre-loaded | | index.ts, helper.ts | + baselineDisableReferencedProjectLoad(true, true, false, false); // Pre-loaded | | index.ts, helper.ts | + baselineDisableReferencedProjectLoad(true, false, true, true); // Pre-loaded | | index.ts, helper.ts | Via map and pre-loaded project + baselineDisableReferencedProjectLoad(true, false, true, false); // Pre-loaded | | lib/index.d.ts | Even though project is loaded + baselineDisableReferencedProjectLoad(true, false, false, true); // Pre-loaded | | index.ts, helper.ts | + baselineDisableReferencedProjectLoad(true, false, false, false); // Pre-loaded | | index.ts, helper.ts | + baselineDisableReferencedProjectLoad(false, true, true, true); // Not loaded | | lib/index.d.ts | Even though map is present + baselineDisableReferencedProjectLoad(false, true, true, false); // Not loaded | | lib/index.d.ts | + baselineDisableReferencedProjectLoad(false, true, false, true); // Not loaded | | index.ts | But not helper.ts, which is not referenced from a + baselineDisableReferencedProjectLoad(false, true, false, false); // Not loaded | | index.ts | But not helper.ts, which is not referenced from a + baselineDisableReferencedProjectLoad(false, false, true, true); // Loaded | Via map | index.ts, helper.ts | Via map and newly loaded project + baselineDisableReferencedProjectLoad(false, false, true, false); // Not loaded | | lib/index.d.ts | + baselineDisableReferencedProjectLoad(false, false, false, true); // Loaded | Via redirect | index.ts, helper.ts | + baselineDisableReferencedProjectLoad(false, false, false, false); // Loaded | Via redirect | index.ts, helper.ts | + } /* eslint-enable local/argument-trivia */ }); }); diff --git a/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts b/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts index d4b0637994224..5f5ecb64d682e 100644 --- a/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts +++ b/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts @@ -27,11 +27,11 @@ export function fn2() { } export function fn3() { } export function fn4() { } export function fn5() { } -` +`, }; const dependencyConfig: File = { path: `${dependecyLocation}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { composite: true, declarationMap: true, declarationDir: "../decls" } }) + content: JSON.stringify({ compilerOptions: { composite: true, declarationMap: true, declarationDir: "../decls" } }), }; const mainTs: File = { @@ -49,23 +49,23 @@ fn2(); fn3(); fn4(); fn5(); -` +`, }; const mainConfig: File = { path: `${mainLocation}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, declarationMap: true }, - references: [{ path: "../dependency" }] - }) + references: [{ path: "../dependency" }], + }), }; const randomFile: File = { path: `/user/username/projects/myproject/random/random.ts`, - content: "let a = 10;" + content: "let a = 10;", }; const randomConfig: File = { path: `/user/username/projects/myproject/random/tsconfig.json`, - content: "{}" + content: "{}", }; const dtsLocation = `${dependecyDeclsLocation}/FnS.d.ts`; const dtsPath = dtsLocation.toLowerCase() as ts.Path; @@ -80,29 +80,29 @@ fn5(); host.readFile(dtsLocation)!.replace( "//# sourceMappingURL=FnS.d.ts.map", `export declare function fn6(): void; -//# sourceMappingURL=FnS.d.ts.map` - ) +//# sourceMappingURL=FnS.d.ts.map`, + ), ); } function changeDtsMapFile(host: TestServerHost) { host.writeFile( dtsMapLocation, - `{"version":3,"file":"FnS.d.ts","sourceRoot":"","sources":["../dependency/FnS.ts"],"names":[],"mappings":"AAAA,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,eAAO,MAAM,CAAC,KAAK,CAAC"}` + `{"version":3,"file":"FnS.d.ts","sourceRoot":"","sources":["../dependency/FnS.ts"],"names":[],"mappings":"AAAA,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,eAAO,MAAM,CAAC,KAAK,CAAC"}`, ); } function goToDefFromMainTs(fn: number): TestSessionRequest { return { command: ts.server.protocol.CommandTypes.DefinitionAndBoundSpan, - arguments: { file: mainTs.path, line: fn + 8, offset: 1 } + arguments: { file: mainTs.path, line: fn + 8, offset: 1 }, }; } function renameFromDependencyTs(fn: number): TestSessionRequest { return { command: ts.server.protocol.CommandTypes.Rename, - arguments: { file: dependencyTs.path, line: fn, offset: 17 } + arguments: { file: dependencyTs.path, line: fn, offset: 17 }, }; } @@ -148,7 +148,7 @@ fn5(); existingDocumentPositionMapper: ts.server.ScriptInfo["documentPositionMapper"], existingMapEqual: boolean, existingDocumentPositionMapperEqual: boolean, - skipMapPathInDtsInfo?: boolean + skipMapPathInDtsInfo?: boolean, ) { let sourceMapPath: ts.server.ScriptInfo["sourceMapFilePath"] | undefined; let dependencyMap: ts.server.ScriptInfo | undefined; @@ -229,9 +229,12 @@ fn5(); function createSessionWithoutProjectReferences(onHostCreate?: OnHostCreate) { const host = createHostWithSolutionBuild(files, [mainConfig.path]); // Erase project reference - host.writeFile(mainConfig.path, JSON.stringify({ - compilerOptions: { composite: true, declarationMap: true } - })); + host.writeFile( + mainConfig.path, + JSON.stringify({ + compilerOptions: { composite: true, declarationMap: true }, + }), + ); onHostCreate?.(host); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); return { host, session }; @@ -247,14 +250,17 @@ fn5(); function createSessionWithDisabledProjectReferences(onHostCreate?: OnHostCreate) { const host = createHostWithSolutionBuild(files, [mainConfig.path]); // Erase project reference - host.writeFile(mainConfig.path, JSON.stringify({ - compilerOptions: { - composite: true, - declarationMap: true, - disableSourceOfProjectReferenceRedirect: true - }, - references: [{ path: "../dependency" }] - })); + host.writeFile( + mainConfig.path, + JSON.stringify({ + compilerOptions: { + composite: true, + declarationMap: true, + disableSourceOfProjectReferenceRedirect: true, + }, + references: [{ path: "../dependency" }], + }), + ); onHostCreate?.(host); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); return { host, session }; @@ -275,8 +281,8 @@ fn5(); offset: 1, endLine: 14, endOffset: 1, - insertString: "const x = 10;" - } + insertString: "const x = 10;", + }, }); } @@ -289,12 +295,11 @@ fn5(); offset: 1, endLine: 6, endOffset: 1, - insertString: "const x = 10;" - } + insertString: "const x = 10;", + }, }); } - describe("from project that uses dependency: goToDef", () => { function setupWithActionWith(setup: (onHostCreate?: OnHostCreate) => ReturnType, onHostCreate: OnHostCreate | undefined) { const result = setup(onHostCreate); @@ -319,7 +324,7 @@ fn5(); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/can go to definition correctly", session); @@ -342,7 +347,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/usage file changes with timeout before request", session); }); @@ -360,7 +365,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/usage file changes", session); }); @@ -381,8 +386,8 @@ fn5(); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dts changes with timeout before request", session); }); @@ -399,8 +404,8 @@ fn5(); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dts changes", session); }); @@ -421,8 +426,8 @@ fn5(); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dtsMap changes with timeout before request", session); }); @@ -439,8 +444,8 @@ fn5(); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dtsMap changes", session); }); @@ -454,7 +459,7 @@ fn5(); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dtsMap not present", session); @@ -473,7 +478,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dtsMap created", session); @@ -489,7 +494,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dtsMap deleted", session); @@ -504,7 +509,7 @@ fn5(); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dts not present", session); @@ -523,7 +528,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dts created", session); @@ -539,7 +544,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configHasNoReference/dependency dts deleted", session); @@ -562,7 +567,7 @@ fn5(); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/can go to definition correctly", session); @@ -584,8 +589,8 @@ fn5(); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/usage file changes with timeout before request", session); }); @@ -602,8 +607,8 @@ fn5(); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/usage file changes", session); }); @@ -624,8 +629,8 @@ fn5(); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dts changes with timeout before request", session); }); @@ -643,7 +648,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dts changes", session); }); @@ -665,7 +670,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dtsMap changes with timeout before request", session); }); @@ -682,8 +687,8 @@ fn5(); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dtsMap changes", session); }); @@ -697,7 +702,7 @@ fn5(); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dtsMap not present", session); @@ -716,7 +721,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dtsMap created", session); @@ -732,7 +737,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dtsMap deleted", session); @@ -747,7 +752,7 @@ fn5(); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dts not present", session); @@ -766,7 +771,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dts created", session); @@ -782,7 +787,7 @@ fn5(); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency dts deleted", session); @@ -793,8 +798,11 @@ fn5(); // change // Make change, without rebuild of solution - host.writeFile(dependencyTs.path, `function fooBar() { } -${dependencyTs.content}`); + host.writeFile( + dependencyTs.path, + `function fooBar() { } +${dependencyTs.content}`, + ); host.runQueuedTimeoutCallbacks(); verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); @@ -805,7 +813,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency source changes with timeout before request", session); }); @@ -815,8 +823,11 @@ ${dependencyTs.content}`); // change // Make change, without rebuild of solution - host.writeFile(dependencyTs.path, `function fooBar() { } -${dependencyTs.content}`); + host.writeFile( + dependencyTs.path, + `function fooBar() { } +${dependencyTs.content}`, + ); // action verifyAllFnAction( @@ -825,7 +836,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/dependency source changes", session); }); @@ -840,7 +851,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/configWithReference/when projects are not built", session); @@ -863,7 +874,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/can go to definition correctly", session); @@ -886,7 +897,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/usage file changes with timeout before request", session); }); @@ -903,8 +914,8 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/usage file changes", session); }); @@ -926,7 +937,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dts changes with timeout before request", session); }); @@ -943,8 +954,8 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dts changes", session); }); @@ -966,7 +977,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dtsMap changes with timeout before request", session); }); @@ -984,7 +995,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dtsMap changes", session); }); @@ -998,7 +1009,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dtsMap not present", session); @@ -1017,7 +1028,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dtsMap created", session); @@ -1033,7 +1044,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dtsMap deleted", session); @@ -1048,7 +1059,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dts not present", session); @@ -1067,7 +1078,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dts created", session); @@ -1083,7 +1094,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs]); baselineTsserverLogs("projectReferencesSourcemap", "usageProject/disabledSourceRef/dependency dts deleted", session); @@ -1115,7 +1126,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/rename locations", session); @@ -1138,7 +1149,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/usage file changes with timeout before request", session); }); @@ -1156,7 +1167,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/usage file changes", session); }); @@ -1177,8 +1188,8 @@ ${dependencyTs.content}`); renameFromDependencyTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dts changes with timeout before request", session); }); @@ -1196,7 +1207,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dts changes", session); }); @@ -1217,8 +1228,8 @@ ${dependencyTs.content}`); renameFromDependencyTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dtsMap changes with timeout before request", session); }); @@ -1236,7 +1247,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dtsMap changes", session); }); @@ -1250,7 +1261,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dtsMap not present", session); @@ -1269,7 +1280,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dtsMap created", session); @@ -1285,7 +1296,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dtsMap deleted", session); @@ -1300,7 +1311,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dts not present", session); @@ -1319,7 +1330,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dts created", session); @@ -1335,7 +1346,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configHasNoReference/dependency dts deleted", session); @@ -1358,7 +1369,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/rename locations", session); @@ -1381,7 +1392,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/usage file changes with timeout before request", session); }); @@ -1398,8 +1409,8 @@ ${dependencyTs.content}`); renameFromDependencyTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/usage file changes", session); }); @@ -1421,7 +1432,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dts changes with timeout before request", session); }); @@ -1439,7 +1450,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dts changes", session); }); @@ -1461,7 +1472,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dtsMap changes with timeout before request", session); }); @@ -1479,7 +1490,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dtsMap changes", session); }); @@ -1493,7 +1504,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dtsMap not present", session); @@ -1512,7 +1523,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dtsMap created", session); @@ -1528,7 +1539,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dtsMap deleted", session); @@ -1543,7 +1554,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dts not present", session); @@ -1562,7 +1573,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dts created", session); @@ -1578,7 +1589,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency dts deleted", session); @@ -1592,8 +1603,14 @@ ${dependencyTs.content}`); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Change, arguments: { - file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } -`} + file: dependencyTs.path, + line: 1, + offset: 1, + endLine: 1, + endOffset: 1, + insertString: `function fooBar() { } +`, + }, }); host.runQueuedTimeoutCallbacks(); verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); @@ -1605,7 +1622,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency source changes with timeout before request", session); }); @@ -1618,18 +1635,24 @@ ${dependencyTs.content}`); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Change, arguments: { - file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } -`} + file: dependencyTs.path, + line: 1, + offset: 1, + endLine: 1, + endOffset: 1, + insertString: `function fooBar() { } +`, + }, }); // action verifyAllFnAction( session, renameFromDependencyTsWithDependencyChange, - /*existingDependencyMap*/ undefined, - /*existingDocumentPositionMapper*/ undefined, - /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDependencyMap*/ undefined, + /*existingDocumentPositionMapper*/ undefined, + /*existingMapEqual*/ false, + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/dependency source changes", session); }); @@ -1644,7 +1667,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/configWithReference/when projects are not built", session); @@ -1667,7 +1690,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/rename locations", session); @@ -1690,7 +1713,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/usage file changes with timeout before request", session); }); @@ -1708,7 +1731,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/usage file changes", session); }); @@ -1730,7 +1753,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dts changes with timeout before request", session); }); @@ -1748,7 +1771,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dts changes", session); }); @@ -1770,7 +1793,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dtsMap changes with timeout before request", session); }); @@ -1788,7 +1811,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dtsMap changes", session); }); @@ -1802,7 +1825,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dtsMap not present", session); @@ -1821,7 +1844,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dtsMap created", session); @@ -1837,7 +1860,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dtsMap deleted", session); @@ -1852,7 +1875,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dts not present", session); @@ -1871,7 +1894,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dts created", session); @@ -1887,7 +1910,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependency/disabledSourceRef/dependency dts deleted", session); @@ -1920,7 +1943,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { dependencyMap, documentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -1929,7 +1952,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/goToDef and rename locations", session); @@ -1953,7 +1976,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -1961,7 +1984,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/usage file changes with timeout before request", session); }); @@ -1980,7 +2003,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -1988,7 +2011,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/usage file changes", session); }); @@ -2010,7 +2033,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2018,7 +2041,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dts changes with timeout before request", session); }); @@ -2036,7 +2059,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2044,7 +2067,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dts changes", session); }); @@ -2066,7 +2089,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2075,7 +2098,7 @@ ${dependencyTs.content}`); dependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dtsMap changes with timeout before request", session); }); @@ -2093,7 +2116,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2102,7 +2125,7 @@ ${dependencyTs.content}`); dependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dtsMap changes", session); }); @@ -2116,7 +2139,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2124,7 +2147,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dtsMap not present", session); @@ -2143,7 +2166,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2152,7 +2175,7 @@ ${dependencyTs.content}`); newDependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dtsMap created", session); @@ -2168,7 +2191,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2177,7 +2200,7 @@ ${dependencyTs.content}`); newDependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dtsMap deleted", session); @@ -2191,7 +2214,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2199,7 +2222,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dts not present", session); @@ -2218,7 +2241,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2227,7 +2250,7 @@ ${dependencyTs.content}`); newDependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dts created", session); @@ -2243,7 +2266,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2251,7 +2274,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configHasNoReference/dependency dts deleted", session); @@ -2274,7 +2297,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2282,7 +2305,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/gotoDef and rename locations", session); @@ -2305,16 +2328,16 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, renameFromDependencyTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/usage file changes with timeout before request", session); }); @@ -2333,7 +2356,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2341,7 +2364,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/usage file changes", session); }); @@ -2362,16 +2385,16 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, renameFromDependencyTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dts changes with timeout before request", session); }); @@ -2389,7 +2412,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2397,7 +2420,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dts changes", session); }); @@ -2419,7 +2442,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2427,7 +2450,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dtsMap changes with timeout before request", session); }); @@ -2444,16 +2467,16 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, renameFromDependencyTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dtsMap changes", session); }); @@ -2467,7 +2490,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2475,7 +2498,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dtsMap not present", session); @@ -2495,7 +2518,7 @@ ${dependencyTs.content}`); documentPositionMapper, /*existingMapEqual*/ true, /*existingDocumentPositionMapperEqual*/ true, - /*skipMapPathInDtsInfo*/ true + /*skipMapPathInDtsInfo*/ true, ); verifyAllFnAction( session, @@ -2503,7 +2526,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dtsMap created", session); @@ -2520,7 +2543,7 @@ ${dependencyTs.content}`); documentPositionMapper, /*existingMapEqual*/ false, /*existingDocumentPositionMapperEqual*/ false, - /*skipMapPathInDtsInfo*/ true + /*skipMapPathInDtsInfo*/ true, ); verifyAllFnAction( session, @@ -2528,7 +2551,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dtsMap deleted", session); @@ -2543,7 +2566,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2551,7 +2574,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dts not present", session); @@ -2570,7 +2593,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2578,7 +2601,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dts created", session); @@ -2594,7 +2617,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2602,7 +2625,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency dts deleted", session); @@ -2616,8 +2639,14 @@ ${dependencyTs.content}`); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Change, arguments: { - file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } -`} + file: dependencyTs.path, + line: 1, + offset: 1, + endLine: 1, + endOffset: 1, + insertString: `function fooBar() { } +`, + }, }); host.runQueuedTimeoutCallbacks(); verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper); @@ -2629,7 +2658,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2637,7 +2666,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency source changes with timeout before request", session); }); @@ -2650,8 +2679,14 @@ ${dependencyTs.content}`); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Change, arguments: { - file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { } - `} + file: dependencyTs.path, + line: 1, + offset: 1, + endLine: 1, + endOffset: 1, + insertString: `function fooBar() { } + `, + }, }); // action @@ -2660,16 +2695,16 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, renameFromDependencyTsWithDependencyChange, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/dependency source changes", session); }); @@ -2684,7 +2719,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2692,7 +2727,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/configWithReference/when projects are not built", session); @@ -2715,7 +2750,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { dependencyMap, documentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2724,7 +2759,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/gotoDef and rename locations", session); @@ -2747,16 +2782,16 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, renameFromDependencyTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/usage file changes with timeout before request", session); }); @@ -2774,16 +2809,16 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, renameFromDependencyTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/usage file changes", session); }); @@ -2805,7 +2840,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2813,7 +2848,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dts changes with timeout before request", session); }); @@ -2831,7 +2866,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2839,7 +2874,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dts changes", session); }); @@ -2860,8 +2895,8 @@ ${dependencyTs.content}`); goToDefFromMainTs, dependencyMap, documentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ false, ); const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2869,8 +2904,8 @@ ${dependencyTs.content}`); renameFromDependencyTs, dependencyMap, newDocumentPositionMapper, - /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingMapEqual*/ true, + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dtsMap changes with timeout before request", session); }); @@ -2888,7 +2923,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2897,7 +2932,7 @@ ${dependencyTs.content}`); dependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dtsMap changes", session); }); @@ -2911,7 +2946,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2919,7 +2954,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dtsMap not present", session); @@ -2938,7 +2973,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2947,7 +2982,7 @@ ${dependencyTs.content}`); newDependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dtsMap created", session); @@ -2963,7 +2998,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -2972,7 +3007,7 @@ ${dependencyTs.content}`); newDependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dtsMap deleted", session); @@ -2987,7 +3022,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -2995,7 +3030,7 @@ ${dependencyTs.content}`); /*existingDependencyMap*/ undefined, /*existingDocumentPositionMapper*/ undefined, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dts not present", session); @@ -3014,7 +3049,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ false, - /*existingDocumentPositionMapperEqual*/ false + /*existingDocumentPositionMapperEqual*/ false, ); const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session); verifyAllFnAction( @@ -3023,7 +3058,7 @@ ${dependencyTs.content}`); newDependencyMap, newDocumentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dts created", session); @@ -3039,7 +3074,7 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyAllFnAction( session, @@ -3047,11 +3082,11 @@ ${dependencyTs.content}`); dependencyMap, documentPositionMapper, /*existingMapEqual*/ true, - /*existingDocumentPositionMapperEqual*/ true + /*existingDocumentPositionMapperEqual*/ true, ); verifyScriptInfoCollectionWith(session, [mainTs, dependencyTs]); baselineTsserverLogs("projectReferencesSourcemap", "dependencyAndUsage/disabledSourceRef/dependency dts deleted", session); }); }); }); -}); \ No newline at end of file +}); diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index 4745650a853d6..fa3203176d90e 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -32,7 +32,7 @@ describe("unittests:: tsserver:: projects::", () => { const file1: File = { path: "/a/b/commonFile1.ts", content: `/// - let x = y` + let x = y`, }; const host = createServerHost([file1, libFile]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -41,14 +41,14 @@ describe("unittests:: tsserver:: projects::", () => { // Two errors: CommonFile2 not found and cannot find name y session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); host.writeFile(commonFile2.path, commonFile2.content); host.runQueuedTimeoutCallbacks(); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: { file: file1.path } + arguments: { file: file1.path }, }); baselineTsserverLogs("projects", "handles the missing files added with tripleslash ref", session); }); @@ -59,7 +59,7 @@ describe("unittests:: tsserver:: projects::", () => { content: `{ "compilerOptions": {}, "files": ["${commonFile1.path}", "${commonFile2.path}"] - }` + }`, }; const files = [commonFile1, commonFile2, configFile]; const host = createServerHost(files); @@ -82,17 +82,17 @@ describe("unittests:: tsserver:: projects::", () => { const file1 = { path: "/a/b/f1.js", content: "let x =1;", - fileSize: 10 * 1024 * 1024 + fileSize: 10 * 1024 * 1024, }; const file2 = { path: "/a/b/f2.js", content: "let y =1;", - fileSize: 6 * 1024 * 1024 + fileSize: 6 * 1024 * 1024, }; const file3 = { path: "/a/b/f3.js", content: "let y =1;", - fileSize: 6 * 1024 * 1024 + fileSize: 6 * 1024 * 1024, }; const proj1name = "proj1", proj2name = "proj2", proj3name = "proj3"; @@ -112,12 +112,12 @@ describe("unittests:: tsserver:: projects::", () => { const file1 = { path: "/a/b/f1.js", content: "let x =1;", - fileSize: 50 * 1024 * 1024 + fileSize: 50 * 1024 * 1024, }; const file2 = { path: "/a/b/f2.js", content: "let x =1;", - fileSize: 100 + fileSize: 100, }; const projName = "proj1"; @@ -135,16 +135,16 @@ describe("unittests:: tsserver:: projects::", () => { it("external project including config file", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x =1;" + content: "let x =1;", }; const config1 = { path: "/a/b/tsconfig.json", content: JSON.stringify( { compilerOptions: {}, - files: ["f1.ts"] - } - ) + files: ["f1.ts"], + }, + ), }; const externalProjectName = "externalproject"; @@ -153,7 +153,7 @@ describe("unittests:: tsserver:: projects::", () => { projectService.openExternalProject({ rootFiles: toExternalFiles([file1.path, config1.path]), options: {}, - projectFileName: externalProjectName + projectFileName: externalProjectName, }); baselineTsserverLogs("projects", "external project including config file", projectService); @@ -162,16 +162,16 @@ describe("unittests:: tsserver:: projects::", () => { it("loose file included in config file (openClientFile)", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x =1;" + content: "let x =1;", }; const config1 = { path: "/a/b/tsconfig.json", content: JSON.stringify( { compilerOptions: {}, - files: ["f1.ts"] - } - ) + files: ["f1.ts"], + }, + ), }; const host = createServerHost([file1, config1]); @@ -183,16 +183,16 @@ describe("unittests:: tsserver:: projects::", () => { it("loose file included in config file (applyCodeChanges)", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x =1;" + content: "let x =1;", }; const config1 = { path: "/a/b/tsconfig.json", content: JSON.stringify( { compilerOptions: {}, - files: ["f1.ts"] - } - ) + files: ["f1.ts"], + }, + ), }; const host = createServerHost([file1, config1]); @@ -206,11 +206,11 @@ describe("unittests:: tsserver:: projects::", () => { it("reload regular file after closing", () => { const f1 = { path: "/a/b/app.ts", - content: "x." + content: "x.", }; const f2 = { path: "/a/b/lib.ts", - content: "let x: number;" + content: "let x: number;", }; const host = createServerHost([f1, f2, libFile]); @@ -221,14 +221,14 @@ describe("unittests:: tsserver:: projects::", () => { // should contain completions for string session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompletionInfo, - arguments: { file: f1.path, line: 1, offset: 3 } + arguments: { file: f1.path, line: 1, offset: 3 }, }); closeFilesForSession([f2], session); // should contain completions for string session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompletionInfo, - arguments: { file: f1.path, line: 1, offset: 3 } + arguments: { file: f1.path, line: 1, offset: 3 }, }); baselineTsserverLogs("projects", "reload regular file after closing", session); }); @@ -236,11 +236,11 @@ describe("unittests:: tsserver:: projects::", () => { it("clear mixed content file after closing", () => { const f1 = { path: "/a/b/app.ts", - content: " " + content: " ", }; const f2 = { path: "/a/b/lib.html", - content: "" + content: "", }; const host = createServerHost([f1, f2, libFile]); @@ -250,13 +250,13 @@ describe("unittests:: tsserver:: projects::", () => { session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompletionInfo, - arguments: { file: f1.path, line: 1, offset: 1 } + arguments: { file: f1.path, line: 1, offset: 1 }, }); closeFilesForSession([f2], session); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.CompletionInfo, - arguments: { file: f1.path, line: 1, offset: 1 } + arguments: { file: f1.path, line: 1, offset: 1 }, }); baselineTsserverLogs("projects", "clear mixed content file after closing", session); }); @@ -264,15 +264,15 @@ describe("unittests:: tsserver:: projects::", () => { it("changes in closed files are reflected in project structure", () => { const file1 = { path: "/a/b/f1.ts", - content: `export * from "./f2"` + content: `export * from "./f2"`, }; const file2 = { path: "/a/b/f2.ts", - content: `export let x = 1` + content: `export let x = 1`, }; const file3 = { path: "/a/c/f3.ts", - content: `export let y = 1;` + content: `export let y = 1;`, }; const host = createServerHost([file1, file2, file3]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -290,15 +290,15 @@ describe("unittests:: tsserver:: projects::", () => { it("deleted files affect project structure", () => { const file1 = { path: "/a/b/f1.ts", - content: `export * from "./f2"` + content: `export * from "./f2"`, }; const file2 = { path: "/a/b/f2.ts", - content: `export * from "../c/f3"` + content: `export * from "../c/f3"`, }; const file3 = { path: "/a/c/f3.ts", - content: `export let y = 1;` + content: `export let y = 1;`, }; const host = createServerHost([file1, file2, file3]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -314,11 +314,11 @@ describe("unittests:: tsserver:: projects::", () => { it("ignores files excluded by a custom safe type list", () => { const file1 = { path: "/a/b/f1.js", - content: "export let x = 5" + content: "export let x = 5", }; const office = { path: "/lib/duckquack-3.min.js", - content: "whoa do @@ not parse me ok thanks!!!" + content: "whoa do @@ not parse me ok thanks!!!", }; const host = createServerHost([file1, office, customTypesMap]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -335,15 +335,15 @@ describe("unittests:: tsserver:: projects::", () => { it("file with name constructor.js doesnt cause issue with typeAcquisition when safe type list", () => { const file1 = { path: "/a/b/f1.js", - content: `export let x = 5; import { s } from "s"` + content: `export let x = 5; import { s } from "s"`, }; const constructorFile = { path: "/a/b/constructor.js", - content: "const x = 10;" + content: "const x = 10;", }; const bliss = { path: "/a/b/bliss.js", - content: "export function is() { return true; }" + content: "export function is() { return true; }", }; const host = createServerHost([file1, libFile, constructorFile, bliss, customTypesMap]); let request: string | undefined; @@ -357,22 +357,25 @@ describe("unittests:: tsserver:: projects::", () => { }, attach: ts.noop, onProjectClosed: ts.noop, - globalTypingsCacheLocation: cachePath + globalTypingsCacheLocation: cachePath, }; const projectName = "project"; const projectService = createProjectService(host, { typingsInstaller, logger: createLoggerWithInMemoryLogs(host) }); projectService.openExternalProject({ projectFileName: projectName, options: {}, rootFiles: toExternalFiles([file1.path, constructorFile.path, bliss.path]) }); - assert.equal(request, JSON.stringify({ - projectName, - fileNames: [libFile.path, file1.path, constructorFile.path, bliss.path], - compilerOptions: { allowNonTsExtensions: true, noEmitForJsFiles: true }, - typeAcquisition: { include: ["blissfuljs"], exclude: [], enable: true }, - unresolvedImports: ["s"], - projectRootPath: "/", - cachePath, - kind: "discover" - })); + assert.equal( + request, + JSON.stringify({ + projectName, + fileNames: [libFile.path, file1.path, constructorFile.path, bliss.path], + compilerOptions: { allowNonTsExtensions: true, noEmitForJsFiles: true }, + typeAcquisition: { include: ["blissfuljs"], exclude: [], enable: true }, + unresolvedImports: ["s"], + projectRootPath: "/", + cachePath, + kind: "discover", + }), + ); const response = JSON.parse(request!); request = undefined; projectService.updateTypingsForProject({ @@ -392,31 +395,31 @@ describe("unittests:: tsserver:: projects::", () => { it("ignores files excluded by the default type list", () => { const file1 = { path: "/a/b/f1.js", - content: "export let x = 5" + content: "export let x = 5", }; const minFile = { path: "/c/moment.min.js", - content: "unspecified" + content: "unspecified", }; const kendoFile1 = { path: "/q/lib/kendo/kendo.all.min.js", - content: "unspecified" + content: "unspecified", }; const kendoFile2 = { path: "/q/lib/kendo/kendo.ui.min.js", - content: "unspecified" + content: "unspecified", }; const kendoFile3 = { path: "/q/lib/kendo-ui/kendo.all.js", - content: "unspecified" + content: "unspecified", }; const officeFile1 = { path: "/scripts/Office/1/excel-15.debug.js", - content: "unspecified" + content: "unspecified", }; const officeFile2 = { path: "/scripts/Office/1/powerpoint.js", - content: "unspecified" + content: "unspecified", }; const files = [file1, minFile, kendoFile1, kendoFile2, kendoFile3, officeFile1, officeFile2]; const host = createServerHost(files); @@ -440,7 +443,7 @@ describe("unittests:: tsserver:: projects::", () => { ["minimum", "minimum"], ["min", "min"], ["min.3.2", "min"], - ["jquery", "jquery"] + ["jquery", "jquery"], ]; for (const t of testData) { assert.equal(ts.removeMinAndVersionNumbers(t[0]), t[1], t[0]); @@ -450,15 +453,15 @@ describe("unittests:: tsserver:: projects::", () => { it("ignores files excluded by a legacy safe type list", () => { const file1 = { path: "/a/b/bliss.js", - content: "let x = 5" + content: "let x = 5", }; const file2 = { path: "/a/b/foo.js", - content: "" + content: "", }; const file3 = { path: "/a/b/Bacon.js", - content: "let y = 5" + content: "let y = 5", }; const host = createServerHost([file1, file2, file3, customTypesMap]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -476,15 +479,15 @@ describe("unittests:: tsserver:: projects::", () => { path: "/a/b/f1.ts", content: ` export * from "../c/f2"; - export * from "../d/f3";` + export * from "../d/f3";`, }; const file2 = { path: "/a/c/f2.ts", - content: "export let x = 1;" + content: "export let x = 1;", }; const file3 = { path: "/a/d/f3.ts", - content: "export let y = 1;" + content: "export let y = 1;", }; const host = createServerHost([file1, file2, file3]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -513,13 +516,13 @@ describe("unittests:: tsserver:: projects::", () => { const tsFile = { fileName: "/a/b/file1.ts", path: "/a/b/file1.ts", - content: "" + content: "", }; const jsFile = { path: "/a/b/file1.js", content: "var x = 10;", fileName: "/a/b/file1.js", - scriptKind: "JS" as const + scriptKind: "JS" as const, }; const host = createServerHost([]); @@ -535,15 +538,15 @@ describe("unittests:: tsserver:: projects::", () => { it("config file is deleted", () => { const file1 = { path: "/a/b/f1.ts", - content: "let x = 1;" + content: "let x = 1;", }; const file2 = { path: "/a/b/f2.ts", - content: "let y = 2;" + content: "let y = 2;", }; const config = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: {} }) + content: JSON.stringify({ compilerOptions: {} }), }; const host = createServerHost([file1, file2, config]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -560,29 +563,29 @@ describe("unittests:: tsserver:: projects::", () => { it("loading files with correct priority", () => { const f1 = { path: "/a/main.ts", - content: "let x = 1" + content: "let x = 1", }; const f2 = { path: "/a/main.js", - content: "var y = 1" + content: "var y = 1", }; const f3 = { path: "/main.js", - content: "var y = 1" + content: "var y = 1", }; const config = { path: "/a/tsconfig.json", content: JSON.stringify({ - compilerOptions: { allowJs: true } - }) + compilerOptions: { allowJs: true }, + }), }; const host = createServerHost([f1, f2, f3, config]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); projectService.setHostConfiguration({ extraFileExtensions: [ { extension: ".js", isMixedContent: false }, - { extension: ".html", isMixedContent: true } - ] + { extension: ".html", isMixedContent: true }, + ], }); projectService.openClientFile(f1.path); @@ -599,15 +602,15 @@ describe("unittests:: tsserver:: projects::", () => { it("tsconfig script block support", () => { const file1 = { path: "/a/b/f1.ts", - content: ` ` + content: ` `, }; const file2 = { path: "/a/b/f2.html", - content: `var hello = "hello";` + content: `var hello = "hello";`, }; const config = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: { allowJs: true } }) + content: JSON.stringify({ compilerOptions: { allowJs: true } }), }; const host = createServerHost([file1, file2, config]); const session = createSession(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -620,7 +623,7 @@ describe("unittests:: tsserver:: projects::", () => { // The configured project should now be updated to include html file session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { extraFileExtensions } + arguments: { extraFileExtensions }, }); // Open HTML file @@ -628,7 +631,7 @@ describe("unittests:: tsserver:: projects::", () => { fileName: file2.path, hasMixedContent: true, scriptKind: ts.ScriptKind.JS, - content: `var hello = "hello";` + content: `var hello = "hello";`, })); // Now HTML file is included in the project @@ -640,14 +643,15 @@ describe("unittests:: tsserver:: projects::", () => { position: 1, line: undefined!, offset: undefined!, - } + }, }); // Close HTML file projectService.applyChangesInOpenFiles( /*openFiles*/ undefined, /*changedFiles*/ undefined, - /*closedFiles*/[file2.path]); + /*closedFiles*/ [file2.path], + ); // HTML file is still included in project @@ -659,25 +663,24 @@ describe("unittests:: tsserver:: projects::", () => { position: 5, line: undefined!, offset: undefined!, - } + }, }); baselineTsserverLogs("projects", "tsconfig script block support", session); }); it("no tsconfig script block diagnostic errors", () => { - // #1. Ensure no diagnostic errors when allowJs is true const file1 = { path: "/a/b/f1.ts", - content: ` ` + content: ` `, }; const file2 = { path: "/a/b/f2.html", - content: `var hello = "hello";` + content: `var hello = "hello";`, }; const config1 = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: { allowJs: true } }) + content: JSON.stringify({ compilerOptions: { allowJs: true } }), }; const logger = createLoggerWithInMemoryLogs(/*host*/ undefined!); // Special @@ -689,14 +692,14 @@ describe("unittests:: tsserver:: projects::", () => { // #2. Ensure no errors when allowJs is false const config2 = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: { allowJs: false } }) + content: JSON.stringify({ compilerOptions: { allowJs: false } }), }; verfiy(config2, createServerHost([file1, file2, config2, libFile], { executingFilePath: ts.combinePaths(ts.getDirectoryPath(libFile.path), "tsc.js") })); // #3. Ensure no errors when compiler options aren't specified const config3 = { path: "/a/b/tsconfig.json", - content: JSON.stringify({}) + content: JSON.stringify({}), }; verfiy(config3, createServerHost([file1, file2, config3, libFile], { executingFilePath: ts.combinePaths(ts.getDirectoryPath(libFile.path), "tsc.js") })); @@ -704,7 +707,7 @@ describe("unittests:: tsserver:: projects::", () => { // #4. Ensure no errors when files are explicitly specified in tsconfig const config4 = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: { allowJs: true }, files: [file1.path, file2.path] }) + content: JSON.stringify({ compilerOptions: { allowJs: true }, files: [file1.path, file2.path] }), }; verfiy(config4, createServerHost([file1, file2, config4, libFile], { executingFilePath: ts.combinePaths(ts.getDirectoryPath(libFile.path), "tsc.js") })); @@ -712,7 +715,7 @@ describe("unittests:: tsserver:: projects::", () => { // #4. Ensure no errors when files are explicitly excluded in tsconfig const config5 = { path: "/a/b/tsconfig.json", - content: JSON.stringify({ compilerOptions: { allowJs: true }, exclude: [file2.path] }) + content: JSON.stringify({ compilerOptions: { allowJs: true }, exclude: [file2.path] }), }; const session = verfiy(config5, createServerHost([file1, file2, config5, libFile], { executingFilePath: ts.combinePaths(ts.getDirectoryPath(libFile.path), "tsc.js") })); @@ -724,7 +727,7 @@ describe("unittests:: tsserver:: projects::", () => { const session = createSession(host, { logger }); session.executeCommandSeq({ command: ts.server.protocol.CommandTypes.Configure, - arguments: { extraFileExtensions } + arguments: { extraFileExtensions }, }); openFilesForSession([file1], session); session.executeCommandSeq({ @@ -732,7 +735,7 @@ describe("unittests:: tsserver:: projects::", () => { arguments: { file: config.path, projectFileName: config.path, - } + }, }); return session; } @@ -741,11 +744,11 @@ describe("unittests:: tsserver:: projects::", () => { it("project structure update is deferred if files are not added or removed", () => { const file1 = { path: "/a/b/f1.ts", - content: `import {x} from "./f2"` + content: `import {x} from "./f2"`, }; const file2 = { path: "/a/b/f2.ts", - content: "export let x = 1" + content: "export let x = 1", }; const host = createServerHost([file1, file2]); const projectService = createProjectService(host, { logger: createLoggerWithInMemoryLogs(host) }); @@ -755,8 +758,9 @@ describe("unittests:: tsserver:: projects::", () => { projectService.applyChangesInOpenFiles( /*openFiles*/ undefined, - /*changedFiles*/ts.singleIterator({ fileName: file1.path, changes: ts.singleIterator({ span: ts.createTextSpan(0, file1.path.length), newText: "let y = 1" }) }), - /*closedFiles*/ undefined); + /*changedFiles*/ ts.singleIterator({ fileName: file1.path, changes: ts.singleIterator({ span: ts.createTextSpan(0, file1.path.length), newText: "let y = 1" }) }), + /*closedFiles*/ undefined, + ); projectService.ensureInferredProjectsUpToDate_TestOnly(); baselineTsserverLogs("projects", "project structure update is deferred if files are not added or removed", projectService); @@ -765,14 +769,13 @@ describe("unittests:: tsserver:: projects::", () => { it("files with mixed content are handled correctly", () => { const file1 = { path: "/a/b/f1.html", - content: `